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
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
//! `tagged_union::resolve` — the typescape's "exactly-one-Option" pattern,
//! lifted to one source of truth.
//!
//! Several CRD-facing types in this crate ([`crate::intent::Intent`],
//! [`crate::lifetime::Lifetime`], [`crate::export::ArtifactSource`],
//! [`crate::export::VectorChannel`], [`crate::encapsulates::EncapsulationKind`])
//! carry `N` `Option<T>` fields where exactly one is expected to be
//! populated on the wire. Each previously hand-rolled the same
//! `count() + if-let-chain + unreachable!()` body — four parallel tables
//! (the struct fields, an `is_some()` count array, an `if-let-else`
//! resolution chain, and any sibling projection like `IntentVariant::kind`)
//! kept coherent only by code review. The `unreachable!()` arm at the
//! bottom of every chain was a sentinel that fires at runtime if the
//! parallel tables ever drift.
//!
//! This module collapses the resolver to ONE typed sweep over an
//! `IntoIterator<Item = Option<V>>` of candidate variant projections.
//! Adding a new tagged-union variant is now ONE additional line at the
//! callsite — no `unreachable!()` arm to update, no parallel `is_some()`
//! count array to extend.
/// Outcome of [`resolve`] when the candidate list isn't exactly-one.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ResolveError {
/// No candidate was populated.
None,
/// More than one candidate was populated.
Many,
}
/// Resolve at most one populated variant from a candidate list.
///
/// Each item in `candidates` is the projected borrowed-variant view for
/// the corresponding `Option<T>` field — `None` when the field is unset,
/// `Some(V::Variant(...))` when set.
///
/// Returns the single populated variant, [`ResolveError::None`] when
/// none are populated, or [`ResolveError::Many`] when more than one are.
///
/// The body is one short-circuiting sweep — `Many` is returned as soon
/// as the second populated entry is seen, without scanning the rest.
pub fn resolve<V>(candidates: impl IntoIterator<Item = Option<V>>) -> Result<V, ResolveError> {
let mut found: Option<V> = None;
for candidate in candidates {
if candidate.is_some() {
if found.is_some() {
return Err(ResolveError::Many);
}
found = candidate;
}
}
found.ok_or(ResolveError::None)
}
/// Sibling error carriers on tagged-union `.variant()` sites all
/// project the two [`ResolveError`] arms onto the SAME closed-set
/// diagnostic shape — `Empty(&'static str)` for "no variant set"
/// (carrying the closed-set kind list so the operator diagnostic
/// names every candidate) and a payload-free `Ambiguous` for
/// "multiple variants set". This trait names that shared shape as
/// ONE typed contract; [`resolve_or_err`] then composes [`resolve`]
/// with the trait so each per-carrier `.map_err(|e| match e { ... })`
/// site collapses to a one-line typed dispatch.
///
/// Impls live at each error carrier's own module so the (diagnostic
/// message, closed-set list) pair stays owned by the carrier that
/// publishes it — the trait is the projection, not the message.
pub trait TaggedUnionError: Sized {
/// Construct the "no variant set" arm with the closed-set kind
/// list slash-joined into the diagnostic payload.
fn empty(kinds: &'static str) -> Self;
/// Construct the "multiple variants set" arm.
fn ambiguous() -> Self;
}
/// Resolve at most one populated variant, mapping the two
/// [`ResolveError`] arms onto the caller's typed carrier via
/// [`TaggedUnionError`]. The compound-lift primitive: sweep +
/// short-circuit + typed-error dispatch as ONE call.
///
/// Substrate primitive for the four sibling `Xxx::variant()` sites
/// on `ProcessSpec` (`Intent::variant`,
/// `EncapsulationKind::variant`, `ArtifactSource::variant`,
/// `VectorChannel::variant`) that previously restated the SAME
/// `.map_err(|e| match e { None => Empty(LIST), Many => Ambiguous })`
/// two-arm dispatch at each call site — every one of them a
/// byte-identical restatement of the (empty→list, many→ambiguous)
/// projection whose payload identity is strictly the carrier's own
/// diagnostic. A fifth sibling error carrier picks up the projection
/// through ONE `impl TaggedUnionError` block + ONE `resolve_or_err`
/// call site.
///
/// The [`Lifetime::variant`](crate::lifetime::Lifetime::variant)
/// site is DELIBERATELY not routed through this primitive — its
/// `ResolveError::None` arm resolves to a `Permanent` default
/// variant, not to an `Empty` typed error, so the projection shape
/// diverges at the None arm.
pub fn resolve_or_err<V, E: TaggedUnionError>(
candidates: impl IntoIterator<Item = Option<V>>,
kinds: &'static str,
) -> Result<V, E> {
resolve(candidates).map_err(|e| match e {
ResolveError::None => E::empty(kinds),
ResolveError::Many => E::ambiguous(),
})
}
/// Declare a sibling error carrier for a tagged-union `.variant()`
/// site — the enum + [`TaggedUnionError`] impl in ONE authoring
/// surface.
///
/// Every one of the four production `.variant()` sites on
/// `ProcessSpec` ([`crate::intent::Intent`],
/// [`crate::encapsulates::EncapsulationKind`],
/// [`crate::export::ArtifactSource`],
/// [`crate::export::VectorChannel`]) pre-lift restated the same
/// four-piece authoring shape by hand:
///
/// 1. `#[derive(Clone, Copy, Debug, thiserror::Error, PartialEq,
/// Eq)]` on the carrier — byte-identical across all four.
/// 2. A two-variant enum body (`Empty(&'static str)`, `Ambiguous`)
/// — structurally identical.
/// 3. Two `#[error(...)]` messages whose only per-carrier knob is a
/// noun-prefix (`"intent"`, `"encapsulation kind"`, ...) — every
/// other byte of the (`"has no variant set (one of {0}
/// required)"`, `"has multiple variants set; exactly one
/// required"`) tails was verbatim.
/// 4. A six-line `impl TaggedUnionError` whose two constructor
/// bodies re-projected `Self::Empty(kinds)` / `Self::Ambiguous`
/// onto each carrier's own typed variants.
///
/// The macro collapses (1) + (2) + (4) onto ONE call and takes the
/// two per-carrier operator-facing diagnostic literals as named
/// arguments so (3) stays visible at the callsite without re-authoring
/// the shared derive set or trait impl. A fifth sibling carrier
/// lands as ONE `declare_tagged_union_error!` invocation — no
/// re-authored `#[derive(...)]`, no re-authored two-variant enum
/// body, no re-authored `impl TaggedUnionError` block.
///
/// Emitted derives include `Copy` — the `Empty` arm carries only
/// a `&'static str` and the `Ambiguous` arm is payload-free, so
/// the carrier is always `Copy` regardless of caller.
///
/// # Example
///
/// ```ignore
/// declare_tagged_union_error! {
/// pub IntentError,
/// empty = "intent has no variant set (one of {0} required)",
/// ambiguous = "intent has multiple variants set; exactly one required",
/// }
/// ```
///
/// Expands to the enum + [`TaggedUnionError`] impl for
/// `IntentError`; the `Empty` arm carries the caller's closed-set
/// kind-list literal.
#[macro_export]
macro_rules! declare_tagged_union_error {
(
$(#[$attr:meta])*
$vis:vis $name:ident,
empty = $empty:literal,
ambiguous = $ambiguous:literal $(,)?
) => {
$(#[$attr])*
#[derive(
::std::clone::Clone,
::std::marker::Copy,
::std::fmt::Debug,
::thiserror::Error,
::std::cmp::PartialEq,
::std::cmp::Eq,
)]
$vis enum $name {
#[error($empty)]
Empty(&'static str),
#[error($ambiguous)]
Ambiguous,
}
impl $crate::tagged_union::TaggedUnionError for $name {
fn empty(kinds: &'static str) -> Self {
Self::Empty(kinds)
}
fn ambiguous() -> Self {
Self::Ambiguous
}
}
};
}
/// Declare the three-block impl stanza a tagged-union parent type
/// publishes to the substrate — inherent `.variant()` forwarder +
/// [`VariantSelector<Parent>`] impl on the sibling `Kind` +
/// [`TaggedUnion`] impl on the parent — in ONE authoring surface.
///
/// Every one of the four production `.variant()` sites on
/// `ProcessSpec` ([`crate::intent::Intent`],
/// [`crate::encapsulates::EncapsulationKind`],
/// [`crate::export::ArtifactSource`],
/// [`crate::export::VectorChannel`]) pre-lift restated the same three
/// impl blocks by hand:
///
/// 1. `impl $parent { pub fn variant(&self) -> Result<$variant<'_>, $err> { ... } }`
/// — a one-line delegation to the [`TaggedUnion::variant`] default
/// body, plus 5 lines of rustdoc cross-referencing the other three
/// sibling `.variant()` sites verbatim.
/// 2. `impl VariantSelector<$parent> for $kind { type Variant<'a> = $variant<'a>; fn select(...) { <$kind>::select(self, parent) } }`
/// — 6 lines whose only per-site knobs are (`$parent`, `$kind`,
/// `$variant`); the trait method body a straight delegation to the
/// inherent `<$kind>::select`.
/// 3. `impl TaggedUnion for $parent { type Kind = $kind; type Error = $err; const KIND_LIST = $kind_list; }`
/// — 3 associated-item assignments whose only per-site knobs are
/// the (`$kind`, `$err`, `$kind_list`) tuple.
///
/// The macro takes the (`$parent`, `$kind`, `$variant`, `$err`,
/// `$kind_list`) five-tuple as named arguments and emits all three
/// blocks. A fifth sibling tagged-union parent picks up all three
/// impls through ONE macro call — no re-authored inherent
/// `.variant()` forwarder, no re-authored `impl VariantSelector`
/// block, no re-authored `impl TaggedUnion` block.
///
/// The emitted inherent `.variant()`'s rustdoc is canonical (names
/// the substrate primitive, not the exact set of sibling sites) so
/// a fifth sibling doesn't drift the cross-ref count against reality
/// merely by existing.
///
/// # Example
///
/// ```ignore
/// declare_tagged_union_impls! {
/// parent = Intent,
/// kind = IntentKind,
/// variant = IntentVariant,
/// error = IntentError,
/// kind_list = INTENT_KIND_LIST,
/// }
/// ```
///
/// Expands to the inherent `Intent::variant`, the
/// `VariantSelector<Intent>` impl on `IntentKind`, and the
/// `TaggedUnion` impl on `Intent`.
#[macro_export]
macro_rules! declare_tagged_union_impls {
(
parent = $parent:ty,
kind = $kind:ty,
variant = $variant:ident,
error = $err:ty,
kind_list = $kind_list:expr $(,)?
) => {
impl $parent {
/// Resolve to exactly one variant. Errors on zero or many.
///
/// One-line inherent forwarder that delegates the sweep
/// body to the substrate primitive
/// [`crate::tagged_union::TaggedUnion::variant`] — every
/// production `.variant()` site on `ProcessSpec` dispatches
/// through this ONE default body so the resolve-sweep
/// pattern lives at ONE substrate site. The inherent surface
/// stays load-bearing so consumer callsites don't need
/// `use TaggedUnion`.
pub fn variant(&self) -> ::std::result::Result<$variant<'_>, $err> {
<Self as $crate::tagged_union::TaggedUnion>::variant(self)
}
/// Presence probe — does this tagged union carry a
/// populated slot addressed by the given closed-set
/// discriminator?
///
/// One-line inherent forwarder that delegates to the
/// substrate primitive
/// [`crate::tagged_union::TaggedUnion::has`] — every
/// closed-set-driven presence check on `ProcessSpec`
/// dispatches through this ONE default body so the
/// per-slot `spec.<field>.is_some()` pattern lives at
/// ONE substrate site. The inherent surface stays
/// load-bearing so consumer callsites don't need
/// `use TaggedUnion`.
pub fn has(&self, kind: $kind) -> bool {
<Self as $crate::tagged_union::TaggedUnion>::has(self, kind)
}
/// Closed-set-complement peer of [`Self::has`] — `true` iff
/// the given `kind` is MISSING (its slot on this tagged
/// union is empty).
///
/// One-line inherent forwarder that delegates to the
/// substrate primitive
/// [`crate::tagged_union::TaggedUnion::lacks`], whose
/// default body is `!self.has(kind)`. Every consumer whose
/// semantic reading is "the missing set contains this
/// kind" — a "still missing: <kind>" diagnostic, a
/// `lacks-<kind>` require-tag classifier arm, a
/// dependency-satisfaction check — reads
/// `parent.lacks(kind)` through the inherent surface
/// rather than negating `parent.has(kind)` at the call
/// site. The definitional complement law
/// `parent.lacks(kind) == !parent.has(kind)` and the
/// kind-scoped implication
/// `parent.lacks_only(kind) → parent.lacks(kind)` are
/// pinned as first-class typed invariants by the trait's
/// own default body and swept substrate-wide by
/// [`crate::tagged_union::assert_lacks_matches_has_complement`].
pub fn lacks(&self, kind: $kind) -> bool {
<Self as $crate::tagged_union::TaggedUnion>::lacks(self, kind)
}
/// Widened peer of [`Self::has`] — returns the borrowed
/// variant view addressed by `kind`, or `None` when the
/// matching slot is empty.
///
/// One-line inherent forwarder that delegates to the
/// substrate primitive
/// [`crate::tagged_union::TaggedUnion::find`], whose
/// default body is `kind.select(self)`. Every
/// closed-set-driven `kind.select(&parent)` callsite that
/// pre-lift required `use VariantSelector` at the caller
/// now reads `parent.find(kind)` through the inherent
/// surface, byte-for-byte symmetrical with
/// `parent.has(kind)`. The composition law
/// `parent.has(kind) == parent.find(kind).is_some()` is
/// pinned as a first-class typed invariant by the trait's
/// own `has` default body
/// (`self.find(kind).is_some()`), swept substrate-wide by
/// [`crate::tagged_union::assert_find_agrees_with_has`].
pub fn find(&self, kind: $kind) -> ::std::option::Option<$variant<'_>> {
<Self as $crate::tagged_union::TaggedUnion>::find(self, kind)
}
/// Closed-set-inversion peer of [`Self::has`] / [`Self::find`]
/// — returns the canonical-ordered `Vec` of populated
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL)
/// discriminators.
///
/// One-line inherent forwarder that delegates to the
/// substrate primitive
/// [`crate::tagged_union::TaggedUnion::populated_kinds`],
/// whose default body is
/// `<Kind as ClosedSet>::ALL.iter().copied().filter(|k|
/// self.has(*k)).collect()`. Every consumer that needs
/// to enumerate which slots on a tagged-union parent are
/// populated (an operator-facing "Ambiguous named
/// [Nix, Container]" diagnostic composed on the malformed
/// arm; a closed-set audit dispatcher; a
/// `populated-kind-count-<n>` require-tag classifier
/// prefix) reads `parent.populated_kinds()` through the
/// inherent surface, byte-for-byte symmetrical with
/// `parent.has(kind)` / `parent.find(kind)`. The
/// composition law
/// `parent.populated_kinds().contains(&k) == parent.has(k)`
/// is pinned as a first-class typed invariant by the
/// trait's own default body and swept substrate-wide by
/// [`crate::tagged_union::assert_populated_kinds_matches_has`].
pub fn populated_kinds(&self) -> ::std::vec::Vec<$kind> {
<Self as $crate::tagged_union::TaggedUnion>::populated_kinds(self)
}
/// Scalar cardinality peer of [`Self::populated_kinds`] —
/// the number of populated slots on this tagged union.
///
/// One-line inherent forwarder that delegates to the
/// substrate primitive
/// [`crate::tagged_union::TaggedUnion::populated_kind_count`],
/// whose default body is
/// `<Kind as ClosedSet>::ALL.iter().copied().filter(|k|
/// self.has(*k)).count()`. Every consumer that needs the
/// cardinality of the populated-slot set as a scalar
/// (a `populated-kind-count-<n>` require-tag classifier
/// prefix; a fast-path branch on the Ambiguous-arm side
/// that discriminates "well-formed" from "malformed with
/// N slots"; a coherence check that verifies "every
/// well-formed parent has exactly one populated slot")
/// reads `parent.populated_kind_count()` through the
/// inherent surface, byte-for-byte symmetrical with
/// `parent.has(kind)` / `parent.find(kind)` /
/// `parent.populated_kinds()`. The composition law
/// `parent.populated_kind_count() == parent.populated_kinds().len()`
/// is pinned as a first-class typed invariant by the
/// trait's own default body and swept substrate-wide by
/// [`crate::tagged_union::assert_populated_kind_count_matches_populated_kinds`].
pub fn populated_kind_count(&self) -> usize {
<Self as $crate::tagged_union::TaggedUnion>::populated_kind_count(self)
}
/// Closed-set-COMPLEMENT peer of [`Self::populated_kinds`]
/// — returns the canonical-ordered `Vec` of EMPTY
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL)
/// discriminators.
///
/// One-line inherent forwarder that delegates to the
/// substrate primitive
/// [`crate::tagged_union::TaggedUnion::missing_kinds`],
/// whose default body is
/// `<Kind as ClosedSet>::ALL.iter().copied().filter(|k|
/// !self.has(*k)).collect()`. Every consumer that needs to
/// enumerate which slots on a tagged-union parent are
/// ABSENT (an operator-facing "still missing [Nix, Container]"
/// diagnostic on the partially-populated arm; a coherence
/// check verifying "every process boundary carries every
/// intent slot"; a `missing-<kind>` require-tag classifier
/// arm) reads `parent.missing_kinds()` through the
/// inherent surface, byte-for-byte symmetrical with
/// `parent.populated_kinds()`. The partition law
/// `parent.populated_kinds() ∪ parent.missing_kinds() ==
/// ClosedSet::ALL` (with the two sets disjoint) is pinned
/// as a first-class typed invariant by the trait's own
/// default body and swept substrate-wide by
/// [`crate::tagged_union::assert_missing_kinds_matches_has`].
pub fn missing_kinds(&self) -> ::std::vec::Vec<$kind> {
<Self as $crate::tagged_union::TaggedUnion>::missing_kinds(self)
}
/// Scalar cardinality peer of [`Self::missing_kinds`] —
/// the number of EMPTY slots on this tagged union.
///
/// One-line inherent forwarder that delegates to the
/// substrate primitive
/// [`crate::tagged_union::TaggedUnion::missing_kind_count`],
/// whose default body is
/// `<Kind as ClosedSet>::ALL.iter().copied().filter(|k|
/// !self.has(*k)).count()`. Every consumer that needs the
/// cardinality of the missing-slot set as a scalar (a
/// `missing-kind-count-<n>` require-tag classifier prefix;
/// a fast-path branch that discriminates "well-formed"
/// from "N missing slots"; a coherence check that verifies
/// "every well-formed parent has exactly ALL.len() - 1
/// missing slots") reads `parent.missing_kind_count()`
/// through the inherent surface, byte-for-byte symmetrical
/// with `parent.populated_kind_count()`. The scalar
/// partition law `parent.populated_kind_count() +
/// parent.missing_kind_count() == <Kind as ClosedSet>::ALL.len()`
/// is pinned by the trait's own default body and swept
/// substrate-wide by
/// [`crate::tagged_union::assert_missing_kind_count_matches_missing_kinds`].
pub fn missing_kind_count(&self) -> usize {
<Self as $crate::tagged_union::TaggedUnion>::missing_kind_count(self)
}
/// Short-circuiting `Option<$kind>` peer of
/// [`Self::populated_kinds`] — the FIRST populated kind on
/// this tagged union in canonical
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL)
/// order, or `None` when no slot is populated.
///
/// One-line inherent forwarder that delegates to the
/// substrate primitive
/// [`crate::tagged_union::TaggedUnion::first_populated_kind`],
/// whose default body is
/// `<Kind as ClosedSet>::ALL.iter().copied().find(|k|
/// self.has(*k))`. Every consumer that needs the earliest
/// populated slot on a tagged-union parent as an
/// `Option<Kind>` (an operator-facing "Ambiguous, starting
/// at Nix" diagnostic on the malformed arm; a
/// `first-populated-<kind>` require-tag classifier arm; a
/// fast-path branch that discriminates "empty" from "any
/// populated") reads `parent.first_populated_kind()` through
/// the inherent surface, byte-for-byte symmetrical with
/// `parent.populated_kinds()` / `parent.has(kind)`. The
/// composition law `parent.first_populated_kind() ==
/// parent.populated_kinds().first().copied()` is pinned as
/// a first-class typed invariant by the trait's own default
/// body and swept substrate-wide by
/// [`crate::tagged_union::assert_first_populated_kind_matches_populated_kinds`].
pub fn first_populated_kind(&self) -> ::std::option::Option<$kind> {
<Self as $crate::tagged_union::TaggedUnion>::first_populated_kind(self)
}
/// Short-circuiting `Option<$kind>` peer of
/// [`Self::missing_kinds`] — the FIRST missing kind on this
/// tagged union in canonical
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL)
/// order, or `None` when EVERY slot is populated.
///
/// One-line inherent forwarder that delegates to the
/// substrate primitive
/// [`crate::tagged_union::TaggedUnion::first_missing_kind`],
/// whose default body is
/// `<Kind as ClosedSet>::ALL.iter().copied().find(|k|
/// !self.has(*k))`. Byte-for-byte symmetrical with
/// `parent.first_populated_kind()` under a negated
/// predicate; the two primitives PARTITION
/// `ClosedSet::ALL`'s earliest-element projection on the
/// (populated, missing) split. The composition law
/// `parent.first_missing_kind() ==
/// parent.missing_kinds().first().copied()` is pinned as a
/// first-class typed invariant by the trait's own default
/// body and swept substrate-wide by
/// [`crate::tagged_union::assert_first_missing_kind_matches_missing_kinds`].
pub fn first_missing_kind(&self) -> ::std::option::Option<$kind> {
<Self as $crate::tagged_union::TaggedUnion>::first_missing_kind(self)
}
/// Short-circuiting `Option<$kind>` peer of
/// [`Self::populated_kinds`] — the LAST populated kind on
/// this tagged union in canonical
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL)
/// order, or `None` when no slot is populated.
///
/// One-line inherent forwarder that delegates to the
/// substrate primitive
/// [`crate::tagged_union::TaggedUnion::last_populated_kind`],
/// whose default body is
/// `<Kind as ClosedSet>::ALL.iter().rev().copied().find(|k|
/// self.has(*k))` — a REVERSED closed-set walk composed
/// against `self.has` per variant that SHORT-CIRCUITS at
/// the latest match. Byte-for-byte time-reversed peer of
/// [`Self::first_populated_kind`]. Empty parent returns
/// `None`; well-formed parent returns `Some(k)` (the sole
/// populated slot); malformed (Ambiguous) parent returns
/// `Some(k)` where `k` is the LATEST populated slot in
/// canonical `ALL` order — the operator-diagnostic "and
/// last at Z" peer of the "Ambiguous, starting at Nix"
/// upgrade the first-projection enables. The composition
/// law `parent.last_populated_kind() ==
/// parent.populated_kinds().last().copied()` is pinned as
/// a first-class typed invariant by the trait's own default
/// body and swept substrate-wide by
/// [`crate::tagged_union::assert_last_populated_kind_matches_populated_kinds`].
pub fn last_populated_kind(&self) -> ::std::option::Option<$kind> {
<Self as $crate::tagged_union::TaggedUnion>::last_populated_kind(self)
}
/// Short-circuiting `Option<$kind>` peer of
/// [`Self::missing_kinds`] — the LAST missing kind on this
/// tagged union in canonical
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL)
/// order, or `None` when EVERY slot is populated.
///
/// One-line inherent forwarder that delegates to the
/// substrate primitive
/// [`crate::tagged_union::TaggedUnion::last_missing_kind`],
/// whose default body is
/// `<Kind as ClosedSet>::ALL.iter().rev().copied().find(|k|
/// !self.has(*k))`. Byte-for-byte time-reversed peer of
/// [`Self::first_missing_kind`] under an identical negated
/// predicate. The two primitives PARTITION
/// `ClosedSet::ALL`'s endpoint projection on the (populated,
/// missing) × (earliest, latest) product together with the
/// `first_*` peers — every endpoint-addressable coherence
/// check reads ONE of the four at ONE call site without
/// allocating a `Vec<$kind>`. The composition law
/// `parent.last_missing_kind() ==
/// parent.missing_kinds().last().copied()` is pinned as a
/// first-class typed invariant by the trait's own default
/// body and swept substrate-wide by
/// [`crate::tagged_union::assert_last_missing_kind_matches_missing_kinds`].
pub fn last_missing_kind(&self) -> ::std::option::Option<$kind> {
<Self as $crate::tagged_union::TaggedUnion>::last_missing_kind(self)
}
/// Exactly-one-populated `Option<$kind>` peer of
/// [`Self::populated_kinds`] — `Some(k)` iff `k` is the
/// SOLE populated kind on this tagged union, else `None`.
///
/// One-line inherent forwarder that delegates to the
/// substrate primitive
/// [`crate::tagged_union::TaggedUnion::unique_populated_kind`],
/// whose default body is a two-step-short-circuit walk
/// over `<Kind as ClosedSet>::ALL` returning `Some(k)`
/// only when EXACTLY ONE `has(k)` is `true`. Every
/// consumer that needs the resolved kind identity on the
/// well-formed arm (without paying for the borrowed
/// variant view [`Self::variant`] returns, and without
/// materializing the [`Self::Error`] carrier on the
/// empty / malformed arms) reads
/// `parent.unique_populated_kind()` through the inherent
/// surface — `Some(k)` names well-formed exactly-one,
/// `None` collapses BOTH the empty AND the malformed
/// (ambiguous) arms.
///
/// The composition laws
/// `parent.unique_populated_kind().is_some() ==
/// (parent.populated_kind_count() == 1)` and (on the
/// `Some` arm) `parent.unique_populated_kind() ==
/// parent.first_populated_kind() ==
/// parent.last_populated_kind()` are pinned as first-
/// class typed invariants by the trait's own default body
/// and swept substrate-wide by
/// [`crate::tagged_union::assert_unique_populated_kind_matches_populated_kinds`].
pub fn unique_populated_kind(&self) -> ::std::option::Option<$kind> {
<Self as $crate::tagged_union::TaggedUnion>::unique_populated_kind(self)
}
/// Exactly-one-missing `Option<$kind>` peer of
/// [`Self::missing_kinds`] — `Some(k)` iff `k` is the
/// SOLE missing kind on this tagged union, else `None`.
///
/// One-line inherent forwarder that delegates to the
/// substrate primitive
/// [`crate::tagged_union::TaggedUnion::unique_missing_kind`],
/// whose default body is a two-step-short-circuit walk
/// over `<Kind as ClosedSet>::ALL` under a NEGATED `has`
/// predicate returning `Some(k)` only when EXACTLY ONE
/// `!has(k)` is `true`. Byte-for-byte symmetrical with
/// `parent.unique_populated_kind()` under complement; on
/// tagged unions with `<Kind as ClosedSet>::ALL.len() >
/// 2` the primitive returns `Some` only on the near-
/// saturation arm (`ALL.len() - 1` populated).
///
/// The composition laws
/// `parent.unique_missing_kind().is_some() ==
/// (parent.missing_kind_count() == 1)` and (on the
/// `Some` arm) `parent.unique_missing_kind() ==
/// parent.first_missing_kind() ==
/// parent.last_missing_kind()` are pinned as first-class
/// typed invariants by the trait's own default body and
/// swept substrate-wide by
/// [`crate::tagged_union::assert_unique_missing_kind_matches_missing_kinds`].
pub fn unique_missing_kind(&self) -> ::std::option::Option<$kind> {
<Self as $crate::tagged_union::TaggedUnion>::unique_missing_kind(self)
}
/// Boolean cardinality-endpoint peer of [`Self::populated_kinds`]
/// — `true` iff NO slot on this tagged union is populated.
///
/// One-line inherent forwarder that delegates to the
/// substrate primitive
/// [`crate::tagged_union::TaggedUnion::is_empty`], whose
/// default body is `!<Kind as ClosedSet>::ALL.iter().any(|k|
/// self.has(k))` — a short-circuiting closed-set walk that
/// returns `true` iff every point-probe returns `false`,
/// WITHOUT materializing the `Vec` `populated_kinds` would
/// build. Every consumer that needs the zero-arm Boolean
/// projection of the populated cardinality (a fast-path
/// guard on "any content at all"; an operator-facing
/// "carrier missing content" diagnostic on the `Empty` arm;
/// an `is-empty` require-tag classifier arm) reads
/// `parent.is_empty()` through the inherent surface, byte-
/// for-byte symmetrical with `parent.is_saturated()` under
/// the (populated, missing) complement axis. The
/// composition law
/// `parent.is_empty() == (parent.populated_kind_count() == 0)`
/// is pinned as a first-class typed invariant by the
/// trait's own default body and swept substrate-wide by
/// [`crate::tagged_union::assert_is_empty_matches_populated_kind_count`].
pub fn is_empty(&self) -> bool {
<Self as $crate::tagged_union::TaggedUnion>::is_empty(self)
}
/// Boolean cardinality-endpoint peer of [`Self::missing_kinds`]
/// — `true` iff EVERY slot on this tagged union is populated
/// (i.e. the missing set is empty).
///
/// One-line inherent forwarder that delegates to the
/// substrate primitive
/// [`crate::tagged_union::TaggedUnion::is_saturated`], whose
/// default body is `<Kind as ClosedSet>::ALL.iter().all(|k|
/// self.has(k))` — a short-circuiting closed-set walk that
/// returns `true` iff every point-probe returns `true`,
/// WITHOUT materializing the `Vec` `missing_kinds` would
/// build. Every consumer that needs the zero-arm Boolean
/// projection of the missing cardinality (a fast-path guard
/// discriminating "over-populated" from "well-formed or
/// partial"; an operator-facing "over-populated carrier"
/// diagnostic; an `is-saturated` require-tag classifier
/// arm) reads `parent.is_saturated()` through the inherent
/// surface, byte-for-byte symmetrical with
/// `parent.is_empty()` under the (populated, missing)
/// complement axis. The composition law
/// `parent.is_saturated() == (parent.missing_kind_count() == 0)`
/// is pinned as a first-class typed invariant by the
/// trait's own default body and swept substrate-wide by
/// [`crate::tagged_union::assert_is_saturated_matches_missing_kind_count`].
pub fn is_saturated(&self) -> bool {
<Self as $crate::tagged_union::TaggedUnion>::is_saturated(self)
}
/// Boolean cardinality "at-least-one" peer of
/// [`Self::populated_kinds`] — `true` iff AT LEAST ONE slot
/// on this tagged union is populated (the populated set is
/// NON-empty).
///
/// One-line inherent forwarder that delegates to the
/// substrate primitive
/// [`crate::tagged_union::TaggedUnion::has_any_populated_kind`],
/// whose default body is `<Kind as ClosedSet>::ALL.iter().any(|k|
/// self.has(k))` — a short-circuiting closed-set walk that
/// returns `true` at the FIRST populated slot, WITHOUT
/// materializing the `Vec` `populated_kinds` would build.
/// Every consumer that needs the ≥ 1 halfspace on the
/// populated cardinality (a boundary-progress "any content
/// at all" diagnostic; an `is-non-empty` require-tag
/// classifier arm; a fast-path branch discriminating "some
/// populated" from "all missing") reads
/// `parent.has_any_populated_kind()` through the inherent
/// surface — byte-for-byte definitional complement of
/// `parent.is_empty()`, no readerly inversion at the
/// callsite, and byte-for-byte symmetrical with
/// `parent.has_any_missing_kind()` under the (populated,
/// missing) complement axis. The composition law
/// `parent.has_any_populated_kind() == !parent.is_empty()`
/// is pinned as a first-class typed invariant by the
/// trait's own default body and swept substrate-wide by
/// [`crate::tagged_union::assert_has_any_populated_kind_matches_populated_kind_count`].
pub fn has_any_populated_kind(&self) -> bool {
<Self as $crate::tagged_union::TaggedUnion>::has_any_populated_kind(self)
}
/// Boolean cardinality "at-least-one" peer of
/// [`Self::missing_kinds`] — `true` iff AT LEAST ONE slot on
/// this tagged union is missing (the missing set is
/// NON-empty).
///
/// One-line inherent forwarder that delegates to the
/// substrate primitive
/// [`crate::tagged_union::TaggedUnion::has_any_missing_kind`],
/// whose default body is `<Kind as ClosedSet>::ALL.iter().any(|k|
/// !self.has(k))` — a short-circuiting closed-set walk under
/// a negated `has` predicate that returns `true` at the
/// FIRST missing slot, WITHOUT materializing the `Vec`
/// `missing_kinds` would build. Every consumer that needs
/// the ≥ 1 halfspace on the missing cardinality (an
/// operator-facing "not fully populated" diagnostic; a
/// `has-any-missing-kind` require-tag classifier arm; a
/// fast-path branch discriminating "any slot still absent"
/// from "over-populated / saturated") reads
/// `parent.has_any_missing_kind()` through the inherent
/// surface — byte-for-byte definitional complement of
/// `parent.is_saturated()`, no readerly inversion at the
/// callsite, and byte-for-byte symmetrical with
/// `parent.has_any_populated_kind()` under the (populated,
/// missing) complement axis. The composition law
/// `parent.has_any_missing_kind() == !parent.is_saturated()`
/// is pinned as a first-class typed invariant by the
/// trait's own default body and swept substrate-wide by
/// [`crate::tagged_union::assert_has_any_missing_kind_matches_missing_kind_count`].
pub fn has_any_missing_kind(&self) -> bool {
<Self as $crate::tagged_union::TaggedUnion>::has_any_missing_kind(self)
}
/// Boolean cardinality-mid-endpoint peer of
/// [`Self::unique_populated_kind`] — `true` iff EXACTLY ONE
/// slot on this tagged union is populated.
///
/// One-line inherent forwarder that delegates to the
/// substrate primitive
/// [`crate::tagged_union::TaggedUnion::has_unique_populated_kind`],
/// whose default body is `self.unique_populated_kind().is_some()`
/// — the Boolean projection of the two-step-short-circuit
/// closed-set walk `unique_populated_kind` already performs,
/// without paying for a `Vec<$kind>` allocation on any arm.
/// Every consumer that needs the exactly-one-populated arm
/// as a `bool` (a fast-path branch on the well-formed arm
/// that skips the borrowed-view / error-carrier
/// materialization [`Self::variant`] would pay for; an
/// operator-facing "well-formed" diagnostic on the resolver's
/// Ok arm; a `has-unique-populated-kind` require-tag
/// classifier arm; a coherence check verifying "every
/// production parent from a `single_slot_X` factory is
/// well-formed") reads `parent.has_unique_populated_kind()`
/// through the inherent surface, byte-for-byte symmetrical
/// with `parent.is_empty()` / `parent.is_saturated()` under
/// the (zero-, one-arm) × (populated, missing) cardinality
/// grid. The composition law
/// `parent.has_unique_populated_kind() == (parent.populated_kind_count() == 1)`
/// is pinned as a first-class typed invariant by the trait's
/// own default body and swept substrate-wide by
/// [`crate::tagged_union::assert_has_unique_populated_kind_matches_populated_kind_count`].
pub fn has_unique_populated_kind(&self) -> bool {
<Self as $crate::tagged_union::TaggedUnion>::has_unique_populated_kind(self)
}
/// Boolean cardinality-mid-endpoint peer of
/// [`Self::unique_missing_kind`] — `true` iff EXACTLY ONE
/// slot on this tagged union is missing.
///
/// One-line inherent forwarder that delegates to the
/// substrate primitive
/// [`crate::tagged_union::TaggedUnion::has_unique_missing_kind`],
/// whose default body is `self.unique_missing_kind().is_some()`
/// — the Boolean projection of the two-step-short-circuit
/// closed-set walk `unique_missing_kind` already performs.
/// Every consumer that needs the exactly-one-missing arm as
/// a `bool` (a fast-path branch on the near-saturation arm;
/// an operator-facing "one slot away from saturated"
/// diagnostic; a `has-unique-missing-kind` require-tag
/// classifier arm) reads `parent.has_unique_missing_kind()`
/// through the inherent surface, byte-for-byte symmetrical
/// with `parent.has_unique_populated_kind()` under the
/// (populated, missing) complement axis. The composition law
/// `parent.has_unique_missing_kind() == (parent.missing_kind_count() == 1)`
/// is pinned as a first-class typed invariant by the trait's
/// own default body and swept substrate-wide by
/// [`crate::tagged_union::assert_has_unique_missing_kind_matches_missing_kind_count`].
pub fn has_unique_missing_kind(&self) -> bool {
<Self as $crate::tagged_union::TaggedUnion>::has_unique_missing_kind(self)
}
/// Boolean cardinality many-arm peer of
/// [`Self::has_unique_populated_kind`] — `true` iff TWO
/// OR MORE slots on this tagged union are populated (i.e.
/// the "ambiguous" arm of the resolver contract).
///
/// One-line inherent forwarder that delegates to the
/// substrate primitive
/// [`crate::tagged_union::TaggedUnion::has_multiple_populated_kinds`],
/// whose default body is a two-step-short-circuit closed-
/// set walk under [`Self::has`] that returns `true` iff
/// the filtered iterator yields at least two hits, WITHOUT
/// materializing the `Vec` `populated_kinds` would build.
/// The short-circuit fires on the SECOND populated slot
/// — strictly cheaper than the widened primitive on every
/// arm past the second populated slot.
///
/// # Sibling to the Boolean cardinality trichotomy
///
/// Third arm of the {0, 1, ≥2} cardinality trichotomy on
/// the populated axis. Together with [`Self::is_empty`]
/// (zero-arm) and [`Self::has_unique_populated_kind`]
/// (one-arm), these three Boolean primitives partition
/// every tagged-union state coherently — EXACTLY ONE of
/// the three returns `true` on any given parent. Maps
/// directly onto the three arms of the resolver contract
/// [`Self::variant`] returns:
/// `is_empty()` ↔ `Err(Error::empty)`,
/// `has_unique_populated_kind()` ↔ `Ok(Variant)`,
/// `has_multiple_populated_kinds()` ↔ `Err(Error::ambiguous)`.
///
/// The composition law
/// `parent.has_multiple_populated_kinds() == (parent.populated_kind_count() >= 2)`
/// is pinned as a first-class typed invariant by the
/// trait's own default body and swept substrate-wide by
/// [`crate::tagged_union::assert_has_multiple_populated_kinds_matches_populated_kind_count`].
pub fn has_multiple_populated_kinds(&self) -> bool {
<Self as $crate::tagged_union::TaggedUnion>::has_multiple_populated_kinds(self)
}
/// Boolean cardinality many-arm peer of
/// [`Self::has_unique_missing_kind`] — `true` iff TWO OR
/// MORE slots on this tagged union are missing.
///
/// One-line inherent forwarder that delegates to the
/// substrate primitive
/// [`crate::tagged_union::TaggedUnion::has_multiple_missing_kinds`],
/// whose default body is a two-step-short-circuit closed-
/// set walk under a NEGATED [`Self::has`] predicate that
/// returns `true` iff the filtered iterator yields at
/// least two hits, WITHOUT materializing the `Vec`
/// `missing_kinds` would build. Byte-for-byte symmetrical
/// with `parent.has_multiple_populated_kinds()` under the
/// (populated, missing) complement axis.
///
/// Third arm of the {0, 1, ≥2} cardinality trichotomy on
/// the missing axis. Together with [`Self::is_saturated`]
/// (zero-arm) and [`Self::has_unique_missing_kind`]
/// (one-arm), these three Boolean primitives partition
/// every tagged-union state coherently on the complement
/// axis. The composition law
/// `parent.has_multiple_missing_kinds() == (parent.missing_kind_count() >= 2)`
/// is pinned as a first-class typed invariant by the
/// trait's own default body and swept substrate-wide by
/// [`crate::tagged_union::assert_has_multiple_missing_kinds_matches_missing_kind_count`].
pub fn has_multiple_missing_kinds(&self) -> bool {
<Self as $crate::tagged_union::TaggedUnion>::has_multiple_missing_kinds(self)
}
/// Boolean cardinality "≤ 1" peer of
/// [`Self::has_multiple_populated_kinds`] — `true` iff AT
/// MOST ONE slot on this tagged union is populated (i.e.
/// zero or one populated slot).
///
/// One-line inherent forwarder that delegates to the
/// substrate primitive
/// [`crate::tagged_union::TaggedUnion::has_at_most_one_populated_kind`],
/// whose default body is the definitional Boolean negation
/// of [`Self::has_multiple_populated_kinds`] — reuses the
/// SAME two-step-short-circuit closed-set walk without
/// re-authoring the fused loop; the short-circuit fires on
/// the SECOND populated slot, and the negation flips the
/// return in-place without a second walk over the closed
/// set. Strictly cheaper than the widened union composition
/// `self.is_empty() || self.has_unique_populated_kind()`
/// (which walks the closed set twice) on every arm.
///
/// # Sibling to the Boolean cardinality "≥ 2" primitive
///
/// Boolean-negation peer under `!(≥ 2) == (≤ 1)` — where
/// [`Self::has_multiple_populated_kinds`] names the
/// AMBIGUOUS arm of the resolver contract (the arm
/// [`Self::variant`] returns `Err(Error::ambiguous)` on),
/// `has_at_most_one_populated_kind` names its complement —
/// the RESOLVEABLE-OR-EMPTY arm (the two arms of the
/// resolver contract that DON'T return `Err(Error::ambiguous)`).
/// The typed predicate for "this parent is not ambiguous"
/// without inverting a `!parent.has_multiple_populated_kinds()`
/// at every callsite.
///
/// # Composition laws
///
/// - `has_at_most_one_populated_kind() == !has_multiple_populated_kinds()`
/// — the definitional Boolean negation, at the trait
/// default body's SAME fused short-circuit walk.
/// - `has_at_most_one_populated_kind() == (populated_kind_count() <= 1)`
/// — the scalar cardinality composition.
/// - `has_at_most_one_populated_kind() == is_empty() || has_unique_populated_kind()`
/// — the union of the zero-arm and the one-arm of the
/// {0, 1, ≥ 2} cardinality trichotomy.
///
/// All three composition laws are pinned as first-class
/// typed invariants by the trait's own default body and
/// swept substrate-wide by
/// [`crate::tagged_union::assert_has_at_most_one_populated_kind_matches_populated_kind_count`].
pub fn has_at_most_one_populated_kind(&self) -> bool {
<Self as $crate::tagged_union::TaggedUnion>::has_at_most_one_populated_kind(self)
}
/// Boolean cardinality "≤ 1" peer of
/// [`Self::has_multiple_missing_kinds`] — `true` iff AT
/// MOST ONE slot on this tagged union is missing (i.e.
/// zero or one missing slot).
///
/// One-line inherent forwarder that delegates to the
/// substrate primitive
/// [`crate::tagged_union::TaggedUnion::has_at_most_one_missing_kind`],
/// whose default body is the definitional Boolean negation
/// of [`Self::has_multiple_missing_kinds`] — reuses the
/// SAME two-step-short-circuit closed-set walk under a
/// negated [`Self::has`] predicate without re-authoring the
/// fused loop. Strictly cheaper than the widened union
/// composition
/// `self.is_saturated() || self.has_unique_missing_kind()`
/// (two closed-set walks) on every arm.
///
/// # Sibling to the Boolean cardinality "≥ 2" primitive
///
/// Boolean-negation peer under `!(≥ 2) == (≤ 1)` —
/// byte-for-byte symmetrical with
/// `parent.has_at_most_one_populated_kind()` under the
/// (populated, missing) complement axis. Names the arm
/// where the parent is SATURATED-OR-NEAR-SATURATED (zero
/// or exactly one missing slot).
///
/// # Composition laws
///
/// - `has_at_most_one_missing_kind() == !has_multiple_missing_kinds()`
/// — the definitional Boolean negation.
/// - `has_at_most_one_missing_kind() == (missing_kind_count() <= 1)`
/// — the scalar complement-cardinality composition.
/// - `has_at_most_one_missing_kind() == is_saturated() || has_unique_missing_kind()`
/// — the union of the zero-missing-arm and the
/// one-missing-arm of the {0, 1, ≥ 2} cardinality
/// trichotomy on the missing axis.
///
/// All three composition laws are pinned as first-class
/// typed invariants by the trait's own default body and
/// swept substrate-wide by
/// [`crate::tagged_union::assert_has_at_most_one_missing_kind_matches_missing_kind_count`].
pub fn has_at_most_one_missing_kind(&self) -> bool {
<Self as $crate::tagged_union::TaggedUnion>::has_at_most_one_missing_kind(self)
}
/// Boolean parent-state middle-arm projection — `true` iff
/// this tagged union has AT LEAST ONE populated slot AND AT
/// LEAST ONE missing slot, i.e. it is neither
/// [`Self::is_empty`] nor [`Self::is_saturated`].
///
/// One-line inherent forwarder that delegates to the
/// substrate primitive
/// [`crate::tagged_union::TaggedUnion::is_partially_populated`],
/// whose default body is a FUSED short-circuit closed-set
/// walk that returns `true` at the EARLIEST slot where both
/// a populated AND a missing kind have been observed —
/// byte-for-byte cheaper than the widened composition
/// `!self.is_empty() && !self.is_saturated()` (two closed-
/// set walks) on every partially-populated arm.
///
/// # Sibling to the parent-state trichotomy
///
/// Middle arm of the natural `{Empty | Partial | Saturated}`
/// parent-state trichotomy — orthogonal to the {0, 1, ≥2}
/// cardinality trichotomies on the populated / missing
/// axes. Together with [`Self::is_empty`] (all-missing arm)
/// and [`Self::is_saturated`] (all-populated arm), these
/// three Boolean primitives partition every tagged-union
/// state coherently on the parent-state axis — EXACTLY ONE
/// of the three returns `true` on any given parent. The
/// trichotomy partition law
/// `usize::from(is_empty()) + usize::from(is_partially_populated())
/// + usize::from(is_saturated()) == 1` is pinned as a first-
/// class typed invariant by the trait's own default body
/// and swept substrate-wide by
/// [`crate::tagged_union::assert_is_partially_populated_matches_cardinality`].
pub fn is_partially_populated(&self) -> bool {
<Self as $crate::tagged_union::TaggedUnion>::is_partially_populated(self)
}
/// Kind-scoped strict refinement of [`Self::has`] — `true`
/// iff the given `kind` is populated AND no OTHER slot on
/// this tagged union is populated. The "exactly this one
/// variant" predicate.
///
/// One-line inherent forwarder that delegates to the
/// substrate primitive
/// [`crate::tagged_union::TaggedUnion::has_only`], whose
/// default body is a FUSED short-circuit closed-set walk
/// that returns `false` at the EARLIEST populated slot
/// whose kind is NOT `kind`, and returns `true` iff the
/// sweep completes with `kind` seen as the sole populated
/// slot. Byte-for-byte cheaper than either widened
/// composition `self.unique_populated_kind() ==
/// Some(kind)` (which walks until the SECOND populated
/// slot) or `self.has(kind) &&
/// self.has_unique_populated_kind()` (which walks the
/// closed set twice) on every arm where the parent
/// carries a populated slot that isn't `kind`.
///
/// # Sibling to [`Self::has`]
///
/// Kind-scoped strict-refinement peer: `has(kind)` is the
/// SUBSET predicate; `has_only(kind)` is the EQUAL
/// predicate. The implication
/// `has_only(kind) → has(kind)` binds the pair on the
/// strict-refinement axis. The composition law
/// `parent.has_only(kind) ==
/// (parent.unique_populated_kind() == Some(kind))` is
/// pinned as a first-class typed invariant by the trait's
/// own default body and swept substrate-wide by
/// [`crate::tagged_union::assert_has_only_matches_unique_populated_kind`].
pub fn has_only(&self, kind: $kind) -> bool {
<Self as $crate::tagged_union::TaggedUnion>::has_only(self, kind)
}
/// Closed-set-complement peer of [`Self::has_only`] —
/// `true` iff the given `kind` is MISSING AND no OTHER slot
/// on this tagged union is missing.
///
/// One-line inherent forwarder that delegates the fused
/// short-circuit walk to the substrate primitive
/// [`crate::tagged_union::TaggedUnion::lacks_only`], whose
/// default body walks
/// `<Self::Kind as ClosedSet>::ALL` under a negated
/// [`crate::tagged_union::TaggedUnion::has`] and returns
/// `false` at the EARLIEST missing slot whose kind is not
/// `kind`. Byte-for-byte cheaper than either widened
/// composition
/// `self.unique_missing_kind() == Some(kind)` (which walks
/// until the SECOND missing slot before comparing) or
/// `!self.has(kind) && self.has_unique_missing_kind()`
/// (two closed-set walks) on every arm where the parent
/// carries a missing slot that isn't `kind`.
///
/// # Sibling to [`Self::has_only`]
///
/// Closed-set-complement peer: `has_only(kind)` names
/// parents whose SOLE populated slot is `kind`;
/// `lacks_only(kind)` names parents whose SOLE missing slot
/// is `kind`. The composition law
/// `parent.lacks_only(kind) ==
/// (parent.unique_missing_kind() == Some(kind))` and the
/// cardinality-refinement law
/// `parent.lacks_only(kind) == (!parent.has(kind) &&
/// parent.has_unique_missing_kind())` are pinned as first-
/// class typed invariants by the trait's own default body
/// and swept substrate-wide by
/// [`crate::tagged_union::assert_lacks_only_matches_unique_missing_kind`].
pub fn lacks_only(&self, kind: $kind) -> bool {
<Self as $crate::tagged_union::TaggedUnion>::lacks_only(self, kind)
}
}
impl $crate::tagged_union::VariantSelector<$parent> for $kind {
type Variant<'a> = $variant<'a>;
fn select<'a>(self, parent: &'a $parent) -> ::std::option::Option<$variant<'a>>
where
Self: 'a,
{
<$kind>::select(self, parent)
}
}
impl $crate::tagged_union::TaggedUnion for $parent {
type Kind = $kind;
type Error = $err;
const KIND_LIST: &'static str = $kind_list;
}
};
}
/// Project the borrowed-view of a tagged-union variant addressed by
/// this closed-set discriminator.
///
/// Companion trait to [`TaggedUnion`] — binds a `Kind` closed-set to
/// the parent `P` it discriminates AND to the borrowed-view
/// [`Self::Variant<'a>`] the resolver hands out. Every one of the
/// four production `.variant()` sites on `ProcessSpec`
/// ([`crate::intent::Intent`], [`crate::encapsulates::EncapsulationKind`],
/// [`crate::export::ArtifactSource`], [`crate::export::VectorChannel`])
/// pre-lift restated the same
/// `Self::Kind::ALL.into_iter().map(|k| k.select(self))` sweep body
/// verbatim at its inherent `.variant()`. Post-lift the trait binds
/// `(k.select(self), Variant<'a>)` onto ONE typed contract per Kind
/// so [`TaggedUnion::variant`]'s default body can dispatch the sweep
/// generically — the four sibling inherent bodies collapse to
/// one-line delegations and a fifth sibling picks up the sweep for
/// free through ONE `impl VariantSelector` block.
///
/// The GAT `Variant<'a>` carries the parent's lifetime so a borrowed
/// view projected from `&'a P` composes typed with the resolver's
/// short-circuit — every projection stays a compile-time refinement,
/// no `Box<dyn ...>` erasure. The GAT is additionally bound to
/// [`VariantKind<Self>`] so every implementor's borrowed view knows
/// its addressing Kind — the reverse projection of [`Self::select`]
/// closed at compile-time so a fifth sibling that adds `impl
/// VariantSelector` without opening the peer `impl VariantKind` fails
/// at the trait bound, not later at a per-consumer round-trip test.
pub trait VariantSelector<P: ?Sized>: Copy + 'static {
/// The borrowed-view enum returned by the parent's inherent
/// `.variant()` method — one arm per closed-set variant, each
/// arm carrying a `&'a` reference into the parent's populated
/// slot. Bound generically here so [`TaggedUnion::variant`]'s
/// default body can name the return type without restating it
/// per parent. Additionally bound to [`VariantKind<Self>`] so
/// the reverse projection `Variant<'a> → Self` is closed at the
/// trait boundary — every implementor's borrowed view knows its
/// addressing Kind through ONE typed contract, and the substrate
/// testkit [`assert_variant_round_trip`] composes `select`
/// (forward) with `variant_kind` (reverse) generically.
type Variant<'a>: VariantKind<Self>
where
P: 'a,
Self: 'a;
/// Project a `&'a P` borrow into the optional typed variant view
/// for `self` (the addressed discriminator). Returns `None` iff
/// the matching slot on `P` is `None`. Composes the closed-set
/// sweep [`TaggedUnion::variant`] loops over.
fn select<'a>(self, parent: &'a P) -> Option<Self::Variant<'a>>
where
Self: 'a;
}
/// Reverse projection — every borrowed-variant view enum knows its
/// closed-set `K` discriminator.
///
/// Dual of [`VariantSelector<P>::select`] on the addressed Kind:
/// where the selector projects a parent borrow forward into an
/// optional Variant, this trait projects a populated Variant back
/// into the Kind that addresses it. Together they compose the
/// round-trip contract every tagged-union `.variant()` site pins
/// via the substrate testkit [`assert_variant_round_trip`]:
/// `k.select(&parent).map(|v| v.variant_kind()) == Some(k)` on the
/// populated side, and `parent.variant().unwrap().variant_kind() == k`
/// through the [`TaggedUnion::variant`] resolver's default body.
///
/// Every borrowed-view enum on `ProcessSpec`'s tagged-union axis
/// ([`crate::intent::IntentVariant<'_>`],
/// [`crate::lifetime::LifetimeVariant<'_>`],
/// [`crate::encapsulates::EncapsulationKindVariant<'_>`],
/// [`crate::export::ArtifactVariant<'_>`],
/// [`crate::export::ChannelVariant<'_>`]) pre-lift restated the same
/// `match self { Self::A(_) => K::A, Self::B(_) => K::B, ... }`
/// per-arm mapping at its own inherent method (named `.kind()` on
/// four of five sites; `.target()` on
/// [`crate::encapsulates::EncapsulationKindVariant`] where the
/// discriminator's semantic role is a target of encapsulation, not
/// a kind of parent). The reverse-projection body must stay
/// per-implementor — it names the ground-truth arm-to-Kind mapping
/// only the site knows — but the CONTRACT lives at ONE typed
/// surface so:
///
/// * Every downstream generic consumer binds through
/// `<T::Variant<'_> as VariantKind<T::Kind>>::variant_kind(&v)`
/// instead of a per-parent inherent-method restatement.
/// * [`VariantSelector<P>::Variant<'a>`] bounds this trait — a
/// fifth sibling that adds `impl VariantSelector<P> for XKind`
/// without the peer `impl VariantKind<XKind> for XVariant<'_>`
/// fails at the associated-type bound, so the reverse projection
/// is closed at compile-time across every implementor.
/// * The generic testkit [`assert_variant_round_trip`] composes
/// `select` (forward) with `variant_kind` (reverse) at ONE
/// substrate site — the four sibling
/// `_kind_round_trips_through_variant_kind` /
/// `_target_round_trips_through_variant_target` test bodies
/// collapse to one-line invocations.
///
/// The trait method is named [`Self::variant_kind`] rather than
/// `kind` to avoid shadowing the inherent `.kind()` (or
/// `.target()`) methods each borrowed-view enum already publishes.
/// Every impl body is a one-line delegation to the site's inherent
/// method — the substrate stays the projection, not the mapping.
pub trait VariantKind<K: Copy + 'static> {
/// Project a borrowed-variant view back into its addressing
/// closed-set `K` discriminator. Round-trips the closed set on
/// the populated side against [`VariantSelector::select`] — a
/// value returned by `k.select(&parent).unwrap()` must satisfy
/// `variant_kind() == k`, and a value returned by
/// `parent.variant().unwrap()` must satisfy `variant_kind() ==
/// k` for the populated slot's `k`.
fn variant_kind(&self) -> K;
}
/// Generic round-trip testkit — pins that
/// [`VariantSelector::select`] (forward projection) and
/// [`VariantKind::variant_kind`] (reverse projection) compose the
/// closed set in both directions on the populated side.
///
/// Substrate primitive for the four sibling
/// `_kind_round_trips_through_variant_kind` /
/// `_target_round_trips_through_variant_target` tests on
/// `ProcessSpec` ([`crate::intent::Intent`],
/// [`crate::encapsulates::EncapsulationKind`],
/// [`crate::export::ArtifactSource`],
/// [`crate::export::VectorChannel`]) that pre-lift each restated the
/// same two-arm round-trip probe at their own test bodies:
///
/// 1. For each `k in K::ALL`, construct a parent with only slot `k`
/// populated (via a site-local `single_slot_X(k) -> Parent`
/// helper).
/// 2. Assert that `k.select(&parent).unwrap().variant_kind() == k`
/// (the forward-then-reverse round-trip).
/// 3. Assert that `parent.variant().unwrap().variant_kind() == k`
/// (the resolver-then-reverse round-trip).
///
/// Post-lift each site's round-trip test collapses to ONE
/// `assert_variant_round_trip::<T, _>(single_slot_X)` invocation
/// whose body is the substrate primitive's own dispatch. A fifth
/// sibling picks up the round-trip check through ONE call site.
///
/// The `make_parent` closure stays per-site — every one of the four
/// production sites already owns a
/// `single_slot_intent(k) / single_slot_source(k) /
/// single_slot_channel(k) / single_slot_kind(t)` helper that
/// constructs a minimally-valid parent with the addressed slot's
/// inner spec populated; the closure IS the round-trip's ground
/// truth for "populate slot k", and lifting it into the primitive
/// would collapse the per-site construction knowledge that stays
/// deliberately local.
///
/// The [`crate::lifetime::Lifetime`] site is DELIBERATELY excluded
/// — `Lifetime` doesn't impl [`TaggedUnion`] (its `variant()` returns
/// `Ok(Permanent)` on empty, not an `Empty` typed error), so the
/// `<T: TaggedUnion>` bound doesn't reach it. Its per-site
/// round-trip test binds through [`VariantKind`] directly on
/// [`crate::lifetime::LifetimeVariant`] instead.
#[track_caller]
pub fn assert_variant_round_trip<T, F>(make_parent: F)
where
T: TaggedUnion,
T::Kind: PartialEq + std::fmt::Debug,
F: Fn(T::Kind) -> T,
{
for k in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let parent = make_parent(k);
let selected = k.select(&parent).unwrap_or_else(|| {
panic!("VariantSelector::select must return Some for populated slot {k:?}")
});
assert_eq!(
<<T::Kind as VariantSelector<T>>::Variant<'_> as VariantKind<T::Kind>>::variant_kind(
&selected,
),
k,
"select→variant_kind round-trip failed for {k:?}",
);
let resolved = parent.variant().ok().unwrap_or_else(|| {
panic!("TaggedUnion::variant must resolve exactly-one populated for {k:?}")
});
assert_eq!(
<<T::Kind as VariantSelector<T>>::Variant<'_> as VariantKind<T::Kind>>::variant_kind(
&resolved,
),
k,
"variant()→variant_kind resolver disagreed on {k:?}",
);
}
}
/// Declarative surface that names the (Kind, Error, KIND_LIST) triple
/// a tagged-union `.variant()` site publishes to the substrate — and
/// provides the sweep body as ONE default method every implementor
/// picks up for free.
///
/// Every one of the four production `.variant()` sites on `ProcessSpec`
/// ([`crate::intent::Intent`], [`crate::encapsulates::EncapsulationKind`],
/// [`crate::export::ArtifactSource`], [`crate::export::VectorChannel`])
/// exposes the SAME three-piece surface: a closed-set discriminator
/// [`Self::Kind`], a typed [`Self::Error`] carrier that projects onto
/// the shared [`TaggedUnionError`] contract, and a slash-joined
/// operator diagnostic literal [`Self::KIND_LIST`]. Pre-lift the
/// triple lived on each parent type as independent inherent items —
/// the (Kind, Error) types cross-referenced only by module-doc prose,
/// the `KIND_LIST` `&'static str` maintained separately at each site
/// alongside the inherent `.variant()` body. Post-lift the trait
/// binds the three onto ONE typed contract per parent so downstream
/// generic code binds to `<T: TaggedUnion>` instead of restating the
/// per-parent quadruple of associated names.
///
/// The [`Self::variant`] default method is the substrate primitive
/// every inherent `.variant()` on the four production sites delegates
/// to — one-line inherent forwarders preserve the load-bearing
/// calling convention (so no downstream callsite needs
/// `use crate::tagged_union::TaggedUnion` to reach `.variant()`) while
/// the resolve-sweep body lives at ONE substrate site. Adding a fifth
/// sibling means ONE `impl TaggedUnion` block + ONE
/// `impl VariantSelector<Self>` block on the sibling `Kind` + ONE
/// one-line inherent forwarder — no re-authored 5-line
/// `resolve_or_err(K::ALL.into_iter().map(|k| k.select(self)),
/// KIND_LIST)` sweep body.
///
/// The `Kind` type is bound to [`tatara_closed_set::ClosedSet`] so
/// generic testkit primitives (starting with
/// [`assert_kind_list_matches_closed_set`]) can compose
/// `<Self::Kind as ClosedSet>::labels_joined("/")` against
/// [`Self::KIND_LIST`] byte-identically across every implementor —
/// the diagnostic-stability invariant every sibling pre-lift pinned
/// through a hand-rolled per-site test body. It is additionally
/// bound to [`VariantSelector<Self>`] so [`Self::variant`]'s default
/// body reaches `k.select(self)` generically.
///
/// The [`crate::lifetime::Lifetime`] site is DELIBERATELY not routed
/// through this trait — its `variant()` returns `Ok(Permanent)` on
/// empty rather than an `Empty` typed error, so its projection shape
/// diverges from the four Empty-projecting siblings. Same reasoning
/// as [`resolve_or_err`]'s explicit exclusion of `Lifetime`.
pub trait TaggedUnion: Sized {
/// The closed-set discriminator over this tagged-union's variants.
/// Bound to [`tatara_closed_set::ClosedSet`] so the generic
/// diagnostic-stability testkit ([`assert_kind_list_matches_closed_set`])
/// can project `<Self::Kind as ClosedSet>::labels_joined("/")`
/// against [`Self::KIND_LIST`] byte-identically. Additionally
/// bound to [`VariantSelector<Self>`] so [`Self::variant`]'s
/// default body can dispatch `k.select(self)` at each
/// [`ClosedSet::ALL`] entry generically.
type Kind: tatara_closed_set::ClosedSet + VariantSelector<Self>;
/// The typed error carrier returned by the parent's inherent
/// `.variant()` method — projects onto the shared
/// [`TaggedUnionError`] contract so [`resolve_or_err`]'s two-arm
/// dispatch reaches every implementor uniformly.
type Error: TaggedUnionError;
/// Slash-joined operator diagnostic literal — the payload of
/// [`TaggedUnionError::empty`] when no slot is populated on this
/// tagged union. Pinned against
/// `<Self::Kind as tatara_closed_set::ClosedSet>::labels_joined("/")`
/// by [`assert_kind_list_matches_closed_set`] so a variant added
/// to `Self::Kind` without updating this constant (or a renamed
/// variant) fails-loudly at the testkit boundary.
const KIND_LIST: &'static str;
/// Sweep over every [`Self::Kind`] discriminator in
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) order,
/// projecting each into the parent's borrowed variant view via
/// [`VariantSelector::select`], and resolve to exactly one populated
/// variant through [`resolve_or_err`]. Errors on zero (with
/// [`Self::KIND_LIST`] carried on the [`TaggedUnionError::empty`]
/// arm) or many.
///
/// The substrate primitive every one of the four production
/// `.variant()` sites on `ProcessSpec` dispatches through — the
/// per-parent inherent `.variant()` is a one-line delegation to
/// this default so the calling convention (`intent.variant()`,
/// `channel.variant()`, ...) stays load-bearing at the callsite
/// without every consumer picking up `use TaggedUnion`.
///
/// Adding a fifth sibling picks up this body for free — no
/// re-authored `resolve_or_err(...)` sweep at the impl block.
fn variant(&self) -> Result<<Self::Kind as VariantSelector<Self>>::Variant<'_>, Self::Error> {
resolve_or_err(
<Self::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
.map(|k| k.select(self)),
Self::KIND_LIST,
)
}
/// Widened peer of [`Self::has`] — projects a `&'a Self` borrow
/// into the optional borrowed-variant view addressed by `kind`,
/// or `None` when the matching slot on `Self` is empty.
///
/// One-liner that delegates to [`VariantSelector::select`] on the
/// closed-set discriminator; the substrate primitive both
/// [`Self::has`] (via the default `self.find(kind).is_some()`
/// body) and future diagnostic consumers (an operator-facing
/// require-tag classifier that reads the populated slot's inner
/// payload for a `param.key=value` message, a coherence check
/// that projects the borrowed variant into its
/// [`VariantKind::variant_kind`] Kind for round-trip validation
/// without going through the resolver's Empty/Ambiguous carriers)
/// compose against.
///
/// # Sibling to [`Self::has`]
///
/// One refinement wider: `has` collapses the return to a `bool`;
/// `find` returns the matching borrowed [`VariantSelector::Variant`]
/// so callers can read the populated slot's inner spec without
/// re-projecting through `kind.select(self)` at the callsite (and
/// without pulling `use VariantSelector` into scope). The default
/// body of `has` is `self.find(kind).is_some()` — the two methods
/// share ONE walk semantics by construction, so a regression that
/// drifted the presence probe from the widened probe becomes
/// structurally impossible past the trait boundary.
///
/// # Peer to [`crate::boundary::ConditionSliceExt::find_kind`]
///
/// Same shape, same axis, second instance in the workspace-wide
/// `(K) -> Option<&V>` widened presence-probe algebra:
/// [`ConditionSliceExt::find_kind`] returns `Option<&Condition>`
/// on the slice-level ONE-shape probe; `find` here returns
/// `Option<Variant<'_>>` on the tagged-union parent-level
/// N-slot probe. Both refine their `has_kind` / `has` bool peer
/// through the same `find(...).is_some()` composition law.
///
/// # Semantics
///
/// Returns `Some(v)` where `v` is the borrowed-view projection of
/// the populated slot addressed by `kind`, or `None` iff that
/// slot is `None`. Byte-for-byte equivalent to
/// `kind.select(self)`; existing `k.select(&parent)` callsites
/// route through this inherent surface after the macro-emitted
/// forwarder lands.
fn find(&self, kind: Self::Kind) -> Option<<Self::Kind as VariantSelector<Self>>::Variant<'_>> {
kind.select(self)
}
/// Presence probe — does this tagged union carry a populated
/// slot addressed by the given closed-set discriminator?
///
/// Default body: `self.find(kind).is_some()`. The presence half
/// of the resolve contract, without allocating an [`Self::Error`]
/// carrier when the caller only needs the yes/no answer.
/// Substrate primitive for closed-set-driven dispatch tables
/// (e.g. tatara-check's `intent-<kind>` requires-tag sweep) where
/// a hand-authored per-slot `spec.<field>.is_some()` chain
/// otherwise drifts from the
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL)
/// enumeration as new variants land.
///
/// Every one of the four production `.variant()` sites on
/// `ProcessSpec` picks this up for free through the trait default
/// — the [`declare_tagged_union_impls!`] macro emits a one-line
/// inherent forwarder so `intent.has(kind)` reads at consumer
/// callsites without `use TaggedUnion`. Adding a fifth sibling
/// picks up the presence probe with zero re-authored body.
fn has(&self, kind: Self::Kind) -> bool {
self.find(kind).is_some()
}
/// Closed-set-complement peer of [`Self::has`] — `true` iff the
/// given `kind` is MISSING (its slot on this tagged union is
/// empty). The definitional dual of the presence probe on the
/// MISSING axis.
///
/// Default body: `!self.has(kind)`. One bit-flip; the primitive
/// value here is naming — every consumer that reads "the missing
/// set contains `kind`" or "the parent lacks this dependency"
/// gets a first-class typed predicate whose call-site text reads
/// correctly on the missing axis, without inverting the reader's
/// parse of `!parent.has(...)` at every site.
///
/// # Sibling to [`Self::has`]
///
/// Closed-set-complement peer on the (populated, missing)
/// duality: `has(kind)` names parents whose POPULATED set
/// contains `kind`; `lacks(kind)` names parents whose MISSING
/// set contains `kind`. The definitional complement law
/// `lacks(kind) == !has(kind)` holds on every arm and every kind
/// — pinned as a first-class typed invariant by the trait's own
/// default body and swept substrate-wide by
/// [`assert_lacks_matches_has_complement`].
///
/// # Sibling to [`Self::lacks_only`]
///
/// Kind-scoped strict-refinement peer on the MISSING axis:
/// `lacks(kind)` is the SUBSET predicate (`kind` missing, maybe
/// others too); `lacks_only(kind)` is the EQUAL predicate
/// (`kind` missing AND ONLY `kind`). The implication
/// `lacks_only(kind) → lacks(kind)` binds the pair on the
/// strict-refinement axis — byte-for-byte missing-axis peer of
/// the populated-axis `has_only(kind) → has(kind)` implication.
/// Together with `has(kind)`, `has_only(kind)`, and
/// `lacks_only(kind)` the four predicates close the 2×2
/// (populated, missing) × (subset, equal) grid on the
/// kind-scoped tagged-union axis.
///
/// # Truth table on the exactly-one-slot tagged-union contract
///
/// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
/// cardinality `N ≥ 2` and a fixed argument `kind`:
///
/// - Empty parent (0 populated, N missing): `true` — every kind
/// is missing, so any `kind` satisfies the predicate.
/// - Well-formed parent with `kind` populated (1 populated ==
/// kind): `false` — the populated slot addresses `kind`, so
/// `kind` is not missing.
/// - Well-formed parent with OTHER kind populated (1 populated
/// != kind): `true` — the sole populated slot is not `kind`,
/// so `kind` is missing.
/// - Saturated parent (N populated, 0 missing): `false` — every
/// kind is populated, so `kind` is not missing.
///
/// # Kind-domain cardinality
///
/// `<Self::Kind as ClosedSet>::ALL.iter().filter(|k| parent.lacks(*k)).count()
/// == parent.missing_kind_count()` — the count of kinds
/// satisfying `lacks` on any arm is exactly the parent's
/// missing-slot count. Closed-set-complement peer of the
/// populated-axis law `count k where has(k) ==
/// populated_kind_count()`. Binds the kind-scoped SUBSET
/// primitive on the missing axis to the arg-less cardinality
/// scalar at ONE substrate site.
///
/// # Compounding future consumers
///
/// - Any consumer whose semantic reading is "the missing set
/// contains this kind" — a "still missing: <kind>" diagnostic,
/// a `lacks-<kind>` require-tag classifier arm, a
/// dependency-satisfaction check — reads `parent.lacks(kind)`
/// through the inherent surface rather than negating
/// `parent.has(kind)` at the call site. The primitive costs
/// one bit-flip past [`Self::has`]; the reader-facing win is
/// that `!parent.has(k)` no longer needs to be re-parsed as
/// "the missing set contains k" at every missing-axis call
/// site.
/// - The kind-scoped implication
/// `lacks_only(kind) → lacks(kind)` becomes a first-class
/// typed law binding [`Self::lacks_only`] to `lacks` on the
/// strict-refinement axis — byte-for-byte missing-axis peer
/// of `has_only(kind) → has(kind)`.
///
/// A new [`Self::Kind`] variant added to
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
/// this primitive mechanically through the delegated
/// [`Self::has`] — the closed-set walk extended by
/// [`Self::has`]'s default body composition picks up the new
/// slot at every downstream callsite without further per-caller
/// edit.
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
/// The closed-set-complement projection lives at ONE substrate
/// site as a definitional negation of [`Self::has`]. The
/// complement law `lacks(kind) == !has(kind)` and the
/// kind-scoped implication `lacks_only(kind) → lacks(kind)`
/// are pinned across every production tagged union at compile
/// time via the trait's default body composition, not
/// per-parent.
/// - THEORY.md §VI.1 — generation over composition. A new
/// [`Self::Kind`] variant added to `ALL` reaches this
/// primitive mechanically through the delegated [`Self::has`]
/// — every downstream consumer sees the widened kind set
/// without further per-caller edit.
fn lacks(&self, kind: Self::Kind) -> bool {
!self.has(kind)
}
/// Closed-set-inversion refinement — enumerate the set of
/// [`Self::Kind`] discriminators whose corresponding slot on
/// `self` is populated, in canonical
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) order.
///
/// Default body:
/// `<Kind as ClosedSet>::ALL.iter().copied().filter(|k| self.has(*k)).collect()`.
/// A tagged-union parent that satisfies the exactly-one-slot
/// contract returns a `Vec` of length 0 (empty parent — matches
/// [`Self::variant`]'s `Empty` arm) or 1 (well-formed — matches
/// the `Ok` arm); a malformed parent with multiple populated
/// slots returns a `Vec` of length ≥ 2 in canonical `ALL` order
/// (matches the `Ambiguous` arm and NAMES which slots are
/// populated, unlike the payload-free `Ambiguous` carrier).
///
/// # Sibling to [`Self::has`] / [`Self::find`]
///
/// One refinement wider on the ORTHOGONAL axis: `has(k) / find(k)`
/// fix a `Self::Kind` and vary the return type (`bool` /
/// `Option<Variant>`); this refinement INVERTS the axis by fixing
/// the parent and varying over `Kind::ALL`, returning the SET of
/// populated kinds. The composition law
/// `populated_kinds().contains(&k) == has(k)` for every
/// `k ∈ Kind::ALL` binds the two axes structurally through the
/// default body — a regression that overrode `populated_kinds`
/// to skip a kind, return duplicates, or drift the walk order
/// surfaces at the substrate testkit
/// [`assert_populated_kinds_matches_has`].
///
/// # Peer to [`crate::boundary::ConditionSliceExt::distinct_kinds`]
///
/// Same shape, same axis, second instance in the workspace-wide
/// closed-set-inversion refinement algebra:
/// [`ConditionSliceExt::distinct_kinds`] returns
/// `Vec<ConditionKind>` on the slice-level presence-probe axis
/// (fixes the slice, varies over `ConditionKind::ALL`);
/// `populated_kinds` here returns `Vec<Self::Kind>` on the
/// tagged-union parent-level presence-probe axis (fixes the
/// parent, varies over `<Self::Kind as ClosedSet>::ALL`). Both
/// refine their `has(k) / has_kind(k)` bool peer through the
/// same `ALL.filter(has).collect()` composition law.
///
/// # Compounding future consumers
///
/// - An operator-facing `Ambiguous(Vec<Kind>)` diagnostic that
/// NAMES which slots collide (upgrading the payload-free
/// [`TaggedUnionError::ambiguous`] carrier without touching the
/// resolver's short-circuit) reads `parent.populated_kinds()`
/// directly on the malformed arm.
/// - A closed-set audit dispatcher that enumerates every
/// populated slot for a fleet-wide "which parents carry
/// {Container, Nix, Aplicacao}" query reaches ONE substrate
/// primitive rather than paying for a per-kind `has(k)` sweep
/// at every callsite.
/// - A hypothetical `populated-kind-count-<n>` require-tag
/// classifier prefix family that publishes the populated-set
/// cardinality as a scalar reads `parent.populated_kinds().len()`.
///
/// A new [`Self::Kind`] variant added to
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
/// this primitive mechanically (the closed-set walk picks up the
/// new entry) and every downstream consumer sees the wider set
/// without further per-caller edit.
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
/// The closed-set-inversion refinement lives at ONE substrate
/// site as a typed projection of [`Self::has`] over the closed
/// set `<Self::Kind as ClosedSet>::ALL`. Every downstream
/// aggregate consumer binds through the SAME shape rather
/// than restating the `ALL`-filter closure body.
/// - THEORY.md §VI.1 — generation over composition. A new
/// [`Self::Kind`] variant added to `ALL` reaches this primitive
/// mechanically and every downstream consumer sees the wider
/// set with no per-caller edit.
fn populated_kinds(&self) -> ::std::vec::Vec<Self::Kind> {
<Self::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
.filter(|k| self.has(*k))
.collect()
}
/// Scalar cardinality refinement on the closed-set-inversion axis —
/// the number of [`Self::Kind`] discriminators whose corresponding
/// slot on `self` is populated.
///
/// Default body:
/// `<Self::Kind as ClosedSet>::ALL.iter().copied().filter(|k| self.has(*k)).count()`
/// — a closed-set walk that composes against [`Self::has`] per
/// variant WITHOUT materializing an intermediate `Vec`. A tagged-
/// union parent that satisfies the exactly-one-slot contract
/// returns `0` (empty — matches [`Self::variant`]'s `Empty` arm),
/// `1` (well-formed — matches the `Ok` arm), or `≥ 2` (malformed
/// — matches the `Ambiguous` arm) exactly aligned with
/// [`Self::populated_kinds`]`().len()` but without paying for the
/// heap allocation and dealloc a caller only needing the scalar
/// cardinality otherwise pays.
///
/// # Sibling to [`Self::populated_kinds`]
///
/// Scalar projection of the closed-set-inversion widened primitive
/// — where `populated_kinds` returns the SET (a `Vec<Self::Kind>`
/// in canonical `ClosedSet::ALL` order), `populated_kind_count`
/// collapses that set to its cardinality. The composition law
/// `populated_kind_count() == populated_kinds().len()` binds the
/// scalar projection to the widened primitive at the trait's
/// default body — a regression that overrode
/// `populated_kind_count` to skip a kind, double-count a slot, or
/// drift the walk from `ClosedSet::ALL` surfaces at the substrate
/// testkit
/// [`assert_populated_kind_count_matches_populated_kinds`].
///
/// # Peer to [`crate::boundary::ConditionSliceExt::count_kind`]
///
/// Not a direct peer — `count_kind(k)` on the slice-level axis
/// fixes a `ConditionKind` and returns the per-kind cardinality
/// (how many `Condition`s in the slice carry `k`);
/// `populated_kind_count` on the tagged-union parent-level axis
/// INVERTS by fixing the parent and returning the cardinality of
/// the populated-kind SET (how many distinct slots on the parent
/// are populated). The distinct peer to `count_kind` on the
/// tagged-union axis would be a hypothetical `populated_slots(k)
/// -> usize` — but since every tagged-union slot is `Option<T>`
/// (populated or not, cardinality ∈ {0, 1}), that peer reduces
/// to `has(k) as usize` and doesn't earn its own name. The
/// canonical scalar peer on the tagged-union axis is this
/// closed-set-inversion cardinality.
///
/// # Sibling of [`Self::has`] / [`Self::find`] / [`Self::populated_kinds`]
///
/// Fourth refinement on the tagged-union presence-probe algebra,
/// scalar-valued on the closed-set-inversion axis: `has` collapses
/// per-kind presence to a `bool`, `find` widens per-kind to
/// `Option<Variant>`, `populated_kinds` inverts to the SET of
/// populated kinds, and `populated_kind_count` scalar-projects
/// that set to its cardinality. Every downstream consumer picks
/// the coarsest refinement that answers its question — a
/// `populated-kind-count-<n>` require-tag classifier prefix
/// (called out in [`Self::populated_kinds`]'s doc-comment as a
/// hypothetical compounding-future consumer) now reaches
/// `parent.populated_kind_count()` at ONE substrate site rather
/// than paying for `parent.populated_kinds().len()` (with its
/// intermediate heap allocation) or the per-kind
/// `<Kind::ALL>.iter().filter(|k| parent.has(*k)).count()` closure
/// body at the callsite.
///
/// # Compounding future consumers
///
/// - A `populated-kind-count-<n>` require-tag classifier prefix
/// family that publishes the populated-set cardinality as a
/// scalar (the exact use case named in
/// [`Self::populated_kinds`]'s doc-comment) reaches this ONE
/// primitive without allocating.
/// - A fast-path branch on `Ambiguous`-arm callers that need to
/// distinguish "well-formed" from "malformed with N slots" reads
/// `parent.populated_kind_count() > 1` at ONE call site rather
/// than reaching for the Vec-materializing widened primitive.
/// - Any coherence check that verifies "every well-formed process
/// parent has exactly one populated slot" now reads
/// `parent.populated_kind_count() == 1` at ONE site rather than
/// restating `parent.populated_kinds().len() == 1` with its
/// allocation cost, or the semantically-equivalent (but
/// parent-arm-projected) `parent.variant().is_ok()`.
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
/// The scalar cardinality lives at ONE substrate site as a
/// typed projection of [`Self::populated_kinds`] onto its
/// `.len()`, and the default body composes against
/// [`Self::has`] over the closed set `<Self::Kind as
/// ClosedSet>::ALL` byte-identically to `populated_kinds`
/// without the intermediate `Vec`. Every downstream aggregate
/// consumer binds through the SAME shape rather than paying
/// for the allocation to reach the cardinality.
/// - THEORY.md §VI.1 — generation over composition. A new
/// [`Self::Kind`] variant added to `ALL` reaches this primitive
/// mechanically (the closed-set walk picks up the new entry)
/// and every downstream consumer sees the wider cardinality
/// without further per-caller edit.
fn populated_kind_count(&self) -> usize {
<Self::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
.filter(|k| self.has(*k))
.count()
}
/// Closed-set-COMPLEMENT refinement — enumerate the set of
/// [`Self::Kind`] discriminators whose corresponding slot on
/// `self` is EMPTY, in canonical
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) order.
///
/// Default body:
/// `<Kind as ClosedSet>::ALL.iter().copied().filter(|k| !self.has(*k)).collect()`.
/// A tagged-union parent that satisfies the exactly-one-slot
/// contract returns a `Vec` of length `ALL.len()` (empty parent —
/// every slot is missing, aligns with [`Self::variant`]'s `Empty`
/// arm) or `ALL.len() - 1` (well-formed — every slot BUT the
/// populated one is missing, aligns with the `Ok` arm); a
/// malformed parent with N populated slots returns a `Vec` of
/// length `ALL.len() - N` in canonical `ALL` order (aligns with
/// the `Ambiguous` arm and NAMES which slots are absent,
/// complementing [`Self::populated_kinds`] which NAMES which are
/// populated).
///
/// # Sibling to [`Self::populated_kinds`]
///
/// Closed-set-complement peer of the closed-set-inversion widened
/// primitive — where `populated_kinds` returns the SET of
/// populated kinds, `missing_kinds` returns its COMPLEMENT within
/// `ClosedSet::ALL`. The two primitives PARTITION the closed set:
/// `populated_kinds() ∪ missing_kinds() == ClosedSet::ALL` and the
/// two sets are disjoint. The composition law
/// `missing_kinds().contains(&k) == !has(k)` for every
/// `k ∈ Kind::ALL` binds the two axes structurally through the
/// default body — a regression that overrode `missing_kinds` to
/// skip a kind, return duplicates, or drift the walk order
/// surfaces at the substrate testkit
/// [`assert_missing_kinds_matches_has`].
///
/// # Peer to [`crate::boundary::ConditionSliceExt::missing_kinds`]
///
/// Same shape, same axis, second instance in the workspace-wide
/// closed-set-complement refinement algebra:
/// [`ConditionSliceExt::missing_kinds`] returns
/// `Vec<ConditionKind>` on the slice-level presence-probe axis
/// (fixes the slice, varies over `ConditionKind::ALL` under a
/// negated predicate); `missing_kinds` here returns
/// `Vec<Self::Kind>` on the tagged-union parent-level presence-
/// probe axis (fixes the parent, varies over `<Self::Kind as
/// ClosedSet>::ALL` under a negated predicate). Both refine their
/// `has(k) / has_kind(k)` bool peer through the same
/// `ALL.filter(!has).collect()` composition law — the parent-axis
/// complement of the widened `populated_kinds` primitive.
///
/// # Compounding future consumers
///
/// - An operator-facing "which slots are still absent" diagnostic
/// on the malformed / partially-populated arm reads
/// `parent.missing_kinds()` at ONE substrate site rather than
/// paying for a negated `<Kind::ALL>.iter().filter(|k|
/// !parent.has(*k)).collect()` closure body at the callsite —
/// or the strictly-worse
/// `<Kind::ALL>.iter().filter(|k| !parent.populated_kinds().contains(k)).collect()`
/// double-loop.
/// - A future require-tag classifier arm that publishes the
/// missing-set membership at fleet audit time (`missing-<kind>`
/// as the negated peer of a hypothetical `populated-<kind>`) reads
/// `parent.missing_kinds().contains(&k)` at ONE call site.
/// - A hypothetical `missing-kind-count-<n>` require-tag
/// classifier prefix family that publishes the missing-set
/// cardinality as a scalar reads [`Self::missing_kind_count`]
/// (the scalar-cardinality peer of this widened primitive)
/// without allocating.
///
/// A new [`Self::Kind`] variant added to
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
/// this primitive mechanically (the closed-set walk picks up the
/// new entry on the missing side WITHOUT further per-caller edit
/// — any parent that doesn't yet populate the new slot sees it
/// listed as missing at every downstream callsite).
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
/// The closed-set complement lives at ONE substrate site as a
/// typed projection of [`Self::has`] over the closed set
/// `<Self::Kind as ClosedSet>::ALL` under negation. Every
/// downstream gap-analysis consumer binds through the SAME shape
/// rather than restating the negated `ALL`-filter closure body.
/// - THEORY.md §VI.1 — generation over composition. A new
/// [`Self::Kind`] variant added to `ALL` reaches this primitive
/// mechanically and every downstream consumer sees the wider
/// complement without further per-caller edit.
fn missing_kinds(&self) -> ::std::vec::Vec<Self::Kind> {
<Self::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
.filter(|k| !self.has(*k))
.collect()
}
/// Scalar cardinality refinement on the closed-set-complement axis —
/// the number of [`Self::Kind`] discriminators whose corresponding
/// slot on `self` is EMPTY.
///
/// Default body:
/// `<Self::Kind as ClosedSet>::ALL.iter().copied().filter(|k| !self.has(*k)).count()`
/// — a closed-set walk that composes against [`Self::has`] per
/// variant under a NEGATED point-probe, WITHOUT materializing an
/// intermediate `Vec`. A tagged-union parent that satisfies the
/// exactly-one-slot contract returns `ALL.len()` (empty — every
/// slot missing, matches [`Self::variant`]'s `Empty` arm),
/// `ALL.len() - 1` (well-formed — matches the `Ok` arm), or
/// `ALL.len() - N` for N-populated (malformed — matches the
/// `Ambiguous` arm), exactly aligned with [`Self::missing_kinds`]
/// `().len()` but without paying for the heap allocation a caller
/// only needing the scalar cardinality otherwise pays.
///
/// # Sibling to [`Self::missing_kinds`] / [`Self::populated_kind_count`]
///
/// Scalar projection of the closed-set-complement widened primitive
/// — where `missing_kinds` returns the SET (a `Vec<Self::Kind>` in
/// canonical `ClosedSet::ALL` order), `missing_kind_count`
/// collapses that set to its cardinality. The composition law
/// `missing_kind_count() == missing_kinds().len()` binds the
/// scalar projection to the widened primitive at the trait's
/// default body — a regression that overrode `missing_kind_count`
/// to skip a kind, double-count a slot, or drift the walk from
/// `ClosedSet::ALL` surfaces at the substrate testkit
/// [`assert_missing_kind_count_matches_missing_kinds`].
///
/// Byte-for-byte peer of [`Self::populated_kind_count`] one axis
/// over (under a negated `has` predicate): where
/// `populated_kind_count` scalar-projects the closed-set-INVERSION
/// widened primitive `populated_kinds`, this method scalar-projects
/// the closed-set-COMPLEMENT widened primitive `missing_kinds`.
/// The two scalar projections PARTITION the closed-set cardinality:
/// `populated_kind_count() + missing_kind_count() ==
/// <Self::Kind as ClosedSet>::ALL.len()` — the scalar consequence
/// of the `(populated_kinds, missing_kinds)` partition law that
/// [`assert_missing_kinds_matches_has`] pins at the widened-
/// primitive layer.
///
/// # Peer to [`crate::boundary::ConditionSliceExt::missing_kind_count`]
///
/// Same shape at the peer axis one struct layer down: fixing the
/// slice-side carrier and inverting the presence probe over the
/// closed set under a negated predicate. The two primitives close
/// the "closed-set-complement scalar cardinality" refinement at
/// two adjacent typescape sites — one per closed-set-addressed
/// slice-level refinement, one per closed-set-addressed
/// tagged-union parent-level refinement (this primitive).
///
/// # Compounding future consumers
///
/// - A `missing-kind-count-<n>` require-tag classifier prefix
/// family that publishes the missing-set cardinality as a scalar
/// (the exact use case named in [`Self::missing_kinds`]'s
/// doc-comment as a hypothetical compounding-future consumer)
/// reaches this ONE primitive without allocating.
/// - A fast-path branch on `Ambiguous`-arm callers that need to
/// distinguish "one missing slot" (well-formed exactly-one) from
/// "N missing slots" (malformed with populated_kind_count > 1)
/// reads `parent.missing_kind_count() == ALL.len() - 1` at ONE
/// call site rather than reaching for the Vec-materializing
/// widened primitive.
/// - Any coherence check that verifies "every well-formed process
/// parent has exactly `ALL.len() - 1` missing slots" now reads
/// `parent.missing_kind_count() == <Kind as ClosedSet>::ALL.len() - 1`
/// at ONE site rather than restating
/// `parent.missing_kinds().len() == ALL.len() - 1` with its
/// allocation cost, or the semantically-equivalent (but
/// parent-arm-projected) `parent.variant().is_ok()`.
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
/// The scalar cardinality lives at ONE substrate site as a typed
/// projection of [`Self::missing_kinds`] onto its `.len()`, and
/// the default body composes against [`Self::has`] over the
/// closed set `<Self::Kind as ClosedSet>::ALL` under negation
/// byte-identically to `missing_kinds` without the intermediate
/// `Vec`. Every downstream aggregate consumer binds through the
/// SAME shape rather than paying for the allocation to reach the
/// cardinality.
/// - THEORY.md §VI.1 — generation over composition. A new
/// [`Self::Kind`] variant added to `ALL` reaches this primitive
/// mechanically (the closed-set walk picks up the new entry on
/// the missing side WITHOUT further per-caller edit — any parent
/// that doesn't yet populate the new slot sees the cardinality
/// rise by one at every downstream callsite).
fn missing_kind_count(&self) -> usize {
<Self::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
.filter(|k| !self.has(*k))
.count()
}
/// Short-circuiting `Option<Self::Kind>` peer of
/// [`Self::populated_kinds`] — the FIRST populated kind on this
/// tagged union in canonical
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) order, or
/// `None` when no slot is populated.
///
/// Default body:
/// `<Kind as ClosedSet>::ALL.iter().copied().find(|k| self.has(*k))`
/// — a closed-set walk that composes against [`Self::has`] per
/// variant and SHORT-CIRCUITS at the earliest match. An empty parent
/// returns `None` (matches [`Self::variant`]'s `Empty` arm); a
/// well-formed parent returns `Some(k)` where `k` is the sole
/// populated slot (matches the `Ok` arm's variant kind through
/// [`VariantKind`]); a malformed parent with multiple populated
/// slots returns `Some(k)` where `k` is the EARLIEST populated
/// slot in canonical `ALL` order — a strictly more informative
/// projection than the payload-free [`TaggedUnionError::ambiguous`]
/// carrier, without materializing the intermediate
/// `Vec<Self::Kind>` [`Self::populated_kinds`] otherwise pays for.
///
/// # Sibling to [`Self::populated_kinds`] / [`Self::populated_kind_count`]
///
/// Third refinement on the closed-set-inversion axis, `Option<Kind>`-
/// valued: `populated_kinds` returns the SET, `populated_kind_count`
/// scalar-projects that set's cardinality, and `first_populated_kind`
/// scalar-projects the SET onto its earliest element. The
/// composition law `first_populated_kind() ==
/// populated_kinds().first().copied()` binds the earliest-element
/// projection to the widened primitive at the trait's default body —
/// pinned substrate-wide by
/// [`assert_first_populated_kind_matches_populated_kinds`]. Both
/// coarser projections agree on emptiness:
/// `first_populated_kind().is_none() == (populated_kind_count() == 0)`.
///
/// # Peer to [`Self::variant`] on the malformed arm
///
/// On well-formed parents the two projections agree
/// (`self.variant().ok().map(|v| v.variant_kind()) ==
/// first_populated_kind()`). On malformed (Ambiguous) parents they
/// diverge: `variant()` returns `Err(Ambiguous)` payload-free,
/// while `first_populated_kind()` names the earliest populated
/// slot. Operator diagnostics that want "started at X first" text
/// on the Ambiguous arm reach this ONE primitive with O(1) storage
/// and short-circuit walk cost, without paying for the widened
/// `populated_kinds().first().copied()` allocation the
/// composition law equates it to.
///
/// # Compounding future consumers
///
/// - An operator-facing "Ambiguous, starting at Nix" upgrade of the
/// payload-free [`TaggedUnionError::ambiguous`] carrier reads
/// `parent.first_populated_kind()` at ONE substrate site.
/// - A `first-populated-<kind>` require-tag classifier arm reads
/// this primitive with no allocation, byte-for-byte symmetrical
/// with `parent.has(kind)`.
/// - A fast-path branch that discriminates "empty" from "any
/// populated" reads `parent.first_populated_kind().is_some()` at
/// ONE call site rather than allocating a `Vec` through
/// `!populated_kinds().is_empty()`.
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
/// The earliest-element projection lives at ONE substrate site as
/// a typed projection of [`Self::has`] over the closed set
/// `<Self::Kind as ClosedSet>::ALL` under short-circuit walk
/// semantics. Every downstream consumer binds through the SAME
/// shape rather than reaching for
/// `populated_kinds().first().copied()` with its allocation cost.
/// - THEORY.md §VI.1 — generation over composition. A new
/// [`Self::Kind`] variant added to `ALL` reaches this primitive
/// mechanically (the closed-set walk picks up the new entry) —
/// any parent that populates only the new variant returns
/// `Some(new_variant)` at every downstream callsite without
/// further per-caller edit.
fn first_populated_kind(&self) -> Option<Self::Kind> {
<Self::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
.find(|k| self.has(*k))
}
/// Short-circuiting `Option<Self::Kind>` peer of
/// [`Self::missing_kinds`] — the FIRST missing kind on this tagged
/// union in canonical
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) order, or
/// `None` when EVERY slot is populated.
///
/// Default body:
/// `<Kind as ClosedSet>::ALL.iter().copied().find(|k| !self.has(*k))`
/// — a closed-set walk composed against [`Self::has`] per variant
/// under NEGATION with SHORT-CIRCUIT at the earliest empty slot. An
/// empty parent returns `Some(ALL[0])` (every slot missing, first
/// hit is index 0); a well-formed parent populating slot `k`
/// returns `Some(ALL[0])` if `k != ALL[0]`, else `Some(ALL[1])`
/// (the earliest non-`k` entry); a saturated parent with every
/// slot populated (structurally impossible on the exactly-one
/// contract but semantically well-defined) returns `None`.
///
/// # Sibling to [`Self::missing_kinds`] / [`Self::missing_kind_count`]
///
/// Third refinement on the closed-set-complement axis,
/// `Option<Kind>`-valued: `missing_kinds` returns the COMPLEMENT SET,
/// `missing_kind_count` scalar-projects its cardinality, and
/// `first_missing_kind` scalar-projects the SET onto its earliest
/// element. The composition law `first_missing_kind() ==
/// missing_kinds().first().copied()` binds the earliest-element
/// projection to the widened primitive at the trait's default
/// body — pinned substrate-wide by
/// [`assert_first_missing_kind_matches_missing_kinds`]. Both
/// coarser projections agree on saturation:
/// `first_missing_kind().is_none() == (missing_kind_count() == 0)`.
///
/// # Peer to [`Self::first_populated_kind`]
///
/// Closed-set-complement peer of the closed-set-inversion earliest-
/// element primitive under a negated `has` predicate. The two
/// primitives PARTITION `ClosedSet::ALL`'s earliest-element
/// projection: at least one of `first_populated_kind()` and
/// `first_missing_kind()` is `Some` on any non-degenerate closed
/// set (they are both `Some` iff `1 ≤ populated_kind_count() <
/// ALL.len()`).
///
/// # Compounding future consumers
///
/// - An operator-facing "first still-unfilled dependency" diagnostic
/// on the partially-populated arm of an aggregate boundary check
/// reads `parent.first_missing_kind()` at ONE substrate site.
/// - A `first-missing-<kind>` require-tag classifier arm reads this
/// primitive with no allocation, byte-for-byte symmetrical with
/// `parent.first_populated_kind()`.
/// - A fast-path branch that discriminates "saturated" from "at
/// least one missing" reads `parent.first_missing_kind().is_some()`
/// at ONE call site rather than allocating through
/// `!missing_kinds().is_empty()` or paying for the full
/// `missing_kind_count() > 0` walk.
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
/// The complement-earliest-element projection lives at ONE
/// substrate site as a typed projection of [`Self::has`] over the
/// closed set `<Self::Kind as ClosedSet>::ALL` under negation
/// with short-circuit walk semantics.
/// - THEORY.md §VI.1 — generation over composition. A new
/// [`Self::Kind`] variant added to `ALL` reaches this primitive
/// mechanically (the closed-set walk picks up the new entry on
/// the missing side) — every downstream consumer sees the wider
/// complement's earliest hit without further per-caller edit.
fn first_missing_kind(&self) -> Option<Self::Kind> {
<Self::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
.find(|k| !self.has(*k))
}
/// Short-circuiting `Option<Self::Kind>` peer of
/// [`Self::populated_kinds`] — the LAST populated kind on this
/// tagged union in canonical
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) order, or
/// `None` when no slot is populated.
///
/// Default body:
/// `<Kind as ClosedSet>::ALL.iter().rev().copied().find(|k|
/// self.has(*k))` — a REVERSED closed-set walk that composes
/// against [`Self::has`] per variant and SHORT-CIRCUITS at the
/// latest match. Byte-for-byte time-reversed peer of
/// [`Self::first_populated_kind`] under identical predicate
/// composition. An empty parent returns `None`; a well-formed
/// parent returns `Some(k)` where `k` is the sole populated slot
/// (matches the `Ok` arm's variant kind through [`VariantKind`]);
/// a malformed parent with multiple populated slots returns
/// `Some(k)` where `k` is the LATEST populated slot in canonical
/// `ALL` order — the operator-diagnostic peer of
/// [`Self::first_populated_kind`] on the malformed arm.
///
/// # Sibling to [`Self::first_populated_kind`]
///
/// FOURTH refinement on the closed-set-inversion axis under a
/// REVERSED walk, `Option<Kind>`-valued: together with
/// [`Self::first_populated_kind`] the two primitives project
/// [`Self::populated_kinds`] onto its endpoint pair (earliest,
/// latest). On the well-formed (exactly-one) arm they agree
/// (`first_populated_kind() == last_populated_kind()` = `Some(k)`);
/// on the empty arm they agree (`None`); on the malformed
/// (Ambiguous) arm they disagree exactly when the populated set
/// has cardinality `> 1` (the operator-diagnostic contract
/// `"Ambiguous, from X to Y"` reads both projections at ONE call
/// site through this trait's default bodies).
///
/// The composition law `last_populated_kind() ==
/// populated_kinds().last().copied()` binds the latest-element
/// projection to the widened primitive at the trait's default
/// body — pinned substrate-wide by
/// [`assert_last_populated_kind_matches_populated_kinds`]. Both
/// coarser projections agree on emptiness:
/// `last_populated_kind().is_none() == (populated_kind_count() == 0)`.
///
/// # Compounding future consumers
///
/// - The `"Ambiguous, from X to Y"` upgrade of the payload-free
/// [`TaggedUnionError::ambiguous`] carrier reads
/// `parent.first_populated_kind()` AND
/// `parent.last_populated_kind()` at TWO substrate primitives
/// with O(1) storage on each side.
/// - A `last-populated-<kind>` require-tag classifier arm reads
/// this primitive with no allocation, byte-for-byte symmetrical
/// with `parent.first_populated_kind()`.
/// - A fast-path branch that discriminates "empty" from "any
/// populated" gains a REVERSED short-circuit option
/// (`parent.last_populated_kind().is_some()`) that commits to
/// the latest-populated slot's identity rather than the
/// earliest.
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
/// The latest-element projection lives at ONE substrate site as
/// a typed projection of [`Self::has`] over the closed set
/// `<Self::Kind as ClosedSet>::ALL` under REVERSED short-circuit
/// walk semantics — byte-for-byte time-reversed peer of the
/// earliest-element projection.
/// - THEORY.md §VI.1 — generation over composition. A new
/// [`Self::Kind`] variant added to `ALL` reaches this primitive
/// mechanically (the reversed closed-set walk picks up the new
/// entry at its canonical `ALL` position) — every downstream
/// consumer sees the wider latest-hit projection with no
/// per-caller edit.
fn last_populated_kind(&self) -> Option<Self::Kind> {
<Self::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.rev()
.copied()
.find(|k| self.has(*k))
}
/// Short-circuiting `Option<Self::Kind>` peer of
/// [`Self::missing_kinds`] — the LAST missing kind on this tagged
/// union in canonical
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) order, or
/// `None` when EVERY slot is populated.
///
/// Default body:
/// `<Kind as ClosedSet>::ALL.iter().rev().copied().find(|k|
/// !self.has(*k))` — a REVERSED closed-set walk composed against
/// [`Self::has`] per variant under NEGATION with SHORT-CIRCUIT at
/// the latest empty slot. Byte-for-byte time-reversed peer of
/// [`Self::first_missing_kind`] under identical predicate
/// composition. An empty parent returns `Some(ALL[ALL.len()-1])`
/// (every slot missing, latest hit is the last index); a well-
/// formed parent populating slot `k` returns
/// `Some(ALL[ALL.len()-1])` when `k != ALL[ALL.len()-1]`, else
/// `Some(ALL[ALL.len()-2])` (the latest non-`k` entry); a
/// saturated parent returns `None`.
///
/// # Sibling to [`Self::first_missing_kind`]
///
/// FOURTH refinement on the closed-set-complement axis under a
/// REVERSED walk, `Option<Kind>`-valued: together with
/// [`Self::first_missing_kind`] the two primitives project
/// [`Self::missing_kinds`] onto its endpoint pair (earliest,
/// latest). The composition law `last_missing_kind() ==
/// missing_kinds().last().copied()` binds the latest-element
/// projection to the widened primitive at the trait's default
/// body — pinned substrate-wide by
/// [`assert_last_missing_kind_matches_missing_kinds`]. Both
/// coarser projections agree on saturation:
/// `last_missing_kind().is_none() == (missing_kind_count() == 0)`.
///
/// # Endpoint partition
///
/// Together with [`Self::first_populated_kind`],
/// [`Self::first_missing_kind`], and [`Self::last_populated_kind`],
/// this primitive closes the FOUR-corner endpoint projection of
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) on the
/// (populated, missing) × (earliest, latest) product — every
/// endpoint-addressable coherence check reads ONE of the four at
/// ONE call site without allocating a `Vec<Self::Kind>` through
/// `populated_kinds()` / `missing_kinds()`.
///
/// # Compounding future consumers
///
/// - An operator-facing "last still-unfilled dependency"
/// diagnostic on the partially-populated arm of an aggregate
/// boundary check reads `parent.last_missing_kind()` at ONE
/// substrate site.
/// - A `last-missing-<kind>` require-tag classifier arm reads this
/// primitive with no allocation, byte-for-byte symmetrical with
/// `parent.last_populated_kind()`.
/// - A fast-path branch that discriminates "saturated" from "at
/// least one missing" now has two symmetric short-circuit walk
/// options (`parent.first_missing_kind().is_some()` from the
/// FORWARD walk, `parent.last_missing_kind().is_some()` from
/// the REVERSED walk) both returning the same Boolean
/// projection but committing to different endpoint disclosures.
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
/// The complement-latest-element projection lives at ONE
/// substrate site as a typed projection of [`Self::has`] over
/// the closed set `<Self::Kind as ClosedSet>::ALL` under
/// REVERSED negation-and-short-circuit walk semantics.
/// - THEORY.md §VI.1 — generation over composition. A new
/// [`Self::Kind`] variant added to `ALL` reaches this primitive
/// mechanically (the reversed closed-set walk picks up the new
/// entry at its canonical `ALL` position on the missing side).
fn last_missing_kind(&self) -> Option<Self::Kind> {
<Self::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.rev()
.copied()
.find(|k| !self.has(*k))
}
/// Exactly-one-populated `Option<Self::Kind>` peer of
/// [`Self::populated_kinds`] — `Some(k)` iff `k` is the SOLE
/// populated kind on this tagged union, else `None`.
///
/// Default body walks `<Self::Kind as ClosedSet>::ALL` under
/// [`Self::has`] and returns `Some(k)` iff EXACTLY ONE hit is seen,
/// short-circuiting at the SECOND hit — a two-step iterator peer
/// of the earliest / latest short-circuit walks whose truth-table
/// projection is disjoint from `first_populated_kind` /
/// `last_populated_kind` on the malformed arm (both endpoints name
/// SOME populated slot on a two-populated parent, `unique` names
/// `None`).
///
/// # Sibling to [`Self::first_populated_kind`] / [`Self::last_populated_kind`]
///
/// FIFTH refinement on the closed-set-inversion axis under
/// exactly-one-hit semantics, `Option<Kind>`-valued: together with
/// [`Self::first_populated_kind`] and [`Self::last_populated_kind`]
/// the three primitives project [`Self::populated_kinds`] onto its
/// cardinality-conditioned scalar identity. On the well-formed
/// (exactly-one) arm all three agree (`unique == first == last =
/// Some(k)`); on the empty arm all three agree (`None`); on the
/// malformed (Ambiguous, cardinality ≥ 2) arm the three DIVERGE:
/// `first`/`last` name the endpoint populated slots (Some), while
/// `unique` returns `None` — the ONLY endpoint-projection primitive
/// in the algebra that distinguishes well-formed from malformed at
/// its return type without paying for a [`Self::variant`] error-
/// carrier allocation.
///
/// The composition laws
/// `unique_populated_kind().is_some() == (populated_kind_count() == 1)`
/// and (on the `Some` arm) `unique_populated_kind() ==
/// first_populated_kind() == last_populated_kind()` bind the
/// exactly-one scalar identity to the widened primitives at the
/// trait's default body — pinned substrate-wide by
/// [`assert_unique_populated_kind_matches_populated_kinds`].
///
/// # Peer to [`Self::variant`] as a kind-only projection
///
/// Byte-for-byte equivalent to
/// `self.variant().ok().map(|v| v.variant_kind())` on the trait's
/// exactly-one contract, but WITHOUT paying for the [`Self::Error`]
/// carrier's allocation on the failing arms, and WITHOUT reaching
/// [`VariantSelector::Variant`] / [`VariantKind::variant_kind`]. A
/// `use TaggedUnion` scope at the consumer is enough; the borrowed
/// variant view is not needed. On well-formed parents the two
/// projections agree; on empty AND malformed parents they agree by
/// returning `None` (unlike `first_populated_kind`, which returns
/// `Some` on malformed).
///
/// # Compounding future consumers
///
/// - A closed-set-driven "resolved kind identity" dispatch that
/// only needs the Kind (not the borrowed variant) reads
/// `parent.unique_populated_kind()` at ONE substrate site — one
/// short-circuit walk, no error-carrier allocation, no
/// VariantKind projection.
/// - A coherence check that verifies "every well-formed process
/// parent has a unique populated kind" now reads
/// `parent.unique_populated_kind().is_some()` at ONE site rather
/// than restating `parent.populated_kind_count() == 1` (which
/// discards the resolved kind identity) or
/// `parent.variant().is_ok()` (which pays for the error carrier).
/// - A future require-tag classifier arm that publishes the
/// exactly-one resolved kind (`unique-populated-<kind>`) at fleet
/// audit time reads this primitive with no allocation, byte-for-
/// byte symmetrical with the `first-populated-<kind>` and
/// `last-populated-<kind>` sibling classifier families.
/// - A fast-path branch on the (empty, well-formed, ambiguous)
/// trichotomy that needs to distinguish "well-formed with kind X"
/// from BOTH "empty" AND "ambiguous" reaches this primitive at
/// ONE call site: `Some(k)` names the well-formed arm's kind,
/// `None` collapses the two failing arms together.
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
/// The exactly-one-hit projection lives at ONE substrate site as
/// a typed two-step-short-circuit walk over
/// `<Self::Kind as ClosedSet>::ALL` under [`Self::has`]. The
/// composition laws above compose the SAME shape as the endpoint
/// projections, differing only in the truth-table arm on the
/// malformed side.
/// - THEORY.md §VI.1 — generation over composition. A new
/// [`Self::Kind`] variant added to `ALL` reaches this primitive
/// mechanically — any parent populating only the new variant
/// returns `Some(new_variant)` at every downstream callsite
/// without further per-caller edit.
fn unique_populated_kind(&self) -> Option<Self::Kind> {
let mut iter = <Self::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
.filter(|k| self.has(*k));
let first = iter.next()?;
match iter.next() {
None => Some(first),
Some(_) => None,
}
}
/// Exactly-one-missing `Option<Self::Kind>` peer of
/// [`Self::missing_kinds`] — `Some(k)` iff `k` is the SOLE missing
/// kind on this tagged union, else `None`.
///
/// Default body walks `<Self::Kind as ClosedSet>::ALL` under a
/// NEGATED [`Self::has`] predicate and returns `Some(k)` iff
/// EXACTLY ONE empty slot is seen, short-circuiting at the SECOND
/// empty slot. Byte-for-byte peer of
/// [`Self::unique_populated_kind`] under the complement axis.
///
/// # Sibling to [`Self::first_missing_kind`] / [`Self::last_missing_kind`]
///
/// FIFTH refinement on the closed-set-complement axis under
/// exactly-one-hit semantics, `Option<Kind>`-valued: together with
/// [`Self::first_missing_kind`] and [`Self::last_missing_kind`] the
/// three primitives project [`Self::missing_kinds`] onto its
/// cardinality-conditioned scalar identity on the empty side. The
/// composition laws
/// `unique_missing_kind().is_some() == (missing_kind_count() == 1)`
/// and (on the `Some` arm) `unique_missing_kind() ==
/// first_missing_kind() == last_missing_kind()` bind the exactly-
/// one scalar identity to the widened primitives at the trait's
/// default body — pinned substrate-wide by
/// [`assert_unique_missing_kind_matches_missing_kinds`].
///
/// # Truth table on the exactly-one-slot tagged-union contract
///
/// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
/// cardinality `N`:
///
/// - Empty parent (0 populated, N missing): `None` (N ≥ 2 missing
/// on any non-degenerate closed set, so not unique).
/// - Well-formed parent (1 populated, N-1 missing): `None` when
/// `N > 2` (N-1 ≥ 2 missing, not unique), `Some(the-one-missing)`
/// when `N == 2` (exactly one missing — the peer of the
/// populated slot).
/// - N-1-populated parent (structurally the missing-side peer of
/// the well-formed arm): `Some(the-lone-empty)` — the ONLY arm
/// where `unique_missing_kind` returns `Some` on a `N > 2`
/// closed set.
/// - Saturated parent (N populated, 0 missing): `None`.
///
/// # Peer to [`Self::unique_populated_kind`]
///
/// Closed-set-complement peer of the closed-set-inversion exactly-
/// one-hit primitive under a negated `has` predicate. The two
/// primitives are useful in DIFFERENT structural regimes: the
/// populated peer names well-formed parents (1 populated of N),
/// the missing peer names the missing-side complement (1 missing
/// of N). On tagged unions with `N == 2` (rare — most `ALL`s are
/// ≥ 3) the two coincide (a well-formed 1-of-2 parent has 1
/// missing too).
///
/// # Compounding future consumers
///
/// - An operator-facing "one dependency still unfulfilled: X"
/// diagnostic on an aggregate boundary check reads
/// `parent.unique_missing_kind()` at ONE substrate site — one
/// short-circuit walk, no allocation.
/// - A `unique-missing-<kind>` require-tag classifier arm reads
/// this primitive with no allocation, byte-for-byte symmetrical
/// with `parent.unique_populated_kind()`.
/// - A fast-path branch on the near-saturation arm that
/// discriminates "exactly one slot still empty" from "0 or ≥ 2
/// still empty" reads `parent.unique_missing_kind().is_some()`
/// at ONE call site.
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
/// The complement-exactly-one-hit projection lives at ONE
/// substrate site as a typed two-step-short-circuit walk over
/// `<Self::Kind as ClosedSet>::ALL` under a negated
/// [`Self::has`] predicate — byte-for-byte peer of the
/// populated-side primitive under complement.
/// - THEORY.md §VI.1 — generation over composition. A new
/// [`Self::Kind`] variant added to `ALL` reaches this primitive
/// mechanically on the missing side.
fn unique_missing_kind(&self) -> Option<Self::Kind> {
let mut iter = <Self::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
.filter(|k| !self.has(*k));
let first = iter.next()?;
match iter.next() {
None => Some(first),
Some(_) => None,
}
}
/// Boolean cardinality-endpoint peer of [`Self::populated_kinds`] —
/// `true` iff NO slot on this tagged union is populated.
///
/// Default body:
/// `!<Self::Kind as ClosedSet>::ALL.iter().copied().any(|k| self.has(k))`
/// — a short-circuiting closed-set walk under [`Self::has`] that
/// returns `true` iff every point-probe returns `false`, WITHOUT
/// materializing the [`Vec`] `populated_kinds` would build and
/// WITHOUT paying for the `usize` `populated_kind_count` would
/// count. The `!any` composition short-circuits at the FIRST
/// populated slot on the non-empty arms — strictly cheaper than
/// either widened primitive on every arm where the parent has ≥ 1
/// populated slot.
///
/// # Sibling to [`Self::populated_kind_count`]
///
/// Boolean cardinality-endpoint peer of the scalar cardinality
/// primitive — where `populated_kind_count` returns the FULL scalar
/// (any `usize` in `0..=ALL.len()`), `is_empty` collapses that
/// scalar to its zero-arm Boolean projection. The composition law
/// `is_empty() == (populated_kind_count() == 0)` binds the Boolean
/// projection to the scalar primitive at the trait's default body —
/// swept substrate-wide by
/// [`assert_is_empty_matches_populated_kind_count`]. Byte-for-byte
/// symmetrical with [`Self::is_saturated`] under the (populated,
/// missing) complement axis: where `is_empty` names the zero-arm
/// of the populated cardinality, `is_saturated` names the zero-arm
/// of the missing cardinality (equivalently, the top-arm of the
/// populated cardinality — `populated_kind_count() == ALL.len()`).
///
/// # Truth table on the exactly-one-slot tagged-union contract
///
/// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
/// cardinality `N ≥ 1`:
///
/// - Empty parent (0 populated, N missing): `true` — the SOLE
/// arm where `is_empty` returns `true`. Aligns with
/// [`Self::variant`]'s `Empty` arm (which returns
/// [`TaggedUnionError::empty`] carrying `KIND_LIST` verbatim).
/// The [`Self::empty`](TaggedUnionError::empty) factory produces
/// parents on this arm — pins one direction of the "empty ↔
/// is_empty()" symmetry.
/// - Well-formed parent (1 populated, N-1 missing): `false`.
/// - K-populated parent for `1 ≤ K ≤ N`: `false`.
/// - Saturated parent (N populated, 0 missing): `false`.
///
/// # Compounding future consumers
///
/// - A fast-path branch that discriminates "any content at all"
/// from "empty carrier" — the most common tagged-union top-level
/// guard — reads `parent.is_empty()` at ONE substrate site with
/// ONE short-circuit walk (returns at the first populated slot),
/// rather than reaching for either `populated_kind_count() == 0`
/// (which walks every slot) or `!variant().is_ok()` (which pays
/// for the borrowed-view projection and the error-carrier
/// materialization on failing arms).
/// - An operator-facing "carrier missing content" diagnostic on
/// the `Empty` arm of [`Self::variant`] reads `parent.is_empty()`
/// at ONE substrate site — one short-circuit walk, no allocation,
/// no error-carrier materialization.
/// - An `is-empty` require-tag classifier arm reaches this
/// primitive at ONE call site, byte-for-byte symmetrical with
/// the sibling `is-saturated` arm.
/// - A coherence check verifying "every well-formed parent has at
/// least one populated slot" reads `!parent.is_empty()` at ONE
/// site rather than the widened-primitive composition
/// `!parent.populated_kinds().is_empty()` (which pays for the
/// Vec) or `parent.populated_kind_count() > 0` (which walks every
/// slot).
///
/// A new [`Self::Kind`] variant added to
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
/// this primitive mechanically (the closed-set walk picks up the
/// new entry as an additional short-circuit slot — a parent that
/// populates ONLY the new variant returns `false` at every
/// downstream callsite without further per-caller edit; an all-
/// empty parent continues to return `true` past every entry
/// including the new one).
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
/// The Boolean cardinality-endpoint projection lives at ONE
/// substrate site as a typed short-circuiting closed-set walk
/// `!<Self::Kind as ClosedSet>::ALL.iter().any(has)` — byte-
/// for-byte peer of `populated_kind_count()` composed against
/// `== 0`, but without the counter allocation on every arm and
/// with a first-populated-slot short-circuit that neither
/// widened primitive offers.
/// - THEORY.md §VI.1 — generation over composition. A new
/// [`Self::Kind`] variant added to `ALL` reaches this primitive
/// mechanically through the `any` short-circuit.
fn is_empty(&self) -> bool {
!<Self::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
.any(|k| self.has(k))
}
/// Boolean cardinality-endpoint peer of [`Self::missing_kinds`] —
/// `true` iff EVERY slot on this tagged union is populated (i.e.
/// the missing set is empty).
///
/// Default body:
/// `<Self::Kind as ClosedSet>::ALL.iter().copied().all(|k| self.has(k))`
/// — a short-circuiting closed-set walk under [`Self::has`] that
/// returns `true` iff every point-probe returns `true`, WITHOUT
/// materializing the [`Vec`] `missing_kinds` would build and
/// WITHOUT paying for the `usize` `missing_kind_count` would
/// count. The `all` composition short-circuits at the FIRST
/// missing slot on the non-saturated arms — strictly cheaper than
/// either widened primitive on every arm where the parent has ≥ 1
/// missing slot.
///
/// # Sibling to [`Self::missing_kind_count`]
///
/// Boolean cardinality-endpoint peer of the scalar cardinality
/// primitive — where `missing_kind_count` returns the FULL scalar
/// (any `usize` in `0..=ALL.len()`), `is_saturated` collapses that
/// scalar to its zero-arm Boolean projection. The composition law
/// `is_saturated() == (missing_kind_count() == 0)` binds the
/// Boolean projection to the scalar primitive at the trait's
/// default body — swept substrate-wide by
/// [`assert_is_saturated_matches_missing_kind_count`]. Byte-for-
/// byte symmetrical with [`Self::is_empty`] under the (populated,
/// missing) complement axis: where `is_empty` names the zero-arm
/// of the populated cardinality, `is_saturated` names the zero-arm
/// of the missing cardinality.
///
/// # Truth table on the exactly-one-slot tagged-union contract
///
/// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
/// cardinality `N ≥ 1`:
///
/// - Empty parent (0 populated, N missing): `false`.
/// - Well-formed parent (1 populated, N-1 missing): `false` (on
/// any `N ≥ 2` closed set). On the degenerate `N == 1` closed
/// set the well-formed and saturated arms coincide — both
/// primitives return `false` on the empty arm and `true` on the
/// single-populated arm — but real-world tagged unions in this
/// workspace all have `N ≥ 2`.
/// - K-populated parent for `0 ≤ K < N`: `false`.
/// - Saturated parent (N populated, 0 missing): `true` — the SOLE
/// arm where `is_saturated` returns `true`.
///
/// # Compounding future consumers
///
/// - A fast-path branch that discriminates "over-populated"
/// (saturated, structurally malformed on any `N ≥ 2` tagged
/// union) from "well-formed or partial" reads
/// `parent.is_saturated()` at ONE substrate site with ONE short-
/// circuit walk (returns at the first missing slot), rather than
/// reaching for either `missing_kind_count() == 0` (which walks
/// every slot) or `populated_kind_count() == ALL.len()` (same
/// cost, different axis).
/// - An operator-facing "over-populated carrier" diagnostic that
/// surfaces the pathological case where every slot on a `N ≥ 2`
/// tagged union is populated reads `parent.is_saturated()` at
/// ONE substrate site — one short-circuit walk, no allocation.
/// - An `is-saturated` require-tag classifier arm reaches this
/// primitive at ONE call site, byte-for-byte symmetrical with
/// the sibling `is-empty` arm.
/// - A coherence check verifying "no production tagged union has
/// ever been observed saturated" reads `!parent.is_saturated()`
/// at ONE site — the substrate's structural pin on the top-arm
/// of the cardinality lattice.
///
/// A new [`Self::Kind`] variant added to
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
/// this primitive mechanically (the closed-set walk picks up the
/// new entry as an additional short-circuit slot — a parent that
/// was previously saturated is no longer saturated at every
/// downstream callsite unless it also populates the new slot; a
/// parent that populates every slot including the new one
/// continues to return `true`).
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
/// The Boolean cardinality-top-endpoint projection lives at ONE
/// substrate site as a typed short-circuiting closed-set walk
/// `<Self::Kind as ClosedSet>::ALL.iter().all(has)` — byte-for-
/// byte peer of `missing_kind_count()` composed against `== 0`,
/// but without the counter allocation on every arm and with a
/// first-missing-slot short-circuit that neither widened
/// primitive offers.
/// - THEORY.md §VI.1 — generation over composition. A new
/// [`Self::Kind`] variant added to `ALL` reaches this primitive
/// mechanically through the `all` short-circuit.
fn is_saturated(&self) -> bool {
<Self::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
.all(|k| self.has(k))
}
/// Boolean cardinality "at-least-one" peer of
/// [`Self::populated_kinds`] — `true` iff AT LEAST ONE slot on this
/// tagged union is populated (i.e. the populated set is NON-empty).
///
/// Default body:
/// `<Self::Kind as ClosedSet>::ALL.iter().copied().any(|k| self.has(k))`
/// — a short-circuiting closed-set walk under [`Self::has`] that
/// returns `true` at the FIRST populated slot, WITHOUT materializing
/// the [`Vec`] `populated_kinds` would build and WITHOUT paying for
/// the `usize` `populated_kind_count` would count. The `any`
/// composition short-circuits at the FIRST populated slot on every
/// non-empty arm — strictly cheaper than either widened primitive
/// `populated_kind_count() > 0` (which walks every slot) or
/// `!populated_kinds().is_empty()` (which pays for the `Vec`
/// allocation before the emptiness check).
///
/// # Sibling to [`Self::is_empty`]
///
/// Definitional-complement Boolean peer on the SAME populated
/// cardinality axis: where [`Self::is_empty`] names the zero-arm
/// (0 populated), `has_any_populated_kind` names the ≥ 1 halfspace
/// (any positive cardinality). The composition law
/// `has_any_populated_kind() == !is_empty()` binds the two primitives
/// at the trait's default body — one bit-flip past [`Self::is_empty`]'s
/// `!any` short-circuit. Byte-for-byte peer of
/// [`Self::has_any_missing_kind`] under the (populated, missing)
/// complement axis: where `has_any_missing_kind` names the ≥ 1
/// missing halfspace via the negated `has`, this primitive names
/// the ≥ 1 populated halfspace via the plain `has`.
///
/// # Cardinality-grid closure
///
/// Third row of the Boolean cardinality grid on the tagged-union
/// parent axis — the SUBSET side of the complement dichotomy between
/// the zero-arm and the at-least-one halfspace. The four rows now
/// close the {0, ≥1, =1, ≥2} cardinality lattice on both the
/// populated and missing axes:
///
/// | | populated axis | missing axis |
/// |----------------|-----------------------------------------|----------------------------------------|
/// | ZERO (== 0) | [`Self::is_empty`] | [`Self::is_saturated`] |
/// | AT LEAST ONE | `has_any_populated_kind` (this) | [`Self::has_any_missing_kind`] |
/// | UNIQUE (== 1) | [`Self::has_unique_populated_kind`] | [`Self::has_unique_missing_kind`] |
/// | AT LEAST TWO | [`Self::has_multiple_populated_kinds`] | [`Self::has_multiple_missing_kinds`] |
///
/// The AT LEAST ONE row partitions the ZERO row's exhaustive
/// complement — for any given parent, `is_empty()` and
/// `has_any_populated_kind()` XOR to `true` (exactly one returns
/// `true`). The row is ALSO the disjunction of the UNIQUE and AT
/// LEAST TWO rows: `has_any_populated_kind() ==
/// has_unique_populated_kind() || has_multiple_populated_kinds()`
/// — the {=1, ≥2} refinement of the ≥ 1 halfspace at ONE substrate
/// site.
///
/// # Truth table on the exactly-one-slot tagged-union contract
///
/// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
/// cardinality `N ≥ 1`:
///
/// - Empty parent (0 populated, N missing): `false` — the SOLE arm
/// where `has_any_populated_kind` returns `false`.
/// - Well-formed parent (1 populated, N-1 missing): `true`.
/// - K-populated parent for `1 ≤ K ≤ N`: `true`.
/// - Saturated parent (N populated, 0 missing): `true`.
///
/// # Compounding future consumers
///
/// - A boundary-progress "any content at all" diagnostic on an
/// aggregate condition-carrier reads
/// `parent.has_any_populated_kind()` at ONE substrate site — one
/// short-circuit walk, no allocation, and no readerly parse of
/// `!parent.is_empty()` inversion at the callsite.
/// - An `is-non-empty` require-tag classifier arm reaches this
/// primitive at ONE call site — the SUBSET peer of the sibling
/// `is-empty` classifier arm, byte-for-byte symmetrical with the
/// sibling `has-any-missing-kind` arm under the (populated,
/// missing) complement axis.
/// - A fast-path branch that discriminates "some populated" from
/// "all missing" (the resolver's non-`Empty`-arm halfspace) reads
/// `parent.has_any_populated_kind()` at ONE call site — same
/// FIRST-populated-slot short-circuit as [`Self::is_empty`], no
/// inversion.
/// - A coherence check verifying "every production parent from a
/// `single_slot_X` factory is NON-empty" reads
/// `parent.has_any_populated_kind()` at ONE site rather than
/// `!parent.is_empty()` (which asks the reader to invert the
/// parse) or `parent.populated_kind_count() > 0` (which walks
/// every slot).
///
/// A new [`Self::Kind`] variant added to
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
/// this primitive mechanically — the `any` short-circuit picks up
/// the new slot as an additional first-hit candidate at every
/// downstream callsite without further per-caller edit.
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
/// The Boolean at-least-one projection on the populated axis
/// lives at ONE substrate site as a typed short-circuiting
/// closed-set walk `<Self::Kind as ClosedSet>::ALL.iter().any(has)`
/// — byte-for-byte definitional complement of [`Self::is_empty`]'s
/// `!<ALL>.iter().any(has)`, semantically identical to
/// `populated_kind_count() > 0` on every arm with the same
/// first-hit short-circuit that [`Self::is_empty`] enjoys.
/// - THEORY.md §VI.1 — generation over composition. A new
/// [`Self::Kind`] variant added to `ALL` reaches this primitive
/// mechanically through the `any` short-circuit.
fn has_any_populated_kind(&self) -> bool {
<Self::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
.any(|k| self.has(k))
}
/// Boolean cardinality "at-least-one" peer of [`Self::missing_kinds`]
/// — `true` iff AT LEAST ONE slot on this tagged union is missing
/// (i.e. the missing set is NON-empty).
///
/// Default body:
/// `<Self::Kind as ClosedSet>::ALL.iter().copied().any(|k| !self.has(k))`
/// — a short-circuiting closed-set walk under a NEGATED [`Self::has`]
/// that returns `true` at the FIRST missing slot, WITHOUT
/// materializing the [`Vec`] `missing_kinds` would build and WITHOUT
/// paying for the `usize` `missing_kind_count` would count. The
/// `any` composition short-circuits at the FIRST missing slot on
/// every non-saturated arm — strictly cheaper than either widened
/// primitive `missing_kind_count() > 0` (which walks every slot) or
/// `!missing_kinds().is_empty()` (which pays for the `Vec`
/// allocation before the emptiness check).
///
/// # Sibling to [`Self::is_saturated`]
///
/// Definitional-complement Boolean peer on the SAME missing
/// cardinality axis: where [`Self::is_saturated`] names the zero-arm
/// (0 missing), `has_any_missing_kind` names the ≥ 1 missing
/// halfspace (any positive missing cardinality). The composition
/// law `has_any_missing_kind() == !is_saturated()` binds the two
/// primitives at the trait's default body — one bit-flip past
/// [`Self::is_saturated`]'s `all` short-circuit. Byte-for-byte peer
/// of [`Self::has_any_populated_kind`] under the (populated,
/// missing) complement axis: where `has_any_populated_kind` names
/// the ≥ 1 populated halfspace via the plain `has`, this primitive
/// names the ≥ 1 missing halfspace via the negated `has`.
///
/// # Cardinality-grid closure
///
/// Third row of the Boolean cardinality grid on the tagged-union
/// parent axis — see [`Self::has_any_populated_kind`] for the full
/// grid. The disjunctive decomposition
/// `has_any_missing_kind() == has_unique_missing_kind() ||
/// has_multiple_missing_kinds()` binds the ≥ 1 halfspace to the
/// {=1, ≥2} refinement at ONE substrate site — byte-for-byte peer
/// of the populated-axis disjunctive decomposition.
///
/// # Truth table on the exactly-one-slot tagged-union contract
///
/// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
/// cardinality `N ≥ 1`:
///
/// - Empty parent (0 populated, N missing): `true` — the empty
/// parent has EVERY slot missing.
/// - Well-formed parent (1 populated, N-1 missing): `true` on any
/// `N ≥ 2`. On the degenerate `N == 1` closed set the well-formed
/// parent has 0 missing, so `has_any_missing_kind()` returns
/// `false` — but real-world tagged unions in this workspace all
/// have `N ≥ 2`.
/// - K-populated parent for `0 ≤ K < N`: `true`.
/// - Saturated parent (N populated, 0 missing): `false` — the SOLE
/// arm where `has_any_missing_kind` returns `false`.
///
/// # Compounding future consumers
///
/// - An operator-facing "not fully populated" diagnostic on an
/// aggregate condition-carrier reads
/// `parent.has_any_missing_kind()` at ONE substrate site — one
/// short-circuit walk, no allocation, no readerly parse of
/// `!parent.is_saturated()` inversion at the callsite.
/// - A `has-any-missing-kind` require-tag classifier arm reaches
/// this primitive at ONE call site — the SUBSET peer of the
/// sibling `is-saturated` classifier arm, closed-set-complement
/// mirror of `has-any-populated-kind` on the populated axis.
/// - A fast-path branch that discriminates "any slot still absent"
/// from "over-populated / saturated" reads
/// `parent.has_any_missing_kind()` at ONE call site — same
/// FIRST-missing-slot short-circuit as [`Self::is_saturated`],
/// no inversion.
/// - A coherence check verifying "no production parent from a
/// `single_slot_X` factory is saturated" reads
/// `parent.has_any_missing_kind()` at ONE site — every
/// `ALL.len() ≥ 2` well-formed parent leaves `ALL.len() - 1 ≥ 1`
/// slot missing, so this predicate is a substrate structural pin
/// on the well-formed diagonal.
///
/// A new [`Self::Kind`] variant added to
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
/// this primitive mechanically — the `any` short-circuit picks up
/// the new slot as an additional first-hit candidate at every
/// downstream callsite without further per-caller edit.
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
/// The Boolean at-least-one projection on the missing axis lives
/// at ONE substrate site as a typed short-circuiting closed-set
/// walk `<Self::Kind as ClosedSet>::ALL.iter().any(|k| !has(k))`
/// — byte-for-byte definitional complement of
/// [`Self::is_saturated`]'s `<ALL>.iter().all(has)` (via the De
/// Morgan dual), semantically identical to
/// `missing_kind_count() > 0` on every arm with the same first-
/// hit short-circuit that [`Self::is_saturated`] enjoys.
/// - THEORY.md §VI.1 — generation over composition. A new
/// [`Self::Kind`] variant added to `ALL` reaches this primitive
/// mechanically through the `any` short-circuit.
fn has_any_missing_kind(&self) -> bool {
<Self::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
.any(|k| !self.has(k))
}
/// Boolean cardinality-mid-endpoint peer of
/// [`Self::unique_populated_kind`] — `true` iff EXACTLY ONE slot on
/// this tagged union is populated.
///
/// Default body: `self.unique_populated_kind().is_some()` — the
/// Boolean projection of the two-step-short-circuit closed-set walk
/// [`Self::unique_populated_kind`] already performs, without paying
/// for the [`Vec`] `populated_kinds` would build or the counter
/// walk `populated_kind_count` would perform. The `unique_*`
/// primitive short-circuits at the SECOND populated slot on the
/// malformed arms, so the `is_some` projection here short-circuits
/// on the same schedule — strictly cheaper than the widened
/// primitives on every arm where the parent has ≥ 2 populated
/// slots.
///
/// # Sibling to [`Self::populated_kind_count`]
///
/// Boolean cardinality-mid-endpoint peer of the scalar cardinality
/// primitive — where `populated_kind_count` returns the FULL scalar
/// (any `usize` in `0..=ALL.len()`), `has_unique_populated_kind`
/// collapses that scalar to its one-arm Boolean projection. The
/// composition law
/// `has_unique_populated_kind() == (populated_kind_count() == 1)`
/// binds the Boolean projection to the scalar primitive at the
/// trait's default body — swept substrate-wide by
/// [`assert_has_unique_populated_kind_matches_populated_kind_count`].
/// Together with [`Self::is_empty`] (zero-arm of the populated
/// axis) and [`Self::is_saturated`] (zero-arm of the missing
/// axis), these three Boolean cardinality primitives close the
/// substrate's 2×2 endpoint grid on the tagged-union parent axis:
///
/// | | populated | missing |
/// |----------|-------------------------------|--------------------------------|
/// | zero-arm | [`Self::is_empty`] | [`Self::is_saturated`] |
/// | one-arm | [`Self::has_unique_populated_kind`] | [`Self::has_unique_missing_kind`] |
///
/// # Truth table on the exactly-one-slot tagged-union contract
///
/// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
/// cardinality `N ≥ 2`:
///
/// - Empty parent (0 populated, N missing): `false`.
/// - Well-formed parent (1 populated, N-1 missing): `true` — the
/// SOLE arm where `has_unique_populated_kind` returns `true`.
/// Aligns with [`Self::variant`]'s `Ok` arm (the single-populated
/// arm where the resolver returns exactly one variant) — this
/// primitive is the `bool`-valued projection of that Ok arm.
/// - K-populated parent for `K ≥ 2`: `false`.
/// - Saturated parent (N populated, 0 missing on any `N ≥ 2`
/// closed set): `false`.
///
/// # Compounding future consumers
///
/// - A fast-path branch that discriminates "well-formed" from
/// "empty or ambiguous" reads `parent.has_unique_populated_kind()`
/// at ONE substrate site with the same two-step short-circuit
/// walk `unique_populated_kind` already performs, rather than
/// reaching for `parent.variant().is_ok()` (which pays for the
/// borrowed-view projection AND the error-carrier
/// materialization on failing arms) or
/// `parent.populated_kind_count() == 1` (which walks every slot).
/// - An operator-facing "well-formed" diagnostic on the resolver's
/// Ok arm reads `parent.has_unique_populated_kind()` at ONE
/// substrate site — one two-step short-circuit walk, no
/// allocation, no borrowed-view materialization.
/// - A `has-unique-populated-kind` require-tag classifier arm
/// reaches this primitive at ONE call site, byte-for-byte
/// symmetrical with the sibling `is-empty` / `is-saturated` /
/// `has-unique-missing-kind` arms across the closed 2×2 grid.
/// - A coherence check verifying "every production parent from a
/// `single_slot_X` factory is well-formed" reads
/// `parent.has_unique_populated_kind()` at ONE site rather than
/// the widened-primitive composition
/// `parent.populated_kind_count() == 1`.
///
/// A new [`Self::Kind`] variant added to
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
/// this primitive mechanically through the `unique_populated_kind`
/// short-circuit (the closed-set walk picks up the new entry as an
/// additional short-circuit slot — a parent that populates ONLY
/// the new variant returns `true` at every downstream callsite
/// without further per-caller edit).
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
/// The Boolean cardinality-mid-endpoint projection lives at ONE
/// substrate site as the `is_some` projection of the
/// `unique_populated_kind` two-step short-circuit walk — byte-
/// for-byte peer of `populated_kind_count()` composed against
/// `== 1`, but with a second-populated-slot short-circuit that
/// the scalar counter primitive does not offer.
/// - THEORY.md §VI.1 — generation over composition. A new
/// [`Self::Kind`] variant added to `ALL` reaches this primitive
/// mechanically through the `unique_populated_kind` short-circuit.
fn has_unique_populated_kind(&self) -> bool {
self.unique_populated_kind().is_some()
}
/// Boolean cardinality-mid-endpoint peer of
/// [`Self::unique_missing_kind`] — `true` iff EXACTLY ONE slot on
/// this tagged union is missing.
///
/// Default body: `self.unique_missing_kind().is_some()` — the
/// Boolean projection of the two-step-short-circuit closed-set
/// walk [`Self::unique_missing_kind`] already performs under a
/// negated `has` predicate, without paying for the [`Vec`]
/// `missing_kinds` would build or the counter walk
/// `missing_kind_count` would perform. The `unique_*` primitive
/// short-circuits at the SECOND missing slot on the partial arms,
/// so the `is_some` projection here short-circuits on the same
/// schedule — strictly cheaper than the widened primitives on
/// every arm where the parent has ≥ 2 missing slots.
///
/// # Sibling to [`Self::missing_kind_count`]
///
/// Boolean cardinality-mid-endpoint peer of the scalar complement
/// cardinality primitive — where `missing_kind_count` returns the
/// FULL scalar (any `usize` in `0..=ALL.len()`),
/// `has_unique_missing_kind` collapses that scalar to its one-arm
/// Boolean projection. The composition law
/// `has_unique_missing_kind() == (missing_kind_count() == 1)`
/// binds the Boolean projection to the scalar primitive at the
/// trait's default body — swept substrate-wide by
/// [`assert_has_unique_missing_kind_matches_missing_kind_count`].
/// Byte-for-byte symmetrical with [`Self::has_unique_populated_kind`]
/// under the (populated, missing) complement axis.
///
/// # Truth table on the exactly-one-slot tagged-union contract
///
/// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
/// cardinality `N ≥ 2`:
///
/// - Empty parent (0 populated, N missing): `false` on any
/// `N ≥ 2` closed set (on the degenerate `N == 1` closed set
/// empty and one-missing coincide; no production tagged union
/// in this workspace has `N == 1`).
/// - Well-formed parent (1 populated, N-1 missing): `false` on
/// any `N ≥ 3` closed set. On `N == 2` well-formed and one-
/// missing coincide — the primitive returns `true` because
/// `N - 1 == 1`.
/// - K-populated parent for `2 ≤ K ≤ N-1` on `N ≥ 3` closed sets:
/// `false` in general; `true` only on the `(N-1)`-populated arm
/// (near-saturation, one slot missing).
/// - Saturated parent (N populated, 0 missing): `false`.
///
/// # Compounding future consumers
///
/// - A fast-path branch on the near-saturation arm (exactly one
/// slot missing, structurally malformed on any `N ≥ 3` tagged
/// union in that it composes multiple populated slots) reads
/// `parent.has_unique_missing_kind()` at ONE substrate site
/// with the same two-step short-circuit walk
/// `unique_missing_kind` already performs, rather than reaching
/// for `parent.missing_kind_count() == 1` (which walks every
/// slot).
/// - An operator-facing "one slot away from saturated" diagnostic
/// on the near-saturation arm reads
/// `parent.has_unique_missing_kind()` at ONE substrate site.
/// - A `has-unique-missing-kind` require-tag classifier arm
/// reaches this primitive at ONE call site, byte-for-byte
/// symmetrical with the sibling `has-unique-populated-kind` arm
/// under the (populated, missing) complement axis.
///
/// A new [`Self::Kind`] variant added to
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
/// this primitive mechanically through the `unique_missing_kind`
/// short-circuit.
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
/// The Boolean cardinality-mid-endpoint projection on the
/// missing axis lives at ONE substrate site as the `is_some`
/// projection of the `unique_missing_kind` two-step short-circuit
/// walk — byte-for-byte peer of `missing_kind_count()` composed
/// against `== 1`, but with a second-missing-slot short-circuit
/// that the scalar counter primitive does not offer.
/// - THEORY.md §VI.1 — generation over composition. A new
/// [`Self::Kind`] variant added to `ALL` reaches this primitive
/// mechanically through the `unique_missing_kind` short-circuit.
fn has_unique_missing_kind(&self) -> bool {
self.unique_missing_kind().is_some()
}
/// Boolean cardinality many-arm peer of
/// [`Self::has_unique_populated_kind`] — `true` iff TWO OR MORE
/// slots on this tagged union are populated.
///
/// Default body: a two-step-short-circuit closed-set walk under
/// [`Self::has`] that pulls two hits off the filtered iterator
/// and returns `true` iff both are `Some`, WITHOUT paying for the
/// [`Vec`] `populated_kinds` would build or the counter walk
/// `populated_kind_count` would perform. Short-circuits at the
/// SECOND populated slot — strictly cheaper than either widened
/// primitive on every arm past the second populated slot.
///
/// # Sibling to the Boolean cardinality trichotomy
///
/// Third arm of the {0, 1, ≥2} cardinality trichotomy on the
/// populated axis, closing the natural partition alongside
/// [`Self::is_empty`] (zero-arm) and
/// [`Self::has_unique_populated_kind`] (one-arm). Every tagged-
/// union state satisfies EXACTLY ONE of the three predicates —
/// the three Boolean projections partition
/// `0..=<Self::Kind as ClosedSet>::ALL.len()` at 0, 1, and ≥2
/// respectively. Maps directly onto the three arms of the
/// resolver contract [`Self::variant`] returns:
///
/// | populated count | Boolean primitive | `variant()` |
/// |-----------------|-----------------------------------------|-------------------------|
/// | 0 | [`Self::is_empty`] | `Err(Error::empty)` |
/// | 1 | [`Self::has_unique_populated_kind`] | `Ok(Variant)` |
/// | ≥ 2 | `has_multiple_populated_kinds` (this) | `Err(Error::ambiguous)` |
///
/// The composition law `has_multiple_populated_kinds() ==
/// (populated_kind_count() >= 2)` binds the Boolean projection
/// to the scalar primitive at the trait's default body — swept
/// substrate-wide by
/// [`assert_has_multiple_populated_kinds_matches_populated_kind_count`].
///
/// # Truth table on the exactly-one-slot tagged-union contract
///
/// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
/// cardinality `N ≥ 2`:
///
/// - Empty parent (0 populated): `false`.
/// - Well-formed parent (1 populated): `false`.
/// - K-populated parent for `K ≥ 2`: `true`.
/// - Saturated parent (N populated, `N ≥ 2`): `true`.
///
/// # Compounding future consumers
///
/// - A fast-path branch that discriminates "ambiguous" from
/// "empty or well-formed" reads
/// `parent.has_multiple_populated_kinds()` at ONE substrate
/// site with a two-step short-circuit walk, rather than
/// `parent.variant().is_err_and(|e| matches!(e,
/// TaggedUnionError::Ambiguous))` (which materializes the
/// borrowed-view AND the error-carrier) or
/// `parent.populated_kind_count() >= 2` (which walks every
/// slot).
/// - An operator-facing "over-populated / ambiguous carrier"
/// diagnostic reads `parent.has_multiple_populated_kinds()`
/// at ONE substrate site — one two-step short-circuit walk,
/// no allocation.
/// - A `has-multiple-populated-kinds` require-tag classifier
/// arm reaches this primitive at ONE call site, byte-for-byte
/// symmetrical with the sibling zero-arm / one-arm classifier
/// arms across the closed 2×3 grid.
///
/// A new [`Self::Kind`] variant added to
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
/// this primitive mechanically — the closed-set walk picks up
/// the new slot as an additional two-step-short-circuit
/// candidate.
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
/// The Boolean cardinality many-arm projection lives at ONE
/// substrate site as a typed two-step-short-circuit walk over
/// `<Self::Kind as ClosedSet>::ALL` under [`Self::has`] — byte-
/// for-byte peer of `populated_kind_count()` composed against
/// `>= 2`, but with a second-populated-slot short-circuit that
/// the scalar counter primitive does not offer.
/// - THEORY.md §VI.1 — generation over composition. A new
/// [`Self::Kind`] variant added to `ALL` reaches this
/// primitive mechanically.
fn has_multiple_populated_kinds(&self) -> bool {
let mut iter = <Self::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
.filter(|k| self.has(*k));
iter.next().is_some() && iter.next().is_some()
}
/// Boolean cardinality many-arm peer of
/// [`Self::has_unique_missing_kind`] — `true` iff TWO OR MORE
/// slots on this tagged union are missing.
///
/// Default body: a two-step-short-circuit closed-set walk under
/// a NEGATED [`Self::has`] predicate that pulls two hits off the
/// filtered iterator and returns `true` iff both are `Some`.
/// Byte-for-byte peer of [`Self::has_multiple_populated_kinds`]
/// under the (populated, missing) complement axis.
///
/// # Sibling to the Boolean cardinality trichotomy
///
/// Third arm of the {0, 1, ≥2} cardinality trichotomy on the
/// missing axis, closing the natural partition alongside
/// [`Self::is_saturated`] (zero-arm) and
/// [`Self::has_unique_missing_kind`] (one-arm). The composition
/// law `has_multiple_missing_kinds() == (missing_kind_count() >=
/// 2)` binds the Boolean projection to the scalar complement
/// cardinality primitive at the trait's default body — swept
/// substrate-wide by
/// [`assert_has_multiple_missing_kinds_matches_missing_kind_count`].
///
/// # Truth table on the exactly-one-slot tagged-union contract
///
/// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
/// cardinality `N`:
///
/// - Empty parent (0 populated, N missing): `true` iff `N ≥ 2`
/// (every production union in the workspace).
/// - Well-formed parent (1 populated, N-1 missing): `true` iff
/// `N ≥ 3`. On `N == 2` the well-formed arm has exactly one
/// missing slot, so this primitive returns `false`.
/// - K-populated parent for `K ≤ N-2`: `true`.
/// - Near-saturated parent (N-1 populated, 1 missing): `false`
/// (exactly one missing, not many).
/// - Saturated parent (N populated, 0 missing): `false`.
///
/// # Compounding future consumers
///
/// - A fast-path branch that discriminates "≥ 2 slots still
/// unfulfilled" from "0 or 1 slot still unfulfilled" (an
/// aggregate boundary progress-guard: at least two conditions
/// still open) reads `parent.has_multiple_missing_kinds()` at
/// ONE substrate site.
/// - An operator-facing "≥ 2 dependencies still unfulfilled"
/// diagnostic reads `parent.has_multiple_missing_kinds()` at
/// ONE substrate site — one two-step short-circuit walk under
/// the negated predicate.
/// - A `has-multiple-missing-kinds` require-tag classifier arm
/// reaches this primitive at ONE call site, byte-for-byte
/// symmetrical with `has_multiple_populated_kinds` under the
/// complement axis.
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
/// - THEORY.md §VI.1 — generation over composition.
fn has_multiple_missing_kinds(&self) -> bool {
let mut iter = <Self::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
.filter(|k| !self.has(*k));
iter.next().is_some() && iter.next().is_some()
}
/// Boolean cardinality "≤ 1" peer of
/// [`Self::has_multiple_populated_kinds`] — `true` iff AT MOST ONE
/// slot on this tagged union is populated (i.e. zero or one
/// populated slot).
///
/// Default body: the definitional Boolean negation
/// `!self.has_multiple_populated_kinds()` — one bit-flip over the
/// SAME two-step-short-circuit closed-set walk that
/// [`Self::has_multiple_populated_kinds`] already runs, without
/// re-authoring the fused loop and WITHOUT a second walk over the
/// closed set. Strictly cheaper than either widened composition
/// `self.is_empty() || self.has_unique_populated_kind()` (which
/// walks the closed set TWICE — once under `all-missing`, once
/// under `exactly-one`) or `self.populated_kind_count() <= 1`
/// (which walks the closed set fully counting hits) on every arm.
///
/// # Sibling to the Boolean cardinality "≥ 2" primitive
///
/// Boolean-negation peer under `!(≥ 2) == (≤ 1)` — where
/// [`Self::has_multiple_populated_kinds`] names the AMBIGUOUS arm
/// of the resolver contract (the arm [`Self::variant`] returns
/// `Err(Error::ambiguous)` on), `has_at_most_one_populated_kind`
/// names its complement — the RESOLVEABLE-OR-EMPTY arm (the two
/// arms of the resolver contract that DON'T return
/// `Err(Error::ambiguous)`, i.e. `Ok(Variant)` OR
/// `Err(Error::empty)`). The typed predicate for "this parent is
/// not ambiguous" without inverting a
/// `!parent.has_multiple_populated_kinds()` at every callsite.
///
/// # Composition laws
///
/// - `has_at_most_one_populated_kind() == !has_multiple_populated_kinds()`
/// — the definitional Boolean negation, at the trait default
/// body's SAME fused short-circuit walk.
/// - `has_at_most_one_populated_kind() == (populated_kind_count() <= 1)`
/// — the scalar cardinality composition.
/// - `has_at_most_one_populated_kind() == is_empty() || has_unique_populated_kind()`
/// — the union of the zero-arm and the one-arm of the
/// {0, 1, ≥ 2} cardinality trichotomy.
///
/// All three laws hold on every arm and every closed-set kind —
/// pinned as first-class typed invariants by the trait's own
/// default body and swept substrate-wide by
/// [`assert_has_at_most_one_populated_kind_matches_populated_kind_count`].
///
/// # Truth table on the exactly-one-slot tagged-union contract
///
/// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
/// cardinality `N ≥ 2`:
///
/// - Empty parent (0 populated, N missing): `true` (0 ≤ 1).
/// - Well-formed parent (1 populated, N-1 missing): `true` (1 ≤ 1)
/// — the SOLE `Ok` arm of [`Self::variant`] lies inside the
/// at-most-one region.
/// - K-populated parent for `K ≥ 2`: `false` (K > 1).
/// - Saturated parent (N populated, 0 missing on any `N ≥ 2`):
/// `false` (N ≥ 2 > 1).
///
/// # Compounding future consumers
///
/// - A fast-path branch on the resolver-clean arm that
/// discriminates "not ambiguous" (0 or 1 populated) from
/// "ambiguous" (≥ 2 populated) reads
/// `parent.has_at_most_one_populated_kind()` at ONE substrate
/// site — one two-step short-circuit walk with a bit-flip,
/// strictly cheaper than the widened union of the zero-arm and
/// one-arm.
/// - An operator-facing "at most one populated variant" diagnostic
/// (the guard for downstream code that assumes non-ambiguous
/// dispatch) reads this primitive at ONE substrate site.
/// - A `has-at-most-one-populated-kind` require-tag classifier arm
/// reaches this primitive at ONE call site, closing the
/// {0, 1, ≥ 2, ≤ 1} cardinality-Boolean grid alongside its
/// sibling `has-multiple-populated-kinds` under the Boolean
/// negation axis.
///
/// A new [`Self::Kind`] variant added to
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
/// this primitive mechanically through the delegated
/// [`Self::has_multiple_populated_kinds`] — the fused walk picks
/// up the new slot as an additional short-circuit candidate at
/// every downstream callsite without further per-caller edit.
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
/// The "≤ 1" Boolean projection lives at ONE substrate site as
/// a definitional negation of the "≥ 2" projection; the two
/// forms `!has_multiple_populated_kinds()`,
/// `populated_kind_count() <= 1`, and
/// `is_empty() || has_unique_populated_kind()` compose through
/// the SAME two-step-short-circuit walk shape, byte-for-byte
/// identical on every arm.
/// - THEORY.md §VI.1 — generation over composition. A new
/// [`Self::Kind`] variant added to `ALL` reaches this primitive
/// mechanically through the delegated
/// [`Self::has_multiple_populated_kinds`].
fn has_at_most_one_populated_kind(&self) -> bool {
!self.has_multiple_populated_kinds()
}
/// Boolean cardinality "≤ 1" peer of
/// [`Self::has_multiple_missing_kinds`] — `true` iff AT MOST ONE
/// slot on this tagged union is missing (i.e. zero or one missing
/// slot).
///
/// Default body: the definitional Boolean negation
/// `!self.has_multiple_missing_kinds()` — one bit-flip over the
/// SAME two-step-short-circuit closed-set walk under a NEGATED
/// [`Self::has`] predicate that [`Self::has_multiple_missing_kinds`]
/// already runs, without re-authoring the fused loop and WITHOUT a
/// second walk over the closed set. Strictly cheaper than either
/// widened composition
/// `self.is_saturated() || self.has_unique_missing_kind()` (which
/// walks the closed set TWICE — once under `all-populated`, once
/// under `exactly-one-missing`) or `self.missing_kind_count() <= 1`
/// (which walks the closed set fully counting missing hits) on
/// every arm.
///
/// # Sibling to the Boolean cardinality "≥ 2" primitive
///
/// Boolean-negation peer under `!(≥ 2) == (≤ 1)` — byte-for-byte
/// symmetrical with [`Self::has_at_most_one_populated_kind`]
/// under the (populated, missing) complement axis. Names the arm
/// where the parent is SATURATED-OR-NEAR-SATURATED (zero or
/// exactly one missing slot).
///
/// # Composition laws
///
/// - `has_at_most_one_missing_kind() == !has_multiple_missing_kinds()`
/// — the definitional Boolean negation.
/// - `has_at_most_one_missing_kind() == (missing_kind_count() <= 1)`
/// — the scalar complement-cardinality composition.
/// - `has_at_most_one_missing_kind() == is_saturated() || has_unique_missing_kind()`
/// — the union of the zero-missing-arm and the one-missing-arm
/// of the {0, 1, ≥ 2} cardinality trichotomy on the missing
/// axis.
///
/// All three laws hold on every arm and every closed-set kind —
/// pinned as first-class typed invariants by the trait's own
/// default body and swept substrate-wide by
/// [`assert_has_at_most_one_missing_kind_matches_missing_kind_count`].
///
/// # Truth table on the exactly-one-slot tagged-union contract
///
/// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
/// cardinality `N`:
///
/// - Empty parent (0 populated, N missing): `true` iff `N ≤ 1`
/// (every production union in the workspace has `N ≥ 2`, so on
/// every production union the empty arm returns `false`).
/// - Well-formed parent (1 populated, N-1 missing): `true` iff
/// `N - 1 ≤ 1`, i.e. `N ≤ 2` (on `N == 2` the well-formed arm
/// has exactly one missing slot; on `N ≥ 3` it has ≥ 2).
/// - Near-saturated parent (N-1 populated, 1 missing): `true` (1 ≤ 1).
/// - K-missing parent for `K ≥ 2`: `false`.
/// - Saturated parent (N populated, 0 missing): `true` (0 ≤ 1).
///
/// # Compounding future consumers
///
/// - A fast-path branch on the near-saturated / saturated arms
/// that discriminates "at most one dependency still open" from
/// "≥ 2 dependencies still open" reads
/// `parent.has_at_most_one_missing_kind()` at ONE substrate
/// site — one two-step short-circuit walk with a bit-flip,
/// strictly cheaper than the widened union of the zero-arm and
/// one-arm.
/// - An operator-facing "at most one dependency still unfulfilled"
/// diagnostic on an aggregate boundary progress-guard reads
/// this primitive at ONE substrate site.
/// - A `has-at-most-one-missing-kind` require-tag classifier arm
/// reaches this primitive at ONE call site, closing the
/// {0, 1, ≥ 2, ≤ 1} cardinality-Boolean grid on the missing
/// axis alongside its sibling `has-multiple-missing-kinds`
/// under the Boolean negation axis.
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
/// The "≤ 1" Boolean projection on the missing axis lives at
/// ONE substrate site as a definitional negation of the "≥ 2"
/// projection; the three composition forms
/// (`!has_multiple_missing_kinds()`,
/// `missing_kind_count() <= 1`, and
/// `is_saturated() || has_unique_missing_kind()`) compose
/// through the SAME two-step-short-circuit walk shape,
/// byte-for-byte identical on every arm.
/// - THEORY.md §VI.1 — generation over composition. A new
/// [`Self::Kind`] variant added to `ALL` reaches this primitive
/// mechanically through the delegated
/// [`Self::has_multiple_missing_kinds`].
fn has_at_most_one_missing_kind(&self) -> bool {
!self.has_multiple_missing_kinds()
}
/// Boolean parent-state middle-arm projection — `true` iff this
/// tagged union has AT LEAST ONE populated slot AND AT LEAST ONE
/// missing slot, i.e. it is neither [`Self::is_empty`] nor
/// [`Self::is_saturated`].
///
/// Default body: a FUSED short-circuit closed-set walk that tracks
/// two Boolean flags (`has_populated`, `has_missing`) across
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) under
/// [`Self::has`] and returns `true` at the EARLIEST slot where
/// both flags have flipped. Best-case O(2) walk (index 0 populated
/// combined with index 1 missing, or vice versa); worst case walks
/// the full closed set only when EVERY slot is populated or EVERY
/// slot is missing (the two arms where the return value is `false`).
/// Byte-for-byte cheaper than the widened composition
/// `!self.is_empty() && !self.is_saturated()` (which walks the
/// closed set TWICE — once under `any`, once under `all`) on every
/// partially-populated arm.
///
/// # Sibling to the parent-state trichotomy
///
/// Middle arm of the natural `{Empty | Partial | Saturated}`
/// parent-state trichotomy — orthogonal to the {0, 1, ≥2}
/// cardinality trichotomies already closed on the populated /
/// missing axes. Together with [`Self::is_empty`] (all-missing
/// arm) and [`Self::is_saturated`] (all-populated arm), these three
/// Boolean primitives partition every tagged-union state on the
/// parent-state axis — EXACTLY ONE of the three returns `true` on
/// any given parent whose `<Self::Kind as ClosedSet>::ALL.len() ≥
/// 1`:
///
/// | parent state | primitive | populated cardinality |
/// |--------------|------------------------------------|-----------------------------|
/// | Empty | [`Self::is_empty`] | `0` |
/// | Partial | `is_partially_populated` (this) | `0 < populated < ALL.len()` |
/// | Saturated | [`Self::is_saturated`] | `ALL.len()` |
///
/// The trichotomy partition law
/// `usize::from(is_empty()) + usize::from(is_partially_populated())
/// + usize::from(is_saturated()) == 1` on every arm is a genuinely
/// new proof binding the three parent-state endpoints together as
/// a typed algebraic invariant — swept substrate-wide by
/// [`assert_is_partially_populated_matches_cardinality`].
///
/// # Composition laws
///
/// - `is_partially_populated() == !is_empty() && !is_saturated()`
/// — the negation-of-both-endpoints composition, at the trait
/// default body's SAME fused short-circuit walk.
/// - `is_partially_populated() == (populated_kind_count() > 0
/// && missing_kind_count() > 0)` — the paired scalar-projection
/// composition.
/// - `is_partially_populated() == (0 < populated_kind_count()
/// && populated_kind_count() < ALL.len())` — the single-axis
/// strict-inequality composition (populated cardinality lies in
/// the open interval `(0, ALL.len())`).
///
/// # Truth table on the exactly-one-slot tagged-union contract
///
/// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
/// cardinality `N ≥ 2`:
///
/// - Empty parent (0 populated, N missing): `false` (empty arm).
/// - Well-formed parent (1 populated, N-1 missing on any `N ≥ 2`):
/// `true` — the SOLE `Ok` arm of [`Self::variant`] lies inside
/// the partial region.
/// - K-populated parent for `0 < K < N`: `true`.
/// - Saturated parent (N populated, 0 missing on any `N ≥ 2`):
/// `false` (saturated arm).
///
/// # Compounding future consumers
///
/// - A boundary-progress "some done, some pending" diagnostic on
/// an aggregate condition-carrier reads
/// `parent.is_partially_populated()` at ONE substrate site —
/// the exact "in flight" arm — rather than composing
/// `!parent.is_empty() && !parent.is_saturated()` (two closed-
/// set walks) or `parent.populated_kind_count() > 0 &&
/// parent.missing_kind_count() > 0` (two counter walks).
/// - A fast-path branch that discriminates "mixed" from "empty or
/// saturated" reads this primitive with ONE fused short-circuit
/// walk, strictly cheaper than either widened composition.
/// - An `is-partially-populated` require-tag classifier arm
/// reaches this primitive at ONE call site, byte-for-byte
/// symmetrical with the sibling `is-empty` / `is-saturated`
/// arms on the closed parent-state trichotomy.
/// - An operator-facing "in-flight ambiguous carrier" diagnostic
/// (the resolver's `Err(Ambiguous)` arm's non-saturated sub-arm)
/// reads `parent.is_partially_populated() && parent.has_multiple_populated_kinds()`
/// composing two short-circuit walks — strictly cheaper than
/// materializing the `variant()` error carrier.
///
/// A new [`Self::Kind`] variant added to
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
/// this primitive mechanically — the fused walk picks up the new
/// slot as an additional short-circuit candidate (a parent that
/// previously satisfied `is_partially_populated` because it had
/// both populated and missing slots continues to satisfy it; a
/// previously-saturated parent that leaves the new slot missing
/// becomes partially populated at every downstream callsite
/// without further per-caller edit).
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
/// The parent-state middle-arm projection lives at ONE
/// substrate site as a fused short-circuit walk over
/// `<Self::Kind as ClosedSet>::ALL` under [`Self::has`] with
/// early exit on the first observed populated/missing pair —
/// byte-for-byte cheaper than the widened negation-of-both-
/// endpoints composition, and semantically identical on every
/// arm. The trichotomy partition law
/// `is_empty + is_partially_populated + is_saturated == 1`
/// lives at ONE substrate site inside the testkit's per-arm
/// sweep — pinned across every production tagged union at
/// compile time via the trait's default body composition, not
/// per-parent.
/// - THEORY.md §VI.1 — generation over composition. A new
/// [`Self::Kind`] variant added to `ALL` reaches this primitive
/// mechanically through the fused walk — the trichotomy holds
/// on the widened kind set without further per-caller edit.
fn is_partially_populated(&self) -> bool {
let mut has_populated = false;
let mut has_missing = false;
for k in <Self::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
if self.has(k) {
has_populated = true;
} else {
has_missing = true;
}
if has_populated && has_missing {
return true;
}
}
false
}
/// Kind-scoped strict refinement of [`Self::has`] — `true` iff the
/// given `kind` is populated AND no OTHER slot on this tagged union
/// is populated. The "exactly this one variant" predicate.
///
/// Default body: a FUSED short-circuit closed-set walk under
/// [`Self::has`] that returns `false` at the EARLIEST populated
/// slot whose kind is NOT `kind`, and returns `true` iff the sweep
/// completes with `kind` seen as the sole populated slot. Byte-for-
/// byte cheaper than either widened composition
/// `self.unique_populated_kind() == Some(kind)` (which walks until
/// the SECOND populated slot before comparing) or
/// `self.has(kind) && self.has_unique_populated_kind()` (two
/// closed-set walks) on every arm where the parent carries a
/// populated slot that isn't `kind`.
///
/// # Sibling to [`Self::has`]
///
/// Kind-scoped strict-refinement peer: `has(kind)` is the SUBSET
/// predicate (`kind` populated, maybe others too); `has_only(kind)`
/// is the EQUAL predicate (`kind` populated AND ONLY `kind`). The
/// implication `has_only(kind) → has(kind)` binds the pair on the
/// strict-refinement axis; the reverse implication holds only on
/// well-formed parents (`has_unique_populated_kind() == true`).
///
/// # Peer to [`Self::unique_populated_kind`]
///
/// Same axis, argument-scoped projection: where
/// `unique_populated_kind()` returns `Some(k)` iff exactly one slot
/// is populated AND names which one, `has_only(kind)` returns
/// `true` iff exactly one slot is populated AND that slot is the
/// passed `kind`. The composition law
/// `has_only(kind) == (unique_populated_kind() == Some(kind))`
/// binds the two primitives at the trait's default body — swept
/// substrate-wide by
/// [`assert_has_only_matches_unique_populated_kind`].
///
/// # Truth table on the exactly-one-slot tagged-union contract
///
/// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
/// cardinality `N ≥ 2` and a fixed argument `kind`:
///
/// - Empty parent (0 populated, N missing): `false` — no populated
/// slot, so `kind` isn't the sole populated kind.
/// - Well-formed parent with `kind` populated (1 populated ==
/// kind): `true` — the SOLE arm where `has_only(kind)` returns
/// `true`. Aligns with [`Self::variant`]'s `Ok(Variant)` arm
/// where the resolver names the same kind.
/// - Well-formed parent with other kind populated (1 populated !=
/// kind): `false` — the populated slot addresses a different
/// kind.
/// - K-populated parent for `K ≥ 2`: `false` — multiple populated
/// slots, so no single kind is the "only" one.
/// - Saturated parent (N populated, 0 missing on any `N ≥ 2`):
/// `false`.
///
/// # Kind-domain exhaustivity
///
/// A parent satisfies `has_only(k)` for AT MOST one `k`, since two
/// distinct kinds cannot both be the sole populated slot. On the
/// well-formed arm the count is exactly 1 (the addressed kind); on
/// every non-well-formed arm the count is 0. This kind-domain
/// exhaustivity law binds the argument-scoped projection to the
/// arg-less uniqueness predicate at ONE substrate site.
///
/// # Compounding future consumers
///
/// - A dispatch table that runs a per-kind branch only when the
/// parent is unambiguously that kind reads `parent.has_only(k)`
/// at ONE substrate site with ONE fused short-circuit walk —
/// strictly cheaper than either widened composition.
/// - An `is-only-<kind>` require-tag classifier arm reaches this
/// primitive at ONE call site — the kind-scoped peer of the
/// arg-less `has_unique_populated_kind` classifier.
/// - A coherence check verifying "every parent from a
/// `single_slot_X(k)` factory is unambiguously kind `k`" reads
/// `parent.has_only(k)` at ONE site — the strongest structural
/// pin on the well-formed diagonal.
/// - An operator-facing "unambiguously kind=<k>" diagnostic on the
/// resolver's Ok arm reads `parent.has_only(k)` after
/// `first_populated_kind` names the resolved kind — one walk, no
/// allocation, no `Option<Kind>` construction.
///
/// A new [`Self::Kind`] variant added to
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
/// this primitive mechanically — the fused walk picks up the new
/// slot as an additional short-circuit candidate at every
/// downstream callsite without further per-caller edit.
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
/// The kind-scoped strict-refinement projection lives at ONE
/// substrate site as a fused short-circuit walk over
/// `<Self::Kind as ClosedSet>::ALL` under [`Self::has`] with
/// early exit on the first populated slot whose kind is not
/// `kind` — byte-for-byte cheaper than the widened composition
/// `unique_populated_kind() == Some(kind)`, semantically
/// identical on every arm.
/// - THEORY.md §VI.1 — generation over composition. A new
/// [`Self::Kind`] variant added to `ALL` reaches this primitive
/// mechanically through the fused walk.
fn has_only(&self, kind: Self::Kind) -> bool
where
Self::Kind: PartialEq,
{
let mut saw_kind = false;
for k in <Self::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
if !self.has(k) {
continue;
}
if k == kind {
saw_kind = true;
} else {
return false;
}
}
saw_kind
}
/// Kind-scoped strict refinement of `!Self::has(kind)` — `true` iff
/// the given `kind` is MISSING AND no OTHER slot on this tagged
/// union is missing. The "exactly this one variant is absent"
/// predicate — closed-set-complement mirror of [`Self::has_only`].
///
/// Default body: a FUSED short-circuit closed-set walk under a
/// negated [`Self::has`] that returns `false` at the EARLIEST
/// missing slot whose kind is NOT `kind`, and returns `true` iff
/// the sweep completes with `kind` seen as the sole missing slot.
/// Byte-for-byte cheaper than either widened composition
/// `self.unique_missing_kind() == Some(kind)` (which walks until
/// the SECOND missing slot before comparing) or
/// `!self.has(kind) && self.has_unique_missing_kind()` (two
/// closed-set walks) on every arm where the parent carries a
/// missing slot that isn't `kind`.
///
/// # Sibling to [`Self::has_only`]
///
/// Closed-set-complement peer of [`Self::has_only`] under a negated
/// [`Self::has`] predicate — where `has_only(kind)` names parents
/// whose SOLE populated slot is `kind`, `lacks_only(kind)` names
/// parents whose SOLE missing slot is `kind`. Byte-for-byte
/// symmetrical fused-walk shape; the two primitives are useful in
/// DIFFERENT structural regimes: `has_only` names well-formed
/// parents (1 of N populated); `lacks_only` names the missing-side
/// complement (N-1 of N populated — the near-saturation arm). On
/// tagged unions with `N == 2` the two coincide (a well-formed
/// 1-of-2 parent has 1 missing too, so `has_only(a)` and
/// `lacks_only(b)` name the same arm iff `a != b`).
///
/// # Peer to [`Self::unique_missing_kind`]
///
/// Same axis, argument-scoped projection: where
/// `unique_missing_kind()` returns `Some(k)` iff exactly one slot
/// is missing AND names which one, `lacks_only(kind)` returns
/// `true` iff exactly one slot is missing AND that slot is the
/// passed `kind`. The composition law
/// `lacks_only(kind) == (unique_missing_kind() == Some(kind))`
/// binds the two primitives at the trait's default body — swept
/// substrate-wide by
/// [`assert_lacks_only_matches_unique_missing_kind`].
///
/// # Truth table on the exactly-one-slot tagged-union contract
///
/// For a tagged union with `<Self::Kind as ClosedSet>::ALL` of
/// cardinality `N ≥ 2` and a fixed argument `kind`:
///
/// - Empty parent (0 populated, N missing): `false` on any `N ≥ 2`
/// — N missing slots, so `kind` isn't the sole missing kind.
/// - Well-formed parent (1 populated, N-1 missing): `false` when
/// `N > 2` (N-1 ≥ 2 missing, no unique missing); on `N == 2`
/// with populated `p`, `lacks_only(kind) == (kind != p)` (the
/// one missing slot is the non-populated one).
/// - N-1-populated parent (missing-side peer of the well-formed
/// arm, 1 missing): `true` iff `kind` names the sole missing
/// slot — the SOLE arm where `lacks_only(kind)` returns `true`
/// on any `N > 2` closed set.
/// - Saturated parent (N populated, 0 missing): `false`.
///
/// # Kind-domain exhaustivity
///
/// A parent satisfies `lacks_only(k)` for AT MOST one `k`, since
/// two distinct kinds cannot both be the sole missing slot. On
/// the near-saturation arm the count is exactly 1 (the addressed
/// missing kind); on every other arm the count is 0. This kind-
/// domain exhaustivity law binds the argument-scoped projection
/// to the arg-less uniqueness predicate at ONE substrate site,
/// byte-for-byte peer of the `has_only` exhaustivity law under
/// complement.
///
/// # Kind-scoped implication
///
/// `lacks_only(kind) → !has(kind)` — if `kind` is the sole missing
/// slot then `kind` cannot be populated. Complement mirror of the
/// `has_only(kind) → has(kind)` implication that binds
/// [`Self::has_only`] to [`Self::has`] on the strict-refinement
/// axis; here the implication binds `lacks_only` to `!has` on the
/// closed-set-complement axis.
///
/// # Compounding future consumers
///
/// - An operator-facing "exactly one dependency still unfulfilled:
/// X" diagnostic on an aggregate boundary check whose `X` is
/// known statically reads `parent.lacks_only(X)` at ONE
/// substrate site — one fused short-circuit walk, no allocation,
/// strictly cheaper than the widened composition.
/// - A `lacks-only-<kind>` require-tag classifier arm reaches this
/// primitive at ONE call site — the argument-scoped peer of the
/// arg-less `has_unique_missing_kind` classifier, closed-set-
/// complement mirror of the `is-only-<kind>` classifier arm on
/// the populated axis.
/// - A coherence check verifying "the near-saturation parent from
/// an `all_but_one_slot_X(k)` factory is unambiguously missing
/// kind `k`" reads `parent.lacks_only(k)` at ONE site — the
/// strongest structural pin on the missing-side well-formed
/// diagonal.
/// - A fast-path branch on the near-saturation arm that
/// discriminates "exactly one specific slot still empty" from
/// "0 or ≥ 2 still empty or some OTHER slot empty" reads
/// `parent.lacks_only(kind)` at ONE call site — the fused-walk
/// short-circuit is strictly cheaper than
/// `parent.unique_missing_kind() == Some(kind)` on every arm
/// where a first-missing-slot mismatch would prune the walk
/// before the second missing slot.
///
/// A new [`Self::Kind`] variant added to
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) reaches
/// this primitive mechanically — the fused walk picks up the new
/// slot as an additional short-circuit candidate at every
/// downstream callsite without further per-caller edit.
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
/// The kind-scoped strict-refinement projection on the missing
/// axis lives at ONE substrate site as a fused short-circuit
/// walk over `<Self::Kind as ClosedSet>::ALL` under a negated
/// [`Self::has`] with early exit on the first missing slot
/// whose kind is not `kind` — byte-for-byte peer of
/// [`Self::has_only`]'s fused walk under complement,
/// semantically identical to
/// `unique_missing_kind() == Some(kind)` on every arm.
/// - THEORY.md §VI.1 — generation over composition. A new
/// [`Self::Kind`] variant added to `ALL` reaches this primitive
/// mechanically through the fused walk.
fn lacks_only(&self, kind: Self::Kind) -> bool
where
Self::Kind: PartialEq,
{
let mut saw_kind = false;
for k in <Self::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
if self.has(k) {
continue;
}
if k == kind {
saw_kind = true;
} else {
return false;
}
}
saw_kind
}
}
/// Generic diagnostic-stability testkit — pins that [`TaggedUnion::KIND_LIST`]
/// matches `<T::Kind as tatara_closed_set::ClosedSet>::labels_joined("/")`
/// byte-identically for every implementor.
///
/// Substrate primitive for the four sibling
/// `_error_empty_lists_every_kind_in_canonical_order` tests on
/// `ProcessSpec` ([`crate::intent::Intent`],
/// [`crate::encapsulates::EncapsulationKind`],
/// [`crate::export::ArtifactSource`], [`crate::export::VectorChannel`])
/// that pre-lift each restated the same
/// `assert_eq!(<XxxKind as ClosedSet>::labels_joined("/"),
/// XXX_KIND_LIST)` two-argument comparison at their own test bodies —
/// byte-identical projections whose only per-carrier knobs (the Kind
/// type + the KIND_LIST constant) are the two associated items the
/// [`TaggedUnion`] trait names. Post-lift each site collapses to ONE
/// `assert_kind_list_matches_closed_set::<Xxx>()` invocation whose
/// body is the substrate primitive's own dispatch.
///
/// A fifth sibling tagged-union parent picks up the diagnostic-
/// stability check through ONE `impl TaggedUnion for X` block + ONE
/// `assert_kind_list_matches_closed_set::<X>()` call site — no
/// re-authored `<XKind as ClosedSet>::labels_joined("/")` composition
/// at the test site, no re-authored per-site `assert_eq!` pair.
#[track_caller]
pub fn assert_kind_list_matches_closed_set<T: TaggedUnion>() {
let derived = <T::Kind as tatara_closed_set::ClosedSet>::labels_joined("/");
assert_eq!(
derived,
T::KIND_LIST,
"TaggedUnion KIND_LIST drift — must equal <T::Kind as ClosedSet>::labels_joined(\"/\")",
);
}
/// Generic presence-probe testkit — pins that [`TaggedUnion::has`]
/// agrees with [`VariantSelector::select`]`.is_some()` across every
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) entry, both
/// on the diagonal (populated slot AND matching kind → `true`) and
/// off the diagonal (populated slot BUT other kind → `false`).
///
/// Substrate primitive for the presence-probe half of the tagged-
/// union contract — dispatch tables that key off `intent-<kind>` /
/// `channel-<kind>` / `source-<kind>` require-tags gain a `.has(k)`
/// call that structurally CANNOT drift from the closed-set sweep,
/// but the pin here surfaces a `has` override that would break the
/// contract (e.g. a future specialization that always returned
/// `false`) at ONE call site rather than at every downstream
/// dispatcher.
///
/// A fifth sibling tagged-union parent picks up the presence-probe
/// check through ONE `assert_has_matches_select::<X, _>(single_slot)`
/// invocation — no re-authored `for k in K::ALL { … }` sweep at the
/// test site.
#[track_caller]
pub fn assert_has_matches_select<T, F>(single_slot: F)
where
T: TaggedUnion,
T::Kind: PartialEq + std::fmt::Debug,
F: Fn(T::Kind) -> T,
{
for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let parent = single_slot(populated);
for probed in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let expected = probed == populated;
assert_eq!(
parent.has(probed),
expected,
"TaggedUnion::has drift — populated={populated:?} probed={probed:?} expected={expected}",
);
assert_eq!(
probed.select(&parent).is_some(),
expected,
"VariantSelector::select drift — populated={populated:?} probed={probed:?} expected={expected}",
);
}
}
}
/// Generic widened-probe testkit — pins that [`TaggedUnion::find`]
/// agrees with [`TaggedUnion::has`] AND with
/// [`VariantSelector::select`] across every
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) entry, and
/// that the returned borrowed view round-trips through
/// [`VariantKind::variant_kind`] back to the addressing Kind on the
/// populated diagonal.
///
/// Substrate primitive for the widened half of the presence-probe
/// contract — dispatch tables that key off `intent-<kind>` /
/// `channel-<kind>` / `source-<kind>` require-tags gain a `.find(k)`
/// call whose return type carries the borrowed variant payload for
/// diagnostic composition (an operator-facing "channel-<kind>
/// matched with e.channel.<field>.<key>=<value>" message, a
/// coherence check that projects the borrowed variant into its
/// Kind for round-trip validation), and the pin here surfaces a
/// `find` override that would drift from the composition law
/// `has(k) == find(k).is_some()` at ONE call site rather than at
/// every downstream dispatcher.
///
/// The three sub-assertions swept per (populated, probed) pair:
///
/// 1. `parent.find(probed).is_some() == parent.has(probed)` — the
/// composition law binding [`TaggedUnion::has`] to
/// [`TaggedUnion::find`] via `find(k).is_some()`.
/// 2. `parent.find(probed).is_some() == probed.select(&parent).is_some()`
/// — the widened primitive delegates to
/// [`VariantSelector::select`] on the Kind, so a regression that
/// inlined a divergent walk body at the trait's `find` default
/// fails here rather than as silent drift at every downstream
/// diagnostic consumer.
/// 3. On the populated diagonal (`probed == populated`), the
/// returned borrowed view satisfies
/// `find(k).unwrap().variant_kind() == k` — the round-trip
/// contract that closes `find` (forward-widened) against
/// [`VariantKind::variant_kind`] (reverse projection).
///
/// A fifth sibling tagged-union parent picks up the widened-probe
/// check through ONE `assert_find_agrees_with_has::<X, _>(single_slot)`
/// invocation — no re-authored `for k in K::ALL { … }` sweep at the
/// test site.
#[track_caller]
pub fn assert_find_agrees_with_has<T, F>(single_slot: F)
where
T: TaggedUnion,
T::Kind: PartialEq + std::fmt::Debug,
F: Fn(T::Kind) -> T,
{
for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let parent = single_slot(populated);
for probed in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let expected = probed == populated;
let via_has = parent.has(probed);
let via_find = parent.find(probed).is_some();
let via_select = probed.select(&parent).is_some();
assert_eq!(
via_find, via_has,
"TaggedUnion::find drifted from has — populated={populated:?} probed={probed:?}",
);
assert_eq!(
via_find, via_select,
"TaggedUnion::find drifted from VariantSelector::select — populated={populated:?} probed={probed:?}",
);
assert_eq!(
via_find, expected,
"TaggedUnion::find truth-table drift — populated={populated:?} probed={probed:?} expected={expected}",
);
if expected {
let variant = parent.find(probed).unwrap_or_else(|| {
panic!("TaggedUnion::find must return Some for populated slot {probed:?}",)
});
assert_eq!(
<<T::Kind as VariantSelector<T>>::Variant<'_> as VariantKind<T::Kind>>::variant_kind(
&variant,
),
probed,
"find→variant_kind round-trip failed for {probed:?}",
);
}
}
}
}
/// Generic closed-set-inversion testkit — pins that
/// [`TaggedUnion::populated_kinds`] composes over
/// [`TaggedUnion::has`] across every
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) entry on
/// the single-slot side, that the returned `Vec` is the canonical
/// [`ClosedSet::ALL`]-ordered filter of `has(k)`, and that on the
/// populated diagonal `single_slot(k).populated_kinds()` equals
/// `vec![k]` exactly (length 1, canonical ordered, no drift).
///
/// Parent-axis substrate primitive for the tagged-union closed-set-
/// inversion refinement — the peer of
/// [`crate::boundary::assert_slice_refinement_composition_laws`]'s
/// `distinct_kinds` sub-arm on the slice-level presence-probe axis,
/// lifted here to the tagged-union parent-level presence-probe axis
/// (same shape, same composition operator, second instance in the
/// workspace-wide closed-set-inversion refinement algebra).
///
/// The three sub-assertions swept per (populated, probed) pair:
///
/// 1. Per-kind membership: `parent.populated_kinds().contains(&k) ==
/// parent.has(k)` for every `k ∈ ClosedSet::ALL` — a regression
/// that overrode `populated_kinds` to skip a kind, drift the walk
/// order from canonical `ALL` to slot-encounter order, or return
/// a superset containing absent kinds surfaces at the specific
/// kind's per-pair assertion.
/// 2. Canonical `ALL`-filter equality:
/// `parent.populated_kinds() == ALL.iter().copied().filter(|k|
/// parent.has(*k)).collect()` — a regression that returned
/// duplicates (a naive override that skipped dedup by
/// construction) or drifted the walk order surfaces at the
/// post-loop equality assert.
/// 3. Single-slot diagonal: `single_slot(k).populated_kinds() ==
/// vec![k]` exactly — pins the single-populated arm's cardinality
/// (length 1) and ordering (the addressed kind's own position in
/// `ALL`) together at ONE assert.
///
/// Substrate primitive for future per-parent
/// `X_populated_kinds_matches_has` tests that would otherwise each
/// restate the same nested-`for populated in K::ALL { for probed in
/// K::ALL { … } }` sweep + canonical-order equality + single-slot
/// diagonal pin — every one of the four production `.variant()`
/// parents on `ProcessSpec` binds through this ONE primitive with a
/// per-site `single_slot` factory. A fifth sibling picks up the
/// closed-set-inversion check through ONE call site — no re-authored
/// `for k in K::ALL { … }` sweep at the test surface, no re-authored
/// `assert_eq!` triad.
///
/// The `single_slot` closure stays per-site — reused verbatim from
/// the sibling primitives ([`assert_variant_round_trip`],
/// [`assert_find_agrees_with_has`],
/// [`assert_single_slot_key_matches_label`]) — the closure IS the
/// "populate slot k" ground truth for the parent's field structure.
///
/// The [`crate::lifetime::Lifetime`] site is DELIBERATELY excluded
/// through the `T: TaggedUnion` bound — `Lifetime`'s `variant()`
/// returns `Ok(Permanent)` on empty rather than an `Empty` typed
/// error, so its projection shape diverges from the four
/// Empty-projecting parents. Same reasoning as
/// [`assert_variant_round_trip`]'s /
/// [`assert_find_agrees_with_has`]'s exclusions.
#[track_caller]
pub fn assert_populated_kinds_matches_has<T, F>(single_slot: F)
where
T: TaggedUnion,
T::Kind: PartialEq + std::fmt::Debug,
F: Fn(T::Kind) -> T,
{
for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let parent = single_slot(populated);
let kinds = parent.populated_kinds();
// Per-kind membership composition law.
for probed in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
assert_eq!(
kinds.contains(&probed),
parent.has(probed),
"TaggedUnion::populated_kinds().contains({probed:?}) drifted from has({probed:?}) — populated={populated:?}",
);
}
// Canonical ALL-filter equality — pins dedup, walk order, and
// membership consistency at ONE assert.
let canonical: Vec<T::Kind> = <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
.filter(|k| parent.has(*k))
.collect();
assert_eq!(
kinds, canonical,
"TaggedUnion::populated_kinds() must yield ClosedSet::ALL-ordered subsequence where has is true (no duplicates, canonical order) — populated={populated:?}",
);
// Single-slot diagonal — the addressed slot IS the ONLY
// populated slot on the parent single_slot produces, so the
// canonical filter yields exactly [populated].
assert_eq!(
kinds,
vec![populated],
"TaggedUnion::populated_kinds() on single_slot({populated:?}) must return vec![{populated:?}] exactly",
);
}
}
/// Generic two-slot closed-set-inversion testkit — peer of
/// [`assert_populated_kinds_matches_has`] on the ambiguous-parent
/// side. Pins that a `two_slot(a, b)` parent's `populated_kinds()`
/// yields the canonical `ClosedSet::ALL`-ordered pair
/// `[min_all(a,b), max_all(a,b)]` (length exactly 2, dedup + walk
/// order enforced), and that per-kind membership composes
/// byte-identically against `has(k)` on the malformed-parent arm.
///
/// The two-slot fixture is the SAME factory production sites already
/// hand [`assert_two_slots_ambiguous`] — every one of the four
/// production `.variant()` parents on `ProcessSpec` composes
/// `two_slot(a, b)` through per-field `Option::or` on
/// `single_slot(a)` and `single_slot(b)`, so BOTH slots on the
/// resulting parent are populated. The primitive's off-diagonal
/// sweep (`a != b`) pins that `populated_kinds()` NAMES both
/// populated slots on the malformed arm — the diagnostic-surface
/// promise the payload-free
/// [`TaggedUnionError::ambiguous`] carrier stops short of.
///
/// The three sub-assertions swept per `(a, b)` off-diagonal pair:
///
/// 1. Cardinality: `populated_kinds().len() == 2` — a regression
/// that returned a length-1 vec (silently short-circuiting on
/// the first populated slot; drifting the walk from `ALL` to
/// single-match `find`) fails HERE at the length assert.
/// 2. Per-kind membership: `populated_kinds().contains(&k) ==
/// has(k)` for every `k ∈ ClosedSet::ALL` — the composition law
/// of the closed-set-inversion refinement, pinned on the
/// multi-populated arm.
/// 3. Canonical `ALL`-filter equality:
/// `populated_kinds() == ALL.iter().copied().filter(|k|
/// parent.has(*k)).collect()` — pins the walk order (a
/// regression that yielded `[b, a]` because it walked the two
/// populated slots in construction order instead of
/// `ClosedSet::ALL` order fails at the equality assert).
///
/// A fifth sibling tagged-union parent picks up the two-slot
/// closed-set-inversion check through ONE call site — no
/// re-authored nested-for sweep at the test surface, no re-authored
/// `assert_eq!` triad.
///
/// Same `Lifetime` exclusion as [`assert_populated_kinds_matches_has`]:
/// the `T: TaggedUnion` bound doesn't reach it.
#[track_caller]
pub fn assert_populated_kinds_across_pairs<T, F>(two_slot: F)
where
T: TaggedUnion,
T::Kind: PartialEq + std::fmt::Debug,
F: Fn(T::Kind, T::Kind) -> T,
{
for a in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
for b in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
if a == b {
continue;
}
let parent = two_slot(a, b);
let kinds = parent.populated_kinds();
assert_eq!(
kinds.len(),
2,
"TaggedUnion::populated_kinds() on two_slot({a:?}, {b:?}) must return exactly two populated kinds, got {kinds:?}",
);
for probed in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
assert_eq!(
kinds.contains(&probed),
parent.has(probed),
"TaggedUnion::populated_kinds().contains({probed:?}) drifted from has({probed:?}) — (a, b)=({a:?}, {b:?})",
);
}
let canonical: Vec<T::Kind> = <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
.filter(|k| parent.has(*k))
.collect();
assert_eq!(
kinds, canonical,
"TaggedUnion::populated_kinds() must yield ClosedSet::ALL-ordered pair on two_slot({a:?}, {b:?}) — got {kinds:?}, expected {canonical:?}",
);
}
}
}
/// Generic scalar-cardinality testkit — pins that
/// [`TaggedUnion::populated_kind_count`] agrees with
/// [`TaggedUnion::populated_kinds`]`.len()` across every
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
/// arrangement AND that on the populated diagonal
/// `single_slot(k).populated_kind_count()` equals `1` exactly (aligned
/// with the single-slot arm's `populated_kinds()` returning
/// `vec![k]`).
///
/// Parent-axis substrate primitive for the scalar-cardinality
/// refinement of the tagged-union closed-set-inversion axis — the
/// scalar projection of [`assert_populated_kinds_matches_has`]'s
/// widened primitive. Together they close the two-refinement
/// composition contract that binds
/// [`TaggedUnion::populated_kind_count`] against
/// [`TaggedUnion::populated_kinds`]:
///
/// 1. **`count ↔ kinds.len()`**: `populated_kind_count() ==
/// populated_kinds().len()` — a regression that overrode
/// `populated_kind_count` to skip a kind (returning `0` on a
/// populated parent), double-count a slot (returning `2` on a
/// single-slot parent), or drift the walk from `ClosedSet::ALL`
/// surfaces at the substrate boundary here.
/// 2. **Single-slot diagonal**: `single_slot(k).populated_kind_count()
/// == 1` — pins the well-formed arm's expected cardinality
/// against the empty (`0`) and Ambiguous (`≥ 2`) arms, at ONE
/// `assert_eq!` per addressed kind.
///
/// Substrate primitive for future per-parent
/// `X_populated_kind_count_matches_populated_kinds_len` tests that
/// would otherwise each restate the same nested-`for k in K::ALL {
/// … }` sweep + composition-law equality + single-slot cardinality
/// pin — every one of the four production `.variant()` parents on
/// `ProcessSpec` binds through this ONE primitive with a per-site
/// `single_slot` factory. A fifth sibling picks up the scalar-
/// cardinality check through ONE call site — no re-authored
/// `for k in K::ALL { … }` sweep at the test surface, no re-authored
/// `assert_eq!` pair.
///
/// The `single_slot` closure stays per-site — reused verbatim from
/// the sibling primitives ([`assert_variant_round_trip`],
/// [`assert_find_agrees_with_has`],
/// [`assert_populated_kinds_matches_has`],
/// [`assert_single_slot_key_matches_label`]) — the closure IS the
/// "populate slot k" ground truth for the parent's field structure.
///
/// The [`crate::lifetime::Lifetime`] site is DELIBERATELY excluded
/// through the `T: TaggedUnion` bound — `Lifetime`'s `variant()`
/// returns `Ok(Permanent)` on empty rather than an `Empty` typed
/// error, so its projection shape diverges from the four
/// Empty-projecting parents. Same reasoning as
/// [`assert_variant_round_trip`]'s /
/// [`assert_find_agrees_with_has`]'s /
/// [`assert_populated_kinds_matches_has`]'s exclusions.
#[track_caller]
pub fn assert_populated_kind_count_matches_populated_kinds<T, F>(single_slot: F)
where
T: TaggedUnion,
T::Kind: PartialEq + std::fmt::Debug,
F: Fn(T::Kind) -> T,
{
for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let parent = single_slot(populated);
let count = parent.populated_kind_count();
let kinds_len = parent.populated_kinds().len();
// Composition law: scalar cardinality projection agrees with
// the widened primitive's `Vec::len()`.
assert_eq!(
count, kinds_len,
"TaggedUnion::populated_kind_count() drifted from populated_kinds().len() — populated={populated:?}",
);
// Single-slot diagonal — a well-formed parent from single_slot
// populates exactly the addressed slot, so the scalar cardinality
// is 1.
assert_eq!(
count, 1,
"TaggedUnion::populated_kind_count() on single_slot({populated:?}) must equal 1 exactly (well-formed arm cardinality)",
);
}
}
/// Generic closed-set-COMPLEMENT testkit — pins that
/// [`TaggedUnion::missing_kinds`] composes over
/// [`TaggedUnion::has`] under NEGATION across every
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) entry on
/// the single-slot side, that the returned `Vec` is the canonical
/// [`ClosedSet::ALL`]-ordered filter of `!has(k)`, that on the
/// populated diagonal `single_slot(k).missing_kinds()` equals
/// `ALL \ {k}` exactly (length `ALL.len() - 1`, canonical ordered,
/// `k` absent), AND that the partition law
/// `populated_kinds() ∪ missing_kinds() == ClosedSet::ALL` (with
/// the two sets disjoint) holds byte-identically.
///
/// Parent-axis substrate primitive for the tagged-union closed-set-
/// complement refinement — the peer of
/// [`crate::boundary::assert_slice_refinement_composition_laws`]'s
/// `missing_kinds` sub-arm on the slice-level presence-probe axis,
/// lifted here to the tagged-union parent-level presence-probe axis
/// (same shape, same composition operator under negation, second
/// instance in the workspace-wide closed-set-complement refinement
/// algebra).
///
/// The FOUR sub-assertions swept per populated slot:
///
/// 1. Per-kind membership under negation:
/// `parent.missing_kinds().contains(&k) == !parent.has(k)` for
/// every `k ∈ ClosedSet::ALL` — a regression that overrode
/// `missing_kinds` to skip a kind, drift the walk order from
/// canonical `ALL`, or return a superset containing populated
/// kinds surfaces at the specific kind's per-pair assertion.
/// 2. Canonical `ALL`-filter equality under negation:
/// `parent.missing_kinds() == ALL.iter().copied().filter(|k|
/// !parent.has(*k)).collect()` — a regression that returned
/// duplicates or drifted the walk order surfaces at the
/// post-loop equality assert.
/// 3. Single-slot diagonal: `single_slot(k).missing_kinds()`
/// equals `ALL` with `k` removed — length exactly `ALL.len() - 1`,
/// canonical order preserved. Pins the well-formed arm's
/// complement cardinality.
/// 4. Partition law: `populated_kinds() ∪ missing_kinds() ==
/// ClosedSet::ALL` byte-identically (concatenated then re-sorted
/// into canonical `ALL` order) AND the two sets are disjoint
/// (no kind appears in both). A regression on either side of the
/// partition (a kind that appears in NEITHER, or in BOTH) fails
/// HERE at the partition assert — the compound-lift's most-
/// load-bearing invariant.
///
/// Substrate primitive for future per-parent
/// `X_missing_kinds_matches_has` tests that would otherwise each
/// restate the same nested-`for populated in K::ALL { for probed
/// in K::ALL { … } }` sweep + canonical-order equality + single-
/// slot diagonal pin + partition-law composition — every one of
/// the four production `.variant()` parents on `ProcessSpec` binds
/// through this ONE primitive with a per-site `single_slot`
/// factory. A fifth sibling picks up the closed-set-complement
/// check through ONE call site — no re-authored `for k in K::ALL
/// { … }` sweep at the test surface, no re-authored `assert_eq!`
/// quad.
///
/// The `single_slot` closure stays per-site — reused verbatim from
/// the sibling primitives ([`assert_variant_round_trip`],
/// [`assert_find_agrees_with_has`],
/// [`assert_populated_kinds_matches_has`],
/// [`assert_populated_kind_count_matches_populated_kinds`],
/// [`assert_single_slot_key_matches_label`]).
///
/// The [`crate::lifetime::Lifetime`] site is DELIBERATELY excluded
/// through the `T: TaggedUnion` bound — same reasoning as the
/// sibling primitives.
#[track_caller]
pub fn assert_missing_kinds_matches_has<T, F>(single_slot: F)
where
T: TaggedUnion,
T::Kind: PartialEq + std::fmt::Debug,
F: Fn(T::Kind) -> T,
{
for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let parent = single_slot(populated);
let missing = parent.missing_kinds();
let populated_kinds = parent.populated_kinds();
// Per-kind membership composition law under negation, AND the
// XOR partition arm: every k ∈ ALL appears in exactly one of
// (populated_kinds, missing_kinds).
for probed in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
assert_eq!(
missing.contains(&probed),
!parent.has(probed),
"TaggedUnion::missing_kinds().contains({probed:?}) drifted from !has({probed:?}) — populated={populated:?}",
);
// XOR partition law: k ∈ populated_kinds ⊕ k ∈ missing_kinds
// — every closed-set entry lives on EXACTLY ONE side of the
// partition (populated OR missing, never both, never neither).
let in_populated = populated_kinds.contains(&probed);
let in_missing = missing.contains(&probed);
assert!(
in_populated ^ in_missing,
"partition law violated — {probed:?} appears in {} of (populated_kinds, missing_kinds), not exactly one (populated={populated:?})",
(in_populated as u8) + (in_missing as u8),
);
}
// Canonical ALL-filter equality under negation — pins dedup,
// walk order, and membership consistency at ONE assert.
let canonical: Vec<T::Kind> = <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
.filter(|k| !parent.has(*k))
.collect();
assert_eq!(
missing, canonical,
"TaggedUnion::missing_kinds() must yield ClosedSet::ALL-ordered subsequence where !has is true (no duplicates, canonical order) — populated={populated:?}",
);
// Single-slot diagonal — a well-formed parent from single_slot
// populates exactly the addressed slot, so the missing set is
// `ALL \ {populated}` in canonical order (length ALL.len() - 1,
// `populated` absent).
let expected_missing: Vec<T::Kind> = <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
.filter(|k| *k != populated)
.collect();
assert_eq!(
missing, expected_missing,
"TaggedUnion::missing_kinds() on single_slot({populated:?}) must return ClosedSet::ALL with {populated:?} removed",
);
}
}
/// Generic scalar-cardinality testkit for the closed-set-complement
/// axis — pins that [`TaggedUnion::missing_kind_count`] agrees with
/// [`TaggedUnion::missing_kinds`]`.len()` across every
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
/// arrangement AND that on the populated diagonal
/// `single_slot(k).missing_kind_count()` equals `ALL.len() - 1`
/// exactly (aligned with the single-slot arm's `missing_kinds()`
/// returning `ALL \ {k}`) AND that the scalar partition law
/// `populated_kind_count() + missing_kind_count() == ALL.len()`
/// holds byte-identically.
///
/// Parent-axis substrate primitive for the scalar-cardinality
/// refinement of the tagged-union closed-set-complement axis — the
/// scalar projection of [`assert_missing_kinds_matches_has`]'s
/// widened primitive. Together they close the three-refinement
/// composition contract that binds
/// [`TaggedUnion::missing_kind_count`] against
/// [`TaggedUnion::missing_kinds`] and against
/// [`TaggedUnion::populated_kind_count`]:
///
/// 1. **`count ↔ kinds.len()`**: `missing_kind_count() ==
/// missing_kinds().len()` — a regression that overrode
/// `missing_kind_count` to skip a kind (returning the populated
/// count instead), double-count a slot, or drift the walk from
/// `ClosedSet::ALL` surfaces at the substrate boundary here.
/// 2. **Single-slot diagonal**: `single_slot(k).missing_kind_count()
/// == ALL.len() - 1` — pins the well-formed arm's complement
/// cardinality against the empty (`ALL.len()`) and Ambiguous
/// (`< ALL.len() - 1`) arms.
/// 3. **Scalar partition law**: `populated_kind_count() +
/// missing_kind_count() == ALL.len()` — the scalar consequence
/// of the `(populated_kinds, missing_kinds)` partition law that
/// [`assert_missing_kinds_matches_has`] pins at the widened-
/// primitive layer. A regression on either scalar side (an
/// off-by-one on missing, a drift on populated) fails HERE at
/// the sum assertion.
///
/// Substrate primitive for future per-parent
/// `X_missing_kind_count_matches_missing_kinds_len` tests that
/// would otherwise each restate the same nested-`for k in K::ALL {
/// … }` sweep + composition-law equality + single-slot cardinality
/// pin + scalar partition — every one of the four production
/// `.variant()` parents on `ProcessSpec` binds through this ONE
/// primitive with a per-site `single_slot` factory. A fifth sibling
/// picks up the scalar-cardinality check through ONE call site.
///
/// The `single_slot` closure stays per-site — reused verbatim from
/// the sibling primitives ([`assert_variant_round_trip`],
/// [`assert_find_agrees_with_has`],
/// [`assert_populated_kinds_matches_has`],
/// [`assert_populated_kind_count_matches_populated_kinds`],
/// [`assert_missing_kinds_matches_has`],
/// [`assert_single_slot_key_matches_label`]).
///
/// The [`crate::lifetime::Lifetime`] site is DELIBERATELY excluded
/// through the `T: TaggedUnion` bound — same reasoning as the
/// sibling primitives.
#[track_caller]
pub fn assert_missing_kind_count_matches_missing_kinds<T, F>(single_slot: F)
where
T: TaggedUnion,
T::Kind: PartialEq + std::fmt::Debug,
F: Fn(T::Kind) -> T,
{
let all_len = <T::Kind as tatara_closed_set::ClosedSet>::ALL.len();
for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let parent = single_slot(populated);
let count = parent.missing_kind_count();
let missing_len = parent.missing_kinds().len();
// Composition law: scalar cardinality projection agrees with
// the widened primitive's `Vec::len()`.
assert_eq!(
count, missing_len,
"TaggedUnion::missing_kind_count() drifted from missing_kinds().len() — populated={populated:?}",
);
// Single-slot diagonal — a well-formed parent from single_slot
// populates exactly the addressed slot, so the missing count is
// ALL.len() - 1.
assert_eq!(
count,
all_len - 1,
"TaggedUnion::missing_kind_count() on single_slot({populated:?}) must equal ALL.len() - 1 exactly (well-formed arm complement cardinality)",
);
// Scalar partition law: populated_kind_count + missing_kind_count == ALL.len().
let populated_count = parent.populated_kind_count();
assert_eq!(
populated_count + count,
all_len,
"scalar partition law violated — populated_kind_count + missing_kind_count must equal ClosedSet::ALL.len() (populated={populated:?})",
);
}
}
/// Generic earliest-populated-kind testkit — pins that
/// [`TaggedUnion::first_populated_kind`] agrees with
/// [`TaggedUnion::populated_kinds`]`.first().copied()` across every
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
/// arrangement AND that on the populated diagonal
/// `single_slot(k).first_populated_kind()` equals `Some(k)` exactly.
///
/// Parent-axis substrate primitive for the earliest-element scalar
/// projection of the tagged-union closed-set-inversion axis — the
/// `Option<Kind>`-valued projection of
/// [`assert_populated_kinds_matches_has`]'s widened primitive. The
/// three sub-assertions swept per populated slot:
///
/// 1. **`first ↔ kinds.first().copied()`**: `first_populated_kind() ==
/// populated_kinds().first().copied()` — a regression that
/// overrode `first_populated_kind` to skip the earliest match (a
/// `.rev().find(...)` inlined by mistake), drop the short-circuit
/// (allocating a full `Vec` at the callsite), or drift the walk
/// from `ClosedSet::ALL` surfaces here.
/// 2. **Single-slot diagonal**: `single_slot(k).first_populated_kind()
/// == Some(k)` — the earliest populated slot on a well-formed
/// parent IS the sole populated slot.
/// 3. **Emptiness composition law**: `first_populated_kind().is_none()
/// == (populated_kind_count() == 0)` — the earliest-element
/// projection agrees with the scalar cardinality on the empty
/// boundary. (Trivially `false == false` on every single-slot
/// arrangement; the load-bearing case is the sibling
/// empty-parent probe outside this primitive.)
///
/// A fifth sibling picks up the earliest-populated check through ONE
/// call site — no re-authored `for k in K::ALL` sweep, no re-authored
/// `assert_eq!(single_slot(k).first_populated_kind(), Some(k))`.
///
/// Same `Lifetime` exclusion as the sibling primitives.
#[track_caller]
pub fn assert_first_populated_kind_matches_populated_kinds<T, F>(single_slot: F)
where
T: TaggedUnion,
T::Kind: PartialEq + std::fmt::Debug,
F: Fn(T::Kind) -> T,
{
for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let parent = single_slot(populated);
let first = parent.first_populated_kind();
let via_kinds = parent.populated_kinds().first().copied();
// Composition law: earliest-element projection agrees with the
// widened primitive's `Vec::first().copied()`.
assert_eq!(
first, via_kinds,
"TaggedUnion::first_populated_kind() drifted from populated_kinds().first().copied() — populated={populated:?}",
);
// Single-slot diagonal — a well-formed parent from single_slot
// populates exactly the addressed slot, so the earliest
// populated slot IS that slot.
assert_eq!(
first,
Some(populated),
"TaggedUnion::first_populated_kind() on single_slot({populated:?}) must equal Some({populated:?}) exactly",
);
// Emptiness composition law on the well-formed diagonal —
// exactly-one is a strictly non-empty populated set, so the
// scalar cardinality and the earliest-element `is_some()`
// agree.
assert_eq!(
first.is_some(),
parent.populated_kind_count() > 0,
"first_populated_kind().is_some() drifted from (populated_kind_count() > 0) — populated={populated:?}",
);
}
}
/// Generic earliest-missing-kind testkit — pins that
/// [`TaggedUnion::first_missing_kind`] agrees with
/// [`TaggedUnion::missing_kinds`]`.first().copied()` across every
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
/// arrangement AND that on the populated diagonal
/// `single_slot(k).first_missing_kind()` equals the earliest `ALL`
/// entry NOT equal to `k`.
///
/// Parent-axis substrate primitive for the earliest-element scalar
/// projection of the tagged-union closed-set-complement axis — the
/// `Option<Kind>`-valued projection of
/// [`assert_missing_kinds_matches_has`]'s widened primitive under a
/// negated `has` predicate. The three sub-assertions swept per
/// populated slot:
///
/// 1. **`first ↔ missing.first().copied()`**: `first_missing_kind()
/// == missing_kinds().first().copied()` — a regression that
/// overrode `first_missing_kind` to drop the negation (returning
/// the populated side instead) or drift the walk from
/// `ClosedSet::ALL` surfaces here.
/// 2. **Single-slot diagonal**: `single_slot(k).first_missing_kind()`
/// equals the earliest `ALL` entry not equal to `k` — a well-
/// formed parent's missing set is `ALL \ {k}` in canonical order,
/// so its earliest element is `ALL[0]` when `k != ALL[0]`, else
/// `ALL[1]`.
/// 3. **Emptiness composition law**: `first_missing_kind().is_some()
/// == (missing_kind_count() > 0)` — the earliest-missing
/// projection agrees with the scalar complement cardinality.
/// Non-trivial on the single-slot arm when `ALL.len() > 1`.
///
/// A fifth sibling picks up the earliest-missing check through ONE
/// call site.
///
/// Same `Lifetime` exclusion as the sibling primitives.
#[track_caller]
pub fn assert_first_missing_kind_matches_missing_kinds<T, F>(single_slot: F)
where
T: TaggedUnion,
T::Kind: PartialEq + std::fmt::Debug,
F: Fn(T::Kind) -> T,
{
for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let parent = single_slot(populated);
let first = parent.first_missing_kind();
let via_missing = parent.missing_kinds().first().copied();
// Composition law: earliest-element projection agrees with the
// widened primitive's `Vec::first().copied()`.
assert_eq!(
first, via_missing,
"TaggedUnion::first_missing_kind() drifted from missing_kinds().first().copied() — populated={populated:?}",
);
// Single-slot diagonal — the missing set is ALL \ {populated}
// in canonical order, so its earliest element is the earliest
// ALL entry not equal to populated.
let expected_first_missing = <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
.find(|k| *k != populated);
assert_eq!(
first, expected_first_missing,
"TaggedUnion::first_missing_kind() on single_slot({populated:?}) must equal earliest ClosedSet::ALL entry != {populated:?}",
);
// Emptiness composition law — the earliest-missing projection
// agrees with the scalar complement cardinality's positivity.
assert_eq!(
first.is_some(),
parent.missing_kind_count() > 0,
"first_missing_kind().is_some() drifted from (missing_kind_count() > 0) — populated={populated:?}",
);
}
}
/// Generic latest-populated-kind testkit — pins that
/// [`TaggedUnion::last_populated_kind`] agrees with
/// [`TaggedUnion::populated_kinds`]`.last().copied()` across every
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
/// arrangement AND that on the populated diagonal
/// `single_slot(k).last_populated_kind()` equals `Some(k)` exactly.
///
/// Parent-axis substrate primitive for the latest-element scalar
/// projection of the tagged-union closed-set-inversion axis — the
/// `Option<Kind>`-valued REVERSED-walk peer of
/// [`assert_first_populated_kind_matches_populated_kinds`]'s
/// earliest-element projection. The three sub-assertions swept per
/// populated slot:
///
/// 1. **`last ↔ kinds.last().copied()`**: `last_populated_kind() ==
/// populated_kinds().last().copied()` — a regression that overrode
/// `last_populated_kind` to walk `ALL` forward (defeating the
/// time-reversal), drop the short-circuit, or drift the walk from
/// `ClosedSet::ALL` surfaces here.
/// 2. **Single-slot diagonal**: `single_slot(k).last_populated_kind()
/// == Some(k)` — the sole populated slot on a well-formed parent
/// IS both the earliest AND the latest populated slot (the
/// endpoint projections agree on the exactly-one arm).
/// 3. **Emptiness composition law**: `last_populated_kind().is_none()
/// == (populated_kind_count() == 0)` — the latest-element
/// projection agrees with the scalar cardinality on the empty
/// boundary. (Trivially `false == false` on every single-slot
/// arrangement; the load-bearing case is the sibling empty-parent
/// probe outside this primitive.)
///
/// A fifth sibling picks up the latest-populated check through ONE
/// call site — no re-authored reversed `for k in K::ALL.iter().rev()`
/// sweep at the test surface, no re-authored
/// `assert_eq!(single_slot(k).last_populated_kind(), Some(k))`.
///
/// Same `Lifetime` exclusion as the sibling primitives.
#[track_caller]
pub fn assert_last_populated_kind_matches_populated_kinds<T, F>(single_slot: F)
where
T: TaggedUnion,
T::Kind: PartialEq + std::fmt::Debug,
F: Fn(T::Kind) -> T,
{
for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let parent = single_slot(populated);
let last = parent.last_populated_kind();
let via_kinds = parent.populated_kinds().last().copied();
// Composition law: latest-element projection agrees with the
// widened primitive's `Vec::last().copied()`.
assert_eq!(
last, via_kinds,
"TaggedUnion::last_populated_kind() drifted from populated_kinds().last().copied() — populated={populated:?}",
);
// Single-slot diagonal — the sole populated slot IS both the
// earliest and the latest, so the endpoint projections
// coincide.
assert_eq!(
last,
Some(populated),
"TaggedUnion::last_populated_kind() on single_slot({populated:?}) must equal Some({populated:?}) exactly",
);
// Emptiness composition law on the well-formed diagonal.
assert_eq!(
last.is_some(),
parent.populated_kind_count() > 0,
"last_populated_kind().is_some() drifted from (populated_kind_count() > 0) — populated={populated:?}",
);
}
}
/// Generic latest-missing-kind testkit — pins that
/// [`TaggedUnion::last_missing_kind`] agrees with
/// [`TaggedUnion::missing_kinds`]`.last().copied()` across every
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
/// arrangement AND that on the populated diagonal
/// `single_slot(k).last_missing_kind()` equals the latest `ALL` entry
/// NOT equal to `k`.
///
/// Parent-axis substrate primitive for the latest-element scalar
/// projection of the tagged-union closed-set-complement axis — the
/// `Option<Kind>`-valued REVERSED-walk peer of
/// [`assert_first_missing_kind_matches_missing_kinds`]'s
/// earliest-element projection under a negated `has` predicate. The
/// three sub-assertions swept per populated slot:
///
/// 1. **`last ↔ missing.last().copied()`**: `last_missing_kind() ==
/// missing_kinds().last().copied()` — a regression that overrode
/// `last_missing_kind` to walk `ALL` forward (defeating the
/// time-reversal), drop the negation (returning the populated
/// side's latest instead), or drift the walk from `ClosedSet::ALL`
/// surfaces here.
/// 2. **Single-slot diagonal**: `single_slot(k).last_missing_kind()`
/// equals the LATEST `ALL` entry not equal to `k` — a well-formed
/// parent's missing set is `ALL \ {k}` in canonical order, so its
/// latest element is `ALL[ALL.len()-1]` when `k != ALL[ALL.len()-1]`,
/// else `ALL[ALL.len()-2]`.
/// 3. **Emptiness composition law**: `last_missing_kind().is_some()
/// == (missing_kind_count() > 0)` — the latest-missing projection
/// agrees with the scalar complement cardinality. Non-trivial on
/// the single-slot arm when `ALL.len() > 1`.
///
/// A fifth sibling picks up the latest-missing check through ONE call
/// site.
///
/// Same `Lifetime` exclusion as the sibling primitives.
#[track_caller]
pub fn assert_last_missing_kind_matches_missing_kinds<T, F>(single_slot: F)
where
T: TaggedUnion,
T::Kind: PartialEq + std::fmt::Debug,
F: Fn(T::Kind) -> T,
{
for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let parent = single_slot(populated);
let last = parent.last_missing_kind();
let via_missing = parent.missing_kinds().last().copied();
// Composition law: latest-element projection agrees with the
// widened primitive's `Vec::last().copied()`.
assert_eq!(
last, via_missing,
"TaggedUnion::last_missing_kind() drifted from missing_kinds().last().copied() — populated={populated:?}",
);
// Single-slot diagonal — the missing set is ALL \ {populated}
// in canonical order, so its latest element is the latest ALL
// entry not equal to populated.
let expected_last_missing = <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.rev()
.copied()
.find(|k| *k != populated);
assert_eq!(
last, expected_last_missing,
"TaggedUnion::last_missing_kind() on single_slot({populated:?}) must equal latest ClosedSet::ALL entry != {populated:?}",
);
// Emptiness composition law — the latest-missing projection
// agrees with the scalar complement cardinality's positivity.
assert_eq!(
last.is_some(),
parent.missing_kind_count() > 0,
"last_missing_kind().is_some() drifted from (missing_kind_count() > 0) — populated={populated:?}",
);
}
}
/// Generic exactly-one-populated-kind testkit — pins that
/// [`TaggedUnion::unique_populated_kind`] returns `Some(k)` iff exactly
/// one slot is populated (and names that slot's kind), and `None` on
/// every empty / ambiguous parent, across every
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
/// arrangement.
///
/// Parent-axis substrate primitive for the exactly-one-hit scalar
/// projection of the tagged-union closed-set-inversion axis — the
/// `Option<Kind>`-valued exactly-one peer of
/// [`assert_first_populated_kind_matches_populated_kinds`] and
/// [`assert_last_populated_kind_matches_populated_kinds`]'s endpoint
/// projections. The four sub-assertions swept per populated slot:
///
/// 1. **`unique ↔ exactly-one on kinds`**: `unique_populated_kind() ==
/// Some(k)` iff `populated_kinds() == vec![k]` — a regression that
/// dropped the second-hit short-circuit (returning `Some(first)`
/// on a two-populated parent) fails on the sibling
/// two-populated pin above.
/// 2. **Single-slot diagonal**: `single_slot(k).unique_populated_kind()
/// == Some(k)` — the sole populated slot IS the unique populated
/// kind.
/// 3. **Cardinality composition law**:
/// `unique_populated_kind().is_some() == (populated_kind_count()
/// == 1)` — the exactly-one predicate agrees with the scalar
/// cardinality on every well-formed / empty / ambiguous arm.
/// 4. **Endpoint agreement on Some**: on the `Some` arm,
/// `unique_populated_kind() == first_populated_kind() ==
/// last_populated_kind()` — the three endpoint-projection
/// primitives coincide on the exactly-one arm and DIVERGE only on
/// the ambiguous arm.
///
/// A fifth sibling picks up the exactly-one-populated check through
/// ONE call site — no re-authored `count == 1` composition at the
/// test surface, no re-authored `single_slot(k).unique_populated_kind()
/// == Some(k)` diagonal pin, no re-authored endpoint-agreement
/// projection.
///
/// Same `Lifetime` exclusion as the sibling primitives.
#[track_caller]
pub fn assert_unique_populated_kind_matches_populated_kinds<T, F>(single_slot: F)
where
T: TaggedUnion,
T::Kind: PartialEq + std::fmt::Debug,
F: Fn(T::Kind) -> T,
{
for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let parent = single_slot(populated);
let unique = parent.unique_populated_kind();
// Composition law: exactly-one predicate on the widened primitive.
let kinds = parent.populated_kinds();
let expected = if kinds.len() == 1 {
Some(kinds[0])
} else {
None
};
assert_eq!(
unique, expected,
"TaggedUnion::unique_populated_kind() drifted from (populated_kinds().len() == 1 ? Some(kinds[0]) : None) — populated={populated:?}",
);
// Single-slot diagonal — a well-formed parent from single_slot
// populates exactly the addressed slot, so the unique populated
// kind IS that slot.
assert_eq!(
unique,
Some(populated),
"TaggedUnion::unique_populated_kind() on single_slot({populated:?}) must equal Some({populated:?}) exactly",
);
// Cardinality composition law — exactly-one predicate agrees
// with the scalar cardinality's equality-to-one.
assert_eq!(
unique.is_some(),
parent.populated_kind_count() == 1,
"unique_populated_kind().is_some() drifted from (populated_kind_count() == 1) — populated={populated:?}",
);
// Endpoint-agreement — on the Some arm the three endpoint
// projections coincide.
if unique.is_some() {
assert_eq!(
unique,
parent.first_populated_kind(),
"unique_populated_kind() must equal first_populated_kind() on the Some arm — populated={populated:?}",
);
assert_eq!(
unique,
parent.last_populated_kind(),
"unique_populated_kind() must equal last_populated_kind() on the Some arm — populated={populated:?}",
);
}
}
}
/// Generic exactly-one-missing-kind testkit — pins that
/// [`TaggedUnion::unique_missing_kind`] returns `Some(k)` iff exactly
/// one slot is missing (and names that slot's kind), and `None` on
/// every parent whose missing-set cardinality is not one, across
/// every [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-
/// slot arrangement.
///
/// Parent-axis substrate primitive for the exactly-one-hit scalar
/// projection of the tagged-union closed-set-COMPLEMENT axis under a
/// negated `has` predicate. The three sub-assertions swept per
/// populated slot (single-slot diagonal only — on any tagged union
/// with `ALL.len() > 2` the single-slot arrangement has ≥ 2 missing
/// slots, so the primitive returns `None`; the load-bearing `Some`
/// pins are the sibling near-saturation probes outside this
/// primitive):
///
/// 1. **`unique ↔ exactly-one on missing`**: `unique_missing_kind()
/// == Some(k)` iff `missing_kinds() == vec![k]` — a regression
/// that dropped the second-hit short-circuit (returning
/// `Some(first)` on a two-missing parent) fails here.
/// 2. **Cardinality composition law**:
/// `unique_missing_kind().is_some() == (missing_kind_count() ==
/// 1)` — the exactly-one predicate agrees with the scalar
/// complement cardinality on every well-formed / empty / ambiguous
/// arm.
/// 3. **Endpoint agreement on Some**: on the `Some` arm,
/// `unique_missing_kind() == first_missing_kind() ==
/// last_missing_kind()` — the three endpoint-projection
/// primitives on the missing axis coincide when exactly one slot
/// is empty.
///
/// A fifth sibling picks up the exactly-one-missing check through
/// ONE call site.
///
/// Same `Lifetime` exclusion as the sibling primitives.
#[track_caller]
pub fn assert_unique_missing_kind_matches_missing_kinds<T, F>(single_slot: F)
where
T: TaggedUnion,
T::Kind: PartialEq + std::fmt::Debug,
F: Fn(T::Kind) -> T,
{
for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let parent = single_slot(populated);
let unique = parent.unique_missing_kind();
// Composition law: exactly-one predicate on the widened
// primitive.
let missing = parent.missing_kinds();
let expected = if missing.len() == 1 {
Some(missing[0])
} else {
None
};
assert_eq!(
unique, expected,
"TaggedUnion::unique_missing_kind() drifted from (missing_kinds().len() == 1 ? Some(missing[0]) : None) — populated={populated:?}",
);
// Cardinality composition law — exactly-one predicate agrees
// with the scalar complement cardinality's equality-to-one.
assert_eq!(
unique.is_some(),
parent.missing_kind_count() == 1,
"unique_missing_kind().is_some() drifted from (missing_kind_count() == 1) — populated={populated:?}",
);
// Endpoint-agreement — on the Some arm the three endpoint
// projections on the missing axis coincide.
if unique.is_some() {
assert_eq!(
unique,
parent.first_missing_kind(),
"unique_missing_kind() must equal first_missing_kind() on the Some arm — populated={populated:?}",
);
assert_eq!(
unique,
parent.last_missing_kind(),
"unique_missing_kind() must equal last_missing_kind() on the Some arm — populated={populated:?}",
);
}
}
}
/// Generic zero-populated-cardinality Boolean testkit — pins that
/// [`TaggedUnion::is_empty`] agrees with the scalar cardinality
/// primitive's equality-to-zero across every
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
/// arrangement AND the empty-parent baseline.
///
/// Parent-axis substrate primitive for the Boolean cardinality-
/// endpoint scalar projection of the tagged-union closed-set-inversion
/// axis under a zero-arm equality — the `bool`-valued zero-endpoint
/// peer of [`assert_populated_kind_count_matches_populated_kinds`]'s
/// scalar cardinality projection. The three sub-assertions swept per
/// populated slot + the ONE baseline sub-assertion on the empty
/// parent:
///
/// 1. **Cardinality composition law**: `is_empty() ==
/// (populated_kind_count() == 0)` — the Boolean projection agrees
/// with the scalar cardinality's zero-arm equality on every empty /
/// well-formed / partial / saturated arm. Byte-identical to the
/// trait's default body, pinning it substrate-wide so a regression
/// that overrides `is_empty` to skip the sweep or return the wrong
/// Boolean fails here.
/// 2. **Widened-primitive agreement**: `is_empty() ==
/// populated_kinds().is_empty()` — the two zero-arm projections of
/// the populated cardinality (via `is_empty()` short-circuit walk
/// vs. via `populated_kinds()` Vec materialization then `.is_empty()`)
/// coincide byte-identically.
/// 3. **Single-slot diagonal**: `single_slot(k).is_empty() == false` —
/// a well-formed parent from `single_slot` populates exactly the
/// addressed slot, so it CANNOT be empty. Pins that the primitive
/// doesn't drift onto the populated side of the endpoint.
/// 4. **Empty-parent baseline** (swept once outside the per-`k` loop):
/// `T::empty(T::KIND_LIST).is_empty() == true` (via a constructed
/// all-`None` parent since [`TaggedUnionError::empty`] is on the
/// error carrier, not the parent factory — the parent-side empty
/// fixture is composed by the caller through `Default` on the
/// sibling scaffold). Pins the primitive's zero-arm — a regression
/// that inverted the negation surfaces here.
///
/// A fifth sibling tagged-union parent picks up the zero-cardinality-
/// Boolean check through ONE `impl TaggedUnion for X` block + ONE
/// per-site `single_slot_X` factory + ONE per-site `empty_X` factory,
/// plus ONE call site — no re-authored `is_empty` sweep at the test
/// surface.
///
/// Same `Lifetime` exclusion as the sibling primitives — see
/// [`assert_two_slots_ambiguous`].
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs. The
/// Boolean zero-endpoint projection binds through the SAME shape
/// the scalar cardinality binds through (a closed-set walk under
/// `Self::has`), differing only in the return-type collapse
/// (`bool` vs. `usize`) and the short-circuit gate (`!any` vs.
/// `count`).
/// - THEORY.md §VI.1 — generation over composition. A new
/// [`Self::Kind`] variant added to `ALL` reaches this primitive
/// mechanically through the `any` short-circuit at the trait's
/// default body.
#[track_caller]
pub fn assert_is_empty_matches_populated_kind_count<T, F, G>(single_slot: F, empty_parent: G)
where
T: TaggedUnion,
T::Kind: PartialEq + std::fmt::Debug,
F: Fn(T::Kind) -> T,
G: Fn() -> T,
{
// Empty-parent baseline — the SOLE arm where `is_empty()` returns
// `true`. The caller supplies the empty-parent fixture (an all-
// `None` construction on the sibling scaffold's field structure).
let empty = empty_parent();
assert!(
empty.is_empty(),
"TaggedUnion::is_empty() on empty_parent() must equal true",
);
assert_eq!(
empty.is_empty(),
empty.populated_kind_count() == 0,
"empty_parent().is_empty() drifted from (populated_kind_count() == 0)",
);
assert_eq!(
empty.is_empty(),
empty.populated_kinds().is_empty(),
"empty_parent().is_empty() drifted from populated_kinds().is_empty()",
);
for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let parent = single_slot(populated);
let is_empty = parent.is_empty();
// Cardinality composition law — Boolean projection agrees with
// the scalar cardinality's zero-arm equality.
assert_eq!(
is_empty,
parent.populated_kind_count() == 0,
"TaggedUnion::is_empty() drifted from (populated_kind_count() == 0) — populated={populated:?}",
);
// Widened-primitive agreement — the two zero-arm projections
// of the populated cardinality coincide.
assert_eq!(
is_empty,
parent.populated_kinds().is_empty(),
"TaggedUnion::is_empty() drifted from populated_kinds().is_empty() — populated={populated:?}",
);
// Single-slot diagonal — a well-formed parent from single_slot
// is NEVER empty.
assert!(
!is_empty,
"TaggedUnion::is_empty() on single_slot({populated:?}) must equal false",
);
}
}
/// Generic zero-missing-cardinality Boolean testkit — pins that
/// [`TaggedUnion::is_saturated`] agrees with the scalar complement
/// cardinality primitive's equality-to-zero across every
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
/// arrangement AND the empty-parent baseline.
///
/// Parent-axis substrate primitive for the Boolean cardinality-
/// endpoint scalar projection of the tagged-union closed-set-COMPLEMENT
/// axis under a zero-arm equality — the `bool`-valued top-endpoint
/// peer of [`assert_missing_kind_count_matches_missing_kinds`]'s
/// scalar complement cardinality projection. The three sub-assertions
/// swept per populated slot + the ONE baseline sub-assertion on the
/// empty parent:
///
/// 1. **Cardinality composition law**: `is_saturated() ==
/// (missing_kind_count() == 0)` — the Boolean projection agrees
/// with the scalar complement cardinality's zero-arm equality on
/// every empty / well-formed / partial / saturated arm. Byte-
/// identical to the trait's default body, pinning it substrate-
/// wide so a regression that overrides `is_saturated` to skip the
/// sweep or return the wrong Boolean fails here.
/// 2. **Widened-primitive agreement**: `is_saturated() ==
/// missing_kinds().is_empty()` — the two zero-arm projections of
/// the missing cardinality (via `is_saturated()` short-circuit walk
/// vs. via `missing_kinds()` Vec materialization then
/// `.is_empty()`) coincide byte-identically.
/// 3. **Single-slot diagonal** (on `ALL.len() ≥ 2` closed sets):
/// `single_slot(k).is_saturated() == false` — a well-formed parent
/// from `single_slot` populates exactly one slot, leaving at least
/// one slot missing (`ALL.len() - 1 ≥ 1`), so it CANNOT be
/// saturated on any real-world tagged union in this workspace.
/// Pins that the primitive doesn't drift onto the missing-side
/// zero endpoint.
/// 4. **Empty-parent baseline** (swept once outside the per-`k` loop):
/// `empty_parent().is_saturated() == false` (empty has EVERY slot
/// missing, so `ALL.len() ≥ 1` missing, NEVER zero). Pins the
/// primitive's opposite-arm on the same fixture the empty-Boolean
/// peer pins its zero-arm.
///
/// A fifth sibling tagged-union parent picks up the zero-complement-
/// cardinality-Boolean check through ONE `impl TaggedUnion for X`
/// block + ONE per-site `single_slot_X` factory + ONE per-site
/// `empty_X` factory + ONE call site — no re-authored `is_saturated`
/// sweep at the test surface.
///
/// Same `Lifetime` exclusion as the sibling primitives.
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs. The
/// Boolean top-endpoint projection binds through the SAME shape
/// the scalar complement cardinality binds through (a closed-set
/// walk under `Self::has`), differing only in the return-type
/// collapse (`bool` vs. `usize`) and the short-circuit gate (`all`
/// vs. `count`).
/// - THEORY.md §VI.1 — generation over composition. A new
/// [`Self::Kind`] variant added to `ALL` reaches this primitive
/// mechanically through the `all` short-circuit at the trait's
/// default body.
#[track_caller]
pub fn assert_is_saturated_matches_missing_kind_count<T, F, G>(single_slot: F, empty_parent: G)
where
T: TaggedUnion,
T::Kind: PartialEq + std::fmt::Debug,
F: Fn(T::Kind) -> T,
G: Fn() -> T,
{
// Empty-parent baseline — the empty parent has EVERY slot missing,
// so `is_saturated()` returns `false` (the opposite endpoint of
// where `is_empty()` returns `true`).
let empty = empty_parent();
assert!(
!empty.is_saturated(),
"TaggedUnion::is_saturated() on empty_parent() must equal false — every slot is missing",
);
assert_eq!(
empty.is_saturated(),
empty.missing_kind_count() == 0,
"empty_parent().is_saturated() drifted from (missing_kind_count() == 0)",
);
assert_eq!(
empty.is_saturated(),
empty.missing_kinds().is_empty(),
"empty_parent().is_saturated() drifted from missing_kinds().is_empty()",
);
for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let parent = single_slot(populated);
let is_saturated = parent.is_saturated();
// Cardinality composition law — Boolean projection agrees with
// the scalar complement cardinality's zero-arm equality.
assert_eq!(
is_saturated,
parent.missing_kind_count() == 0,
"TaggedUnion::is_saturated() drifted from (missing_kind_count() == 0) — populated={populated:?}",
);
// Widened-primitive agreement — the two zero-arm projections
// of the missing cardinality coincide.
assert_eq!(
is_saturated,
parent.missing_kinds().is_empty(),
"TaggedUnion::is_saturated() drifted from missing_kinds().is_empty() — populated={populated:?}",
);
// Single-slot diagonal (on any `ALL.len() ≥ 2` closed set) — a
// well-formed parent leaves `ALL.len() - 1 ≥ 1` missing, so it
// CANNOT be saturated. This holds for every production tagged
// union in the workspace (all have `ALL.len() ≥ 2`).
assert!(
!is_saturated,
"TaggedUnion::is_saturated() on single_slot({populated:?}) must equal false — ALL.len() >= 2",
);
}
}
/// Generic at-least-one-populated-cardinality Boolean testkit — pins
/// that [`TaggedUnion::has_any_populated_kind`] agrees with its
/// definitional complement [`TaggedUnion::is_empty`] AND with the
/// scalar cardinality primitive's strict-inequality-to-zero across
/// every [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-
/// slot arrangement AND the empty-parent baseline.
///
/// Parent-axis substrate primitive for the Boolean at-least-one
/// halfspace projection on the tagged-union closed-set-inversion axis
/// — the `bool`-valued definitional complement of
/// [`assert_is_empty_matches_populated_kind_count`]'s zero-endpoint
/// Boolean projection, and the SUBSET peer of the zero-arm Boolean on
/// the populated cardinality lattice. The four sub-assertions swept
/// per populated slot + the ONE baseline sub-assertion on the empty
/// parent:
///
/// 1. **Definitional complement law**: `has_any_populated_kind() ==
/// !is_empty()` — the SUBSET Boolean is the bit-flip of the
/// zero-endpoint Boolean on every empty / well-formed / partial /
/// saturated arm. Byte-identical to the trait's default body
/// (both walk `<Self::Kind as ClosedSet>::ALL.iter().any(has)`,
/// the endpoint arm negates the whole expression), pinning the
/// pair substrate-wide so a regression that overrides
/// `has_any_populated_kind` to skip the sweep or drift off the
/// complement law surfaces here.
/// 2. **Cardinality composition law**: `has_any_populated_kind() ==
/// (populated_kind_count() > 0)` — the ≥ 1 halfspace agrees with
/// the scalar cardinality's strict-inequality-to-zero on every arm.
/// 3. **Widened-primitive agreement**: `has_any_populated_kind() ==
/// !populated_kinds().is_empty()` — the two at-least-one
/// projections of the populated cardinality (via
/// `has_any_populated_kind()` short-circuit walk vs. via
/// `populated_kinds()` `Vec` materialization then `!is_empty()`)
/// coincide byte-identically.
/// 4. **Single-slot diagonal**: `single_slot(k).has_any_populated_kind()
/// == true` — a well-formed parent from `single_slot` populates
/// exactly one slot, so the ≥ 1 halfspace returns `true`. Pins
/// that the primitive doesn't drift off the well-formed arm.
/// 5. **Empty-parent baseline** (swept once outside the per-`k` loop):
/// `empty_parent().has_any_populated_kind() == false` (empty has
/// zero populated). Pins the primitive's opposite arm on the same
/// fixture the zero-endpoint peer pins its zero-arm — the only arm
/// where the ≥ 1 halfspace returns `false`.
///
/// A fifth sibling tagged-union parent picks up the at-least-one-
/// populated-cardinality-Boolean check through ONE `impl TaggedUnion
/// for X` block + ONE per-site `single_slot_X` factory + ONE per-site
/// `empty_X` factory + ONE call site — no re-authored
/// `has_any_populated_kind` sweep at the test surface.
///
/// Same `Lifetime` exclusion as the sibling primitives — see
/// [`assert_two_slots_ambiguous`].
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs. The
/// Boolean at-least-one halfspace projection binds through the SAME
/// shape [`assert_is_empty_matches_populated_kind_count`] binds
/// through (a closed-set `any` walk under `Self::has`), differing
/// only in the final negation the zero-endpoint applies — pinned as
/// the definitional-complement law at ONE substrate site inside the
/// testkit's per-arm sweep.
/// - THEORY.md §VI.1 — generation over composition. A new
/// [`Self::Kind`] variant added to `ALL` reaches this primitive
/// mechanically through the `any` short-circuit at the trait's
/// default body.
#[track_caller]
pub fn assert_has_any_populated_kind_matches_populated_kind_count<T, F, G>(
single_slot: F,
empty_parent: G,
) where
T: TaggedUnion,
T::Kind: PartialEq + std::fmt::Debug,
F: Fn(T::Kind) -> T,
G: Fn() -> T,
{
// Empty-parent baseline — the SOLE arm where
// `has_any_populated_kind()` returns `false`. The definitional
// complement law binds this to `is_empty() == true`.
let empty = empty_parent();
assert!(
!empty.has_any_populated_kind(),
"TaggedUnion::has_any_populated_kind() on empty_parent() must equal false",
);
assert_eq!(
empty.has_any_populated_kind(),
!empty.is_empty(),
"empty_parent().has_any_populated_kind() drifted from !is_empty()",
);
assert_eq!(
empty.has_any_populated_kind(),
empty.populated_kind_count() > 0,
"empty_parent().has_any_populated_kind() drifted from (populated_kind_count() > 0)",
);
assert_eq!(
empty.has_any_populated_kind(),
!empty.populated_kinds().is_empty(),
"empty_parent().has_any_populated_kind() drifted from !populated_kinds().is_empty()",
);
for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let parent = single_slot(populated);
let has_any = parent.has_any_populated_kind();
// Definitional complement law — SUBSET Boolean is the bit-flip
// of the zero-endpoint Boolean.
assert_eq!(
has_any,
!parent.is_empty(),
"TaggedUnion::has_any_populated_kind() drifted from !is_empty() — populated={populated:?}",
);
// Cardinality composition law — ≥ 1 halfspace agrees with
// scalar cardinality's strict-inequality-to-zero.
assert_eq!(
has_any,
parent.populated_kind_count() > 0,
"TaggedUnion::has_any_populated_kind() drifted from (populated_kind_count() > 0) — populated={populated:?}",
);
// Widened-primitive agreement — the two at-least-one projections
// of the populated cardinality coincide.
assert_eq!(
has_any,
!parent.populated_kinds().is_empty(),
"TaggedUnion::has_any_populated_kind() drifted from !populated_kinds().is_empty() — populated={populated:?}",
);
// Single-slot diagonal — a well-formed parent from single_slot
// is ALWAYS at least one populated.
assert!(
has_any,
"TaggedUnion::has_any_populated_kind() on single_slot({populated:?}) must equal true",
);
}
}
/// Generic at-least-one-missing-cardinality Boolean testkit — pins
/// that [`TaggedUnion::has_any_missing_kind`] agrees with its
/// definitional complement [`TaggedUnion::is_saturated`] AND with the
/// scalar complement cardinality primitive's strict-inequality-to-zero
/// across every [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL)
/// single-slot arrangement AND the empty-parent baseline.
///
/// Parent-axis substrate primitive for the Boolean at-least-one
/// halfspace projection on the tagged-union closed-set-COMPLEMENT axis
/// — the `bool`-valued definitional complement of
/// [`assert_is_saturated_matches_missing_kind_count`]'s zero-endpoint
/// Boolean projection, and the SUBSET peer of the zero-arm Boolean on
/// the missing cardinality lattice. Byte-for-byte symmetrical with
/// [`assert_has_any_populated_kind_matches_populated_kind_count`]
/// under the (populated, missing) complement axis.
///
/// The four sub-assertions swept per populated slot + the ONE baseline
/// sub-assertion on the empty parent:
///
/// 1. **Definitional complement law**: `has_any_missing_kind() ==
/// !is_saturated()` — the SUBSET Boolean is the bit-flip of the
/// zero-endpoint Boolean on every arm. Byte-identical to the trait's
/// default body (via De Morgan: `any(|k| !has(k)) == !all(|k|
/// has(k))`), pinning the pair substrate-wide.
/// 2. **Cardinality composition law**: `has_any_missing_kind() ==
/// (missing_kind_count() > 0)` — the ≥ 1 halfspace agrees with the
/// scalar complement cardinality's strict-inequality-to-zero on
/// every arm.
/// 3. **Widened-primitive agreement**: `has_any_missing_kind() ==
/// !missing_kinds().is_empty()` — the two at-least-one projections
/// of the missing cardinality coincide byte-identically.
/// 4. **Single-slot diagonal** (on `ALL.len() ≥ 2` closed sets):
/// `single_slot(k).has_any_missing_kind() == true` — a well-formed
/// parent from `single_slot` populates exactly one slot, leaving at
/// least one slot missing (`ALL.len() - 1 ≥ 1`), so the ≥ 1 missing
/// halfspace returns `true` on every real-world tagged union in
/// this workspace.
/// 5. **Empty-parent baseline** (swept once outside the per-`k` loop):
/// `empty_parent().has_any_missing_kind() == true` (empty has EVERY
/// slot missing on any `N ≥ 1`, so ≥ 1 missing). Pins the
/// primitive's non-saturated arm on the same fixture the zero-
/// endpoint peer pins its opposite arm.
///
/// Same `Lifetime` exclusion as the sibling primitives.
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs. The
/// Boolean at-least-one halfspace projection on the missing axis
/// binds through the SAME shape
/// [`assert_is_saturated_matches_missing_kind_count`] binds through
/// (a closed-set walk under `Self::has`), pinned as the
/// definitional-complement law at ONE substrate site inside the
/// testkit's per-arm sweep — the trait's default body composes
/// `any(|k| !has(k))` which is De-Morgan-equivalent to
/// `!all(|k| has(k))`, the exact expression `is_saturated()`
/// negates.
/// - THEORY.md §VI.1 — generation over composition. A new
/// [`Self::Kind`] variant added to `ALL` reaches this primitive
/// mechanically through the `any` short-circuit at the trait's
/// default body.
#[track_caller]
pub fn assert_has_any_missing_kind_matches_missing_kind_count<T, F, G>(
single_slot: F,
empty_parent: G,
) where
T: TaggedUnion,
T::Kind: PartialEq + std::fmt::Debug,
F: Fn(T::Kind) -> T,
G: Fn() -> T,
{
// Empty-parent baseline — the empty parent has EVERY slot missing,
// so `has_any_missing_kind()` returns `true` (the opposite endpoint
// of where `is_saturated()` returns `true`).
let empty = empty_parent();
assert!(
empty.has_any_missing_kind(),
"TaggedUnion::has_any_missing_kind() on empty_parent() must equal true — every slot is missing",
);
assert_eq!(
empty.has_any_missing_kind(),
!empty.is_saturated(),
"empty_parent().has_any_missing_kind() drifted from !is_saturated()",
);
assert_eq!(
empty.has_any_missing_kind(),
empty.missing_kind_count() > 0,
"empty_parent().has_any_missing_kind() drifted from (missing_kind_count() > 0)",
);
assert_eq!(
empty.has_any_missing_kind(),
!empty.missing_kinds().is_empty(),
"empty_parent().has_any_missing_kind() drifted from !missing_kinds().is_empty()",
);
for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let parent = single_slot(populated);
let has_any = parent.has_any_missing_kind();
// Definitional complement law — SUBSET Boolean is the bit-flip
// of the zero-endpoint Boolean.
assert_eq!(
has_any,
!parent.is_saturated(),
"TaggedUnion::has_any_missing_kind() drifted from !is_saturated() — populated={populated:?}",
);
// Cardinality composition law — ≥ 1 halfspace agrees with
// scalar complement cardinality's strict-inequality-to-zero.
assert_eq!(
has_any,
parent.missing_kind_count() > 0,
"TaggedUnion::has_any_missing_kind() drifted from (missing_kind_count() > 0) — populated={populated:?}",
);
// Widened-primitive agreement — the two at-least-one projections
// of the missing cardinality coincide.
assert_eq!(
has_any,
!parent.missing_kinds().is_empty(),
"TaggedUnion::has_any_missing_kind() drifted from !missing_kinds().is_empty() — populated={populated:?}",
);
// Single-slot diagonal (on any `ALL.len() ≥ 2` closed set) — a
// well-formed parent leaves `ALL.len() - 1 ≥ 1` missing, so
// ≥ 1 missing halfspace holds. Every production tagged union
// in the workspace has `ALL.len() ≥ 2`.
assert!(
has_any,
"TaggedUnion::has_any_missing_kind() on single_slot({populated:?}) must equal true — ALL.len() >= 2",
);
}
}
/// Generic one-populated-cardinality Boolean testkit — pins that
/// [`TaggedUnion::has_unique_populated_kind`] agrees with the scalar
/// cardinality primitive's equality-to-one across every
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
/// arrangement AND the empty-parent baseline.
///
/// Parent-axis substrate primitive for the Boolean cardinality-mid-
/// endpoint scalar projection of the tagged-union closed-set-inversion
/// axis under a one-arm equality — the `bool`-valued one-endpoint peer
/// of [`assert_populated_kind_count_matches_populated_kinds`]'s scalar
/// cardinality projection. Together with [`assert_is_empty_matches_populated_kind_count`]
/// and [`assert_is_saturated_matches_missing_kind_count`] this closes
/// the substrate's 2×2 Boolean-endpoint sweep on the tagged-union
/// parent axis. The three sub-assertions swept per populated slot +
/// the ONE baseline sub-assertion on the empty parent:
///
/// 1. **Cardinality composition law**: `has_unique_populated_kind() ==
/// (populated_kind_count() == 1)` — the Boolean projection agrees
/// with the scalar cardinality's one-arm equality on every empty /
/// well-formed / partial / saturated arm. Byte-identical to the
/// trait's default body composed with `unique_populated_kind`,
/// pinning it substrate-wide so a regression that overrides
/// `has_unique_populated_kind` to skip the sweep or return the
/// wrong Boolean fails here.
/// 2. **Unique-primitive agreement**: `has_unique_populated_kind() ==
/// unique_populated_kind().is_some()` — the trait's default body,
/// pinned explicitly so a regression on the `unique_*` primitive
/// or on the Boolean projection's `is_some` collapse surfaces at
/// ONE assertion.
/// 3. **Single-slot diagonal**: `single_slot(k).has_unique_populated_kind()
/// == true` — a well-formed parent from `single_slot` populates
/// exactly one slot, so the one-arm Boolean returns `true`. Pins
/// that the primitive doesn't drift off the well-formed arm.
/// 4. **Empty-parent baseline** (swept once outside the per-`k` loop):
/// `empty_parent().has_unique_populated_kind() == false` (zero
/// populated, not one). Pins the primitive's opposite-arm on the
/// same fixture the zero-endpoint peer pins its zero-arm.
///
/// A fifth sibling tagged-union parent picks up the one-cardinality-
/// Boolean check through ONE `impl TaggedUnion for X` block plus ONE
/// per-site `single_slot_X` factory plus ONE per-site `empty_X` factory
/// plus ONE call site — no re-authored `has_unique_populated_kind`
/// sweep at the test surface.
///
/// Same `Lifetime` exclusion as the sibling primitives — see
/// [`assert_two_slots_ambiguous`].
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs. The
/// Boolean one-endpoint projection binds through the SAME shape
/// the scalar cardinality binds through (a closed-set walk under
/// `Self::has` composed with a two-step short-circuit), differing
/// only in the return-type collapse (`bool` vs. `usize`) and the
/// equality gate (`is_some` vs. `== 1`).
/// - THEORY.md §VI.1 — generation over composition. A new
/// [`Self::Kind`] variant added to `ALL` reaches this primitive
/// mechanically through the `unique_populated_kind` two-step short-
/// circuit at the trait's default body.
#[track_caller]
pub fn assert_has_unique_populated_kind_matches_populated_kind_count<T, F, G>(
single_slot: F,
empty_parent: G,
) where
T: TaggedUnion,
T::Kind: PartialEq + std::fmt::Debug,
F: Fn(T::Kind) -> T,
G: Fn() -> T,
{
// Empty-parent baseline — the empty parent has ZERO populated
// slots, so `has_unique_populated_kind()` returns `false` (the
// opposite endpoint of where a single-slot parent returns `true`).
let empty = empty_parent();
assert!(
!empty.has_unique_populated_kind(),
"TaggedUnion::has_unique_populated_kind() on empty_parent() must equal false",
);
assert_eq!(
empty.has_unique_populated_kind(),
empty.populated_kind_count() == 1,
"empty_parent().has_unique_populated_kind() drifted from (populated_kind_count() == 1)",
);
assert_eq!(
empty.has_unique_populated_kind(),
empty.unique_populated_kind().is_some(),
"empty_parent().has_unique_populated_kind() drifted from unique_populated_kind().is_some()",
);
for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let parent = single_slot(populated);
let has_unique = parent.has_unique_populated_kind();
// Cardinality composition law — Boolean projection agrees with
// the scalar cardinality's one-arm equality.
assert_eq!(
has_unique,
parent.populated_kind_count() == 1,
"TaggedUnion::has_unique_populated_kind() drifted from (populated_kind_count() == 1) — populated={populated:?}",
);
// Unique-primitive agreement — the Boolean is the `is_some`
// projection of the Option-valued unique primitive.
assert_eq!(
has_unique,
parent.unique_populated_kind().is_some(),
"TaggedUnion::has_unique_populated_kind() drifted from unique_populated_kind().is_some() — populated={populated:?}",
);
// Single-slot diagonal — a well-formed parent from single_slot
// has exactly one populated slot, so the one-arm Boolean is
// `true`.
assert!(
has_unique,
"TaggedUnion::has_unique_populated_kind() on single_slot({populated:?}) must equal true",
);
}
}
/// Generic one-missing-cardinality Boolean testkit — pins that
/// [`TaggedUnion::has_unique_missing_kind`] agrees with the scalar
/// complement cardinality primitive's equality-to-one across every
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
/// arrangement AND the empty-parent baseline.
///
/// Parent-axis substrate primitive for the Boolean cardinality-mid-
/// endpoint scalar projection of the tagged-union closed-set-COMPLEMENT
/// axis under a one-arm equality — the `bool`-valued one-endpoint peer
/// of [`assert_missing_kind_count_matches_missing_kinds`]'s scalar
/// complement cardinality projection. Byte-for-byte symmetrical with
/// [`assert_has_unique_populated_kind_matches_populated_kind_count`]
/// under the (populated, missing) complement axis. The three
/// sub-assertions swept per populated slot + the baseline sub-assertion
/// on the empty parent:
///
/// 1. **Cardinality composition law**: `has_unique_missing_kind() ==
/// (missing_kind_count() == 1)` — the Boolean projection agrees
/// with the scalar complement cardinality's one-arm equality on
/// every empty / well-formed / partial / saturated arm.
/// 2. **Unique-primitive agreement**: `has_unique_missing_kind() ==
/// unique_missing_kind().is_some()` — the trait's default body,
/// pinned explicitly.
/// 3. **Single-slot diagonal on `ALL.len() ≥ 3` closed sets**:
/// `single_slot(k).has_unique_missing_kind() == false` — a well-
/// formed parent leaves `ALL.len() - 1 ≥ 2` missing on any
/// `ALL.len() ≥ 3` closed set, so the one-arm Boolean returns
/// `false`. On the degenerate `ALL.len() == 2` closed set (e.g.
/// `Lifetime`, which this testkit excludes through the `TaggedUnion`
/// bound) well-formed and one-missing coincide; on every
/// production tagged union in the workspace (`ALL.len() ≥ 3`) the
/// diagonal returns `false`.
/// 4. **Empty-parent baseline**: `empty_parent().has_unique_missing_kind()
/// == false` (empty has EVERY slot missing, `ALL.len() ≥ 2` on
/// every production union, so never exactly one).
///
/// A fifth sibling tagged-union parent picks up the one-complement-
/// cardinality-Boolean check through ONE `impl TaggedUnion for X`
/// block plus ONE per-site `single_slot_X` factory plus ONE per-site
/// `empty_X` factory plus ONE call site — no re-authored
/// `has_unique_missing_kind` sweep at the test surface.
///
/// Same `Lifetime` exclusion as the sibling primitives.
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
/// - THEORY.md §VI.1 — generation over composition.
#[track_caller]
pub fn assert_has_unique_missing_kind_matches_missing_kind_count<T, F, G>(
single_slot: F,
empty_parent: G,
) where
T: TaggedUnion,
T::Kind: PartialEq + std::fmt::Debug,
F: Fn(T::Kind) -> T,
G: Fn() -> T,
{
// Empty-parent baseline — the empty parent has ALL.len() missing
// slots, so `has_unique_missing_kind()` returns `false` on any
// ALL.len() >= 2 closed set (every production union).
let empty = empty_parent();
assert!(
!empty.has_unique_missing_kind(),
"TaggedUnion::has_unique_missing_kind() on empty_parent() must equal false — ALL.len() >= 2 missing",
);
assert_eq!(
empty.has_unique_missing_kind(),
empty.missing_kind_count() == 1,
"empty_parent().has_unique_missing_kind() drifted from (missing_kind_count() == 1)",
);
assert_eq!(
empty.has_unique_missing_kind(),
empty.unique_missing_kind().is_some(),
"empty_parent().has_unique_missing_kind() drifted from unique_missing_kind().is_some()",
);
let all_len = <T::Kind as tatara_closed_set::ClosedSet>::ALL.len();
for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let parent = single_slot(populated);
let has_unique = parent.has_unique_missing_kind();
// Cardinality composition law — Boolean projection agrees with
// the scalar complement cardinality's one-arm equality.
assert_eq!(
has_unique,
parent.missing_kind_count() == 1,
"TaggedUnion::has_unique_missing_kind() drifted from (missing_kind_count() == 1) — populated={populated:?}",
);
// Unique-primitive agreement — the Boolean is the `is_some`
// projection of the Option-valued unique primitive.
assert_eq!(
has_unique,
parent.unique_missing_kind().is_some(),
"TaggedUnion::has_unique_missing_kind() drifted from unique_missing_kind().is_some() — populated={populated:?}",
);
// Single-slot diagonal — a well-formed parent has ALL.len() - 1
// missing slots. On ALL.len() == 2 the diagonal returns `true`
// (2 - 1 == 1); on ALL.len() >= 3 it returns `false`.
let expected_diagonal = all_len == 2;
assert_eq!(
has_unique,
expected_diagonal,
"TaggedUnion::has_unique_missing_kind() on single_slot({populated:?}) must equal {expected_diagonal} (ALL.len() == {all_len} → missing == {})",
all_len - 1,
);
}
}
/// Generic ≥2-populated-cardinality Boolean testkit — pins that
/// [`TaggedUnion::has_multiple_populated_kinds`] agrees with the
/// scalar cardinality primitive's `>= 2` inequality across every
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
/// arrangement, every off-diagonal two-slot pair, AND the empty-
/// parent baseline.
///
/// Parent-axis substrate primitive for the Boolean cardinality many-
/// arm scalar projection of the tagged-union closed-set-inversion
/// axis under a `>= 2` inequality — third arm of the {0, 1, ≥2}
/// cardinality trichotomy on the populated axis, byte-for-byte peer
/// of [`assert_is_empty_matches_populated_kind_count`] (zero-arm) and
/// [`assert_has_unique_populated_kind_matches_populated_kind_count`]
/// (one-arm). The primitives partition every tagged-union state — on
/// any parent EXACTLY ONE of `is_empty()`,
/// `has_unique_populated_kind()`, `has_multiple_populated_kinds()`
/// returns `true`, closing the trichotomy at the trait's default
/// bodies. The four sub-assertions swept per populated slot + the
/// baseline sub-assertions + the two-slot sweep:
///
/// 1. **Cardinality composition law**: `has_multiple_populated_kinds()
/// == (populated_kind_count() >= 2)` on every empty / well-formed
/// / two-slot / saturated arm.
/// 2. **Trichotomy partition law**: EXACTLY ONE of `is_empty()`,
/// `has_unique_populated_kind()`, `has_multiple_populated_kinds()`
/// returns `true` on every arm swept — pinned as
/// `usize::from(is_empty()) + usize::from(has_unique_populated_kind())
/// + usize::from(has_multiple_populated_kinds()) == 1`.
/// 3. **Empty-parent baseline**: `empty_parent().has_multiple_populated_kinds()
/// == false` (zero populated, not many).
/// 4. **Single-slot diagonal**:
/// `single_slot(k).has_multiple_populated_kinds() == false` on
/// every `k` in `ClosedSet::ALL` (one populated, not many).
/// 5. **Two-slot diagonal**: for every off-diagonal `(a, b)` pair,
/// `two_slot(a, b).has_multiple_populated_kinds() == true` (two
/// populated, definitively many).
///
/// A fifth sibling tagged-union parent picks up the many-cardinality
/// Boolean check through ONE `impl TaggedUnion for X` block plus ONE
/// per-site `single_slot_X` factory plus ONE per-site `two_slot_X`
/// factory plus ONE per-site `empty_X` factory plus ONE call site.
///
/// Same [`crate::lifetime::Lifetime`] exclusion as the sibling
/// primitives — `Lifetime` doesn't impl [`TaggedUnion`].
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
/// - THEORY.md §VI.1 — generation over composition.
#[track_caller]
pub fn assert_has_multiple_populated_kinds_matches_populated_kind_count<T, F, G, H>(
single_slot: F,
two_slot: G,
empty_parent: H,
) where
T: TaggedUnion,
T::Kind: PartialEq + std::fmt::Debug,
F: Fn(T::Kind) -> T,
G: Fn(T::Kind, T::Kind) -> T,
H: Fn() -> T,
{
// Empty-parent baseline — zero populated slots, so
// `has_multiple_populated_kinds()` returns `false`.
let empty = empty_parent();
assert!(
!empty.has_multiple_populated_kinds(),
"TaggedUnion::has_multiple_populated_kinds() on empty_parent() must equal false",
);
assert_eq!(
empty.has_multiple_populated_kinds(),
empty.populated_kind_count() >= 2,
"empty_parent().has_multiple_populated_kinds() drifted from (populated_kind_count() >= 2)",
);
// Trichotomy partition on the empty arm — is_empty is true, the
// other two are false.
assert_eq!(
usize::from(empty.is_empty())
+ usize::from(empty.has_unique_populated_kind())
+ usize::from(empty.has_multiple_populated_kinds()),
1,
"empty_parent() must satisfy EXACTLY ONE of is_empty / has_unique_populated_kind / has_multiple_populated_kinds",
);
for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let parent = single_slot(populated);
let has_multiple = parent.has_multiple_populated_kinds();
// Cardinality composition law.
assert_eq!(
has_multiple,
parent.populated_kind_count() >= 2,
"TaggedUnion::has_multiple_populated_kinds() drifted from (populated_kind_count() >= 2) — populated={populated:?}",
);
// Single-slot diagonal — one populated, not many.
assert!(
!has_multiple,
"TaggedUnion::has_multiple_populated_kinds() on single_slot({populated:?}) must equal false",
);
// Trichotomy partition on the well-formed arm —
// has_unique_populated_kind is true, the other two are false.
assert_eq!(
usize::from(parent.is_empty())
+ usize::from(parent.has_unique_populated_kind())
+ usize::from(has_multiple),
1,
"single_slot({populated:?}) must satisfy EXACTLY ONE of is_empty / has_unique_populated_kind / has_multiple_populated_kinds",
);
}
// Two-slot sweep — every off-diagonal pair has ≥ 2 populated.
for a in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
for b in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
if a == b {
continue;
}
let parent = two_slot(a, b);
let has_multiple = parent.has_multiple_populated_kinds();
assert!(
has_multiple,
"TaggedUnion::has_multiple_populated_kinds() on two_slot({a:?}, {b:?}) must equal true",
);
assert_eq!(
has_multiple,
parent.populated_kind_count() >= 2,
"TaggedUnion::has_multiple_populated_kinds() drifted from (populated_kind_count() >= 2) — pair=({a:?}, {b:?})",
);
// Trichotomy partition on the two-slot arm —
// has_multiple_populated_kinds is true, the other two
// are false.
assert_eq!(
usize::from(parent.is_empty())
+ usize::from(parent.has_unique_populated_kind())
+ usize::from(has_multiple),
1,
"two_slot({a:?}, {b:?}) must satisfy EXACTLY ONE of is_empty / has_unique_populated_kind / has_multiple_populated_kinds",
);
}
}
}
/// Generic ≥2-missing-cardinality Boolean testkit — pins that
/// [`TaggedUnion::has_multiple_missing_kinds`] agrees with the scalar
/// complement cardinality primitive's `>= 2` inequality across every
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
/// arrangement, every off-diagonal two-slot pair, AND the empty-
/// parent baseline.
///
/// Byte-for-byte peer of
/// [`assert_has_multiple_populated_kinds_matches_populated_kind_count`]
/// under the (populated, missing) complement axis. Third arm of the
/// {0, 1, ≥2} cardinality trichotomy on the missing axis, closing the
/// natural partition alongside
/// [`assert_is_saturated_matches_missing_kind_count`] (zero-arm) and
/// [`assert_has_unique_missing_kind_matches_missing_kind_count`]
/// (one-arm). Same trichotomy partition law:
/// `is_saturated() + has_unique_missing_kind() +
/// has_multiple_missing_kinds() == 1` on every arm.
///
/// The single-slot diagonal expectation depends on `ALL.len()`:
///
/// - `ALL.len() == 2`: well-formed has 1 missing, so
/// `has_multiple_missing_kinds() == false` (production `Lifetime`
/// is excluded via the `TaggedUnion` bound anyway).
/// - `ALL.len() >= 3`: well-formed has `ALL.len() - 1 >= 2` missing,
/// so `has_multiple_missing_kinds() == true`.
///
/// The two-slot diagonal expectation similarly depends:
///
/// - `ALL.len() == 3`: two_slot has `3 - 2 == 1` missing → `false`.
/// - `ALL.len() >= 4`: two_slot has `ALL.len() - 2 >= 2` missing →
/// `true`.
///
/// A fifth sibling tagged-union parent picks up the many-complement-
/// cardinality Boolean check through ONE `impl TaggedUnion for X`
/// block plus ONE per-site `single_slot_X` factory plus ONE per-site
/// `two_slot_X` factory plus ONE per-site `empty_X` factory plus ONE
/// call site.
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
/// - THEORY.md §VI.1 — generation over composition.
#[track_caller]
pub fn assert_has_multiple_missing_kinds_matches_missing_kind_count<T, F, G, H>(
single_slot: F,
two_slot: G,
empty_parent: H,
) where
T: TaggedUnion,
T::Kind: PartialEq + std::fmt::Debug,
F: Fn(T::Kind) -> T,
G: Fn(T::Kind, T::Kind) -> T,
H: Fn() -> T,
{
let all_len = <T::Kind as tatara_closed_set::ClosedSet>::ALL.len();
// Empty-parent baseline — ALL.len() missing slots, so
// `has_multiple_missing_kinds()` returns `true` on any
// ALL.len() >= 2 closed set.
let empty = empty_parent();
let empty_expected = all_len >= 2;
assert_eq!(
empty.has_multiple_missing_kinds(),
empty_expected,
"TaggedUnion::has_multiple_missing_kinds() on empty_parent() must equal {empty_expected} (ALL.len() == {all_len})",
);
assert_eq!(
empty.has_multiple_missing_kinds(),
empty.missing_kind_count() >= 2,
"empty_parent().has_multiple_missing_kinds() drifted from (missing_kind_count() >= 2)",
);
// Trichotomy partition on the empty arm — has_multiple_missing_kinds
// is true (ALL.len() >= 2), is_saturated + has_unique_missing_kind
// are false.
assert_eq!(
usize::from(empty.is_saturated())
+ usize::from(empty.has_unique_missing_kind())
+ usize::from(empty.has_multiple_missing_kinds()),
1,
"empty_parent() must satisfy EXACTLY ONE of is_saturated / has_unique_missing_kind / has_multiple_missing_kinds",
);
for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let parent = single_slot(populated);
let has_multiple = parent.has_multiple_missing_kinds();
// Cardinality composition law.
assert_eq!(
has_multiple,
parent.missing_kind_count() >= 2,
"TaggedUnion::has_multiple_missing_kinds() drifted from (missing_kind_count() >= 2) — populated={populated:?}",
);
// Single-slot diagonal — well-formed has ALL.len() - 1
// missing. `>= 2` iff `ALL.len() >= 3`.
let expected_diagonal = all_len >= 3;
assert_eq!(
has_multiple,
expected_diagonal,
"TaggedUnion::has_multiple_missing_kinds() on single_slot({populated:?}) must equal {expected_diagonal} (ALL.len() == {all_len} → missing == {})",
all_len - 1,
);
// Trichotomy partition on the well-formed arm.
assert_eq!(
usize::from(parent.is_saturated())
+ usize::from(parent.has_unique_missing_kind())
+ usize::from(has_multiple),
1,
"single_slot({populated:?}) must satisfy EXACTLY ONE of is_saturated / has_unique_missing_kind / has_multiple_missing_kinds",
);
}
// Two-slot sweep — every off-diagonal pair has ALL.len() - 2
// missing.
for a in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
for b in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
if a == b {
continue;
}
let parent = two_slot(a, b);
let has_multiple = parent.has_multiple_missing_kinds();
let expected_two_slot = all_len >= 4;
assert_eq!(
has_multiple,
expected_two_slot,
"TaggedUnion::has_multiple_missing_kinds() on two_slot({a:?}, {b:?}) must equal {expected_two_slot} (ALL.len() == {all_len} → missing == {})",
all_len - 2,
);
assert_eq!(
has_multiple,
parent.missing_kind_count() >= 2,
"TaggedUnion::has_multiple_missing_kinds() drifted from (missing_kind_count() >= 2) — pair=({a:?}, {b:?})",
);
// Trichotomy partition on the two-slot arm.
assert_eq!(
usize::from(parent.is_saturated())
+ usize::from(parent.has_unique_missing_kind())
+ usize::from(has_multiple),
1,
"two_slot({a:?}, {b:?}) must satisfy EXACTLY ONE of is_saturated / has_unique_missing_kind / has_multiple_missing_kinds",
);
}
}
}
/// Generic ≤1-populated-cardinality Boolean testkit — pins that
/// [`TaggedUnion::has_at_most_one_populated_kind`] agrees with all
/// THREE of its composition laws across every
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
/// arrangement, every off-diagonal two-slot pair, AND the empty-parent
/// baseline.
///
/// Boolean-negation peer of
/// [`assert_has_multiple_populated_kinds_matches_populated_kind_count`]
/// under `!(≥ 2) == (≤ 1)` — closes the `{≥ 2, ≤ 1}` Boolean-negation
/// pair on the populated cardinality axis. The three composition laws
/// swept per arm:
///
/// 1. **Definitional Boolean-negation law**:
/// `has_at_most_one_populated_kind() == !has_multiple_populated_kinds()`
/// — the trait's default body binds the two forms as one bit-flip
/// over the SAME two-step-short-circuit closed-set walk.
/// 2. **Scalar cardinality composition law**:
/// `has_at_most_one_populated_kind() == (populated_kind_count() <= 1)`
/// — the Boolean projection agrees with the scalar count's `<= 1`
/// inequality.
/// 3. **Trichotomy union composition law**:
/// `has_at_most_one_populated_kind() == is_empty() || has_unique_populated_kind()`
/// — the union of the zero-arm and the one-arm of the
/// {0, 1, ≥ 2} cardinality trichotomy.
///
/// The three arm expectations:
///
/// - **Empty-parent baseline**: `has_at_most_one_populated_kind() ==
/// true` (0 ≤ 1).
/// - **Single-slot diagonal**: `has_at_most_one_populated_kind() ==
/// true` (1 ≤ 1) — the SOLE `Ok` arm of [`TaggedUnion::variant`]
/// lies inside the at-most-one region.
/// - **Two-slot sweep**: `has_at_most_one_populated_kind() == false`
/// (2 > 1) — the AMBIGUOUS arm sits outside the at-most-one region.
///
/// A fifth sibling tagged-union parent picks up the ≤1-populated-
/// cardinality Boolean check through ONE `impl TaggedUnion for X`
/// block plus ONE per-site `single_slot_X` factory plus ONE per-site
/// `two_slot_X` factory plus ONE per-site `empty_X` factory plus ONE
/// call site — no re-authored per-site sweep.
///
/// Same [`crate::lifetime::Lifetime`] exclusion as the sibling
/// primitives — `Lifetime` doesn't impl [`TaggedUnion`].
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs. The
/// three composition laws bind the ≤1-populated Boolean projection
/// to the widened `!has_multiple_populated_kinds`, the scalar
/// `populated_kind_count <= 1`, and the union of zero-arm ∪ one-arm
/// at ONE substrate site each — swept across every production
/// tagged union at the testkit's per-arm sweep, not per-parent.
/// - THEORY.md §VI.1 — generation over composition. A new
/// [`Self::Kind`] variant added to `ALL` reaches the primitive
/// mechanically through the delegated
/// [`TaggedUnion::has_multiple_populated_kinds`].
#[track_caller]
pub fn assert_has_at_most_one_populated_kind_matches_populated_kind_count<T, F, G, H>(
single_slot: F,
two_slot: G,
empty_parent: H,
) where
T: TaggedUnion,
T::Kind: PartialEq + std::fmt::Debug,
F: Fn(T::Kind) -> T,
G: Fn(T::Kind, T::Kind) -> T,
H: Fn() -> T,
{
// Empty-parent baseline — zero populated slots, so
// `has_at_most_one_populated_kind()` returns `true` (0 <= 1).
let empty = empty_parent();
assert!(
empty.has_at_most_one_populated_kind(),
"TaggedUnion::has_at_most_one_populated_kind() on empty_parent() must equal true",
);
// Definitional Boolean-negation composition law on the empty arm.
assert_eq!(
empty.has_at_most_one_populated_kind(),
!empty.has_multiple_populated_kinds(),
"empty_parent().has_at_most_one_populated_kind() drifted from !has_multiple_populated_kinds()",
);
// Scalar cardinality composition law on the empty arm.
assert_eq!(
empty.has_at_most_one_populated_kind(),
empty.populated_kind_count() <= 1,
"empty_parent().has_at_most_one_populated_kind() drifted from (populated_kind_count() <= 1)",
);
// Trichotomy union composition law on the empty arm.
assert_eq!(
empty.has_at_most_one_populated_kind(),
empty.is_empty() || empty.has_unique_populated_kind(),
"empty_parent().has_at_most_one_populated_kind() drifted from (is_empty() || has_unique_populated_kind())",
);
for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let parent = single_slot(populated);
let has_at_most_one = parent.has_at_most_one_populated_kind();
// Single-slot diagonal — one populated (1 <= 1).
assert!(
has_at_most_one,
"TaggedUnion::has_at_most_one_populated_kind() on single_slot({populated:?}) must equal true",
);
// Definitional Boolean-negation composition law.
assert_eq!(
has_at_most_one,
!parent.has_multiple_populated_kinds(),
"TaggedUnion::has_at_most_one_populated_kind() drifted from !has_multiple_populated_kinds() — populated={populated:?}",
);
// Scalar cardinality composition law.
assert_eq!(
has_at_most_one,
parent.populated_kind_count() <= 1,
"TaggedUnion::has_at_most_one_populated_kind() drifted from (populated_kind_count() <= 1) — populated={populated:?}",
);
// Trichotomy union composition law.
assert_eq!(
has_at_most_one,
parent.is_empty() || parent.has_unique_populated_kind(),
"TaggedUnion::has_at_most_one_populated_kind() drifted from (is_empty() || has_unique_populated_kind()) — populated={populated:?}",
);
}
// Two-slot sweep — every off-diagonal pair has 2 populated (> 1).
for a in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
for b in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
if a == b {
continue;
}
let parent = two_slot(a, b);
let has_at_most_one = parent.has_at_most_one_populated_kind();
assert!(
!has_at_most_one,
"TaggedUnion::has_at_most_one_populated_kind() on two_slot({a:?}, {b:?}) must equal false",
);
// Definitional Boolean-negation composition law.
assert_eq!(
has_at_most_one,
!parent.has_multiple_populated_kinds(),
"TaggedUnion::has_at_most_one_populated_kind() drifted from !has_multiple_populated_kinds() — pair=({a:?}, {b:?})",
);
// Scalar cardinality composition law.
assert_eq!(
has_at_most_one,
parent.populated_kind_count() <= 1,
"TaggedUnion::has_at_most_one_populated_kind() drifted from (populated_kind_count() <= 1) — pair=({a:?}, {b:?})",
);
// Trichotomy union composition law.
assert_eq!(
has_at_most_one,
parent.is_empty() || parent.has_unique_populated_kind(),
"TaggedUnion::has_at_most_one_populated_kind() drifted from (is_empty() || has_unique_populated_kind()) — pair=({a:?}, {b:?})",
);
}
}
}
/// Generic ≤1-missing-cardinality Boolean testkit — pins that
/// [`TaggedUnion::has_at_most_one_missing_kind`] agrees with all THREE
/// of its composition laws across every
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
/// arrangement, every off-diagonal two-slot pair, AND the empty-parent
/// baseline.
///
/// Byte-for-byte peer of
/// [`assert_has_at_most_one_populated_kind_matches_populated_kind_count`]
/// under the (populated, missing) complement axis, and Boolean-negation
/// peer of
/// [`assert_has_multiple_missing_kinds_matches_missing_kind_count`]
/// under `!(≥ 2) == (≤ 1)` — closes the `{≥ 2, ≤ 1}` Boolean-negation
/// pair on the missing cardinality axis. Same three composition laws:
///
/// 1. **Definitional Boolean-negation law**:
/// `has_at_most_one_missing_kind() == !has_multiple_missing_kinds()`.
/// 2. **Scalar complement-cardinality composition law**:
/// `has_at_most_one_missing_kind() == (missing_kind_count() <= 1)`.
/// 3. **Trichotomy union composition law**:
/// `has_at_most_one_missing_kind() == is_saturated() || has_unique_missing_kind()`.
///
/// The three arm expectations depend on `ALL.len()`:
///
/// - **Empty-parent baseline** (on `ALL.len() ≥ 2`):
/// `has_at_most_one_missing_kind() == false` (ALL.len() missing
/// slots, so ≥ 2).
/// - **Single-slot diagonal**: `has_at_most_one_missing_kind() == true`
/// iff `ALL.len() - 1 <= 1`, i.e. `ALL.len() <= 2`. Every production
/// tagged union in this workspace has `ALL.len() ≥ 3`, so the
/// single-slot diagonal returns `false` on every production arm.
/// (Kept general for future 2-variant tagged unions.)
/// - **Two-slot sweep**: `has_at_most_one_missing_kind() == true` iff
/// `ALL.len() - 2 <= 1`, i.e. `ALL.len() <= 3`. On production unions
/// with `ALL.len() == 3` (e.g. two-arm plus one — none currently),
/// two_slot returns `true`; on `ALL.len() >= 4` it returns `false`.
///
/// A fifth sibling tagged-union parent picks up the ≤1-missing-
/// cardinality Boolean check through ONE `impl TaggedUnion for X`
/// block plus ONE per-site `single_slot_X` factory plus ONE per-site
/// `two_slot_X` factory plus ONE per-site `empty_X` factory plus ONE
/// call site.
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
/// - THEORY.md §VI.1 — generation over composition.
#[track_caller]
pub fn assert_has_at_most_one_missing_kind_matches_missing_kind_count<T, F, G, H>(
single_slot: F,
two_slot: G,
empty_parent: H,
) where
T: TaggedUnion,
T::Kind: PartialEq + std::fmt::Debug,
F: Fn(T::Kind) -> T,
G: Fn(T::Kind, T::Kind) -> T,
H: Fn() -> T,
{
let all_len = <T::Kind as tatara_closed_set::ClosedSet>::ALL.len();
// Empty-parent baseline — ALL.len() missing slots, so
// `has_at_most_one_missing_kind()` returns `true` iff ALL.len() <= 1.
let empty = empty_parent();
let empty_expected = all_len <= 1;
assert_eq!(
empty.has_at_most_one_missing_kind(),
empty_expected,
"TaggedUnion::has_at_most_one_missing_kind() on empty_parent() must equal {empty_expected} (ALL.len() == {all_len})",
);
// Definitional Boolean-negation composition law on the empty arm.
assert_eq!(
empty.has_at_most_one_missing_kind(),
!empty.has_multiple_missing_kinds(),
"empty_parent().has_at_most_one_missing_kind() drifted from !has_multiple_missing_kinds()",
);
// Scalar complement-cardinality composition law on the empty arm.
assert_eq!(
empty.has_at_most_one_missing_kind(),
empty.missing_kind_count() <= 1,
"empty_parent().has_at_most_one_missing_kind() drifted from (missing_kind_count() <= 1)",
);
// Trichotomy union composition law on the empty arm.
assert_eq!(
empty.has_at_most_one_missing_kind(),
empty.is_saturated() || empty.has_unique_missing_kind(),
"empty_parent().has_at_most_one_missing_kind() drifted from (is_saturated() || has_unique_missing_kind())",
);
for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let parent = single_slot(populated);
let has_at_most_one = parent.has_at_most_one_missing_kind();
// Single-slot diagonal — well-formed parent has ALL.len() - 1
// missing. `<= 1` iff `ALL.len() <= 2`.
let expected_diagonal = all_len <= 2;
assert_eq!(
has_at_most_one,
expected_diagonal,
"TaggedUnion::has_at_most_one_missing_kind() on single_slot({populated:?}) must equal {expected_diagonal} (ALL.len() == {all_len} → missing == {})",
all_len - 1,
);
// Definitional Boolean-negation composition law.
assert_eq!(
has_at_most_one,
!parent.has_multiple_missing_kinds(),
"TaggedUnion::has_at_most_one_missing_kind() drifted from !has_multiple_missing_kinds() — populated={populated:?}",
);
// Scalar complement-cardinality composition law.
assert_eq!(
has_at_most_one,
parent.missing_kind_count() <= 1,
"TaggedUnion::has_at_most_one_missing_kind() drifted from (missing_kind_count() <= 1) — populated={populated:?}",
);
// Trichotomy union composition law.
assert_eq!(
has_at_most_one,
parent.is_saturated() || parent.has_unique_missing_kind(),
"TaggedUnion::has_at_most_one_missing_kind() drifted from (is_saturated() || has_unique_missing_kind()) — populated={populated:?}",
);
}
// Two-slot sweep — every off-diagonal pair has ALL.len() - 2
// missing. `<= 1` iff `ALL.len() <= 3`.
for a in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
for b in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
if a == b {
continue;
}
let parent = two_slot(a, b);
let has_at_most_one = parent.has_at_most_one_missing_kind();
let expected_two_slot = all_len <= 3;
assert_eq!(
has_at_most_one,
expected_two_slot,
"TaggedUnion::has_at_most_one_missing_kind() on two_slot({a:?}, {b:?}) must equal {expected_two_slot} (ALL.len() == {all_len} → missing == {})",
all_len - 2,
);
// Definitional Boolean-negation composition law.
assert_eq!(
has_at_most_one,
!parent.has_multiple_missing_kinds(),
"TaggedUnion::has_at_most_one_missing_kind() drifted from !has_multiple_missing_kinds() — pair=({a:?}, {b:?})",
);
// Scalar complement-cardinality composition law.
assert_eq!(
has_at_most_one,
parent.missing_kind_count() <= 1,
"TaggedUnion::has_at_most_one_missing_kind() drifted from (missing_kind_count() <= 1) — pair=({a:?}, {b:?})",
);
// Trichotomy union composition law.
assert_eq!(
has_at_most_one,
parent.is_saturated() || parent.has_unique_missing_kind(),
"TaggedUnion::has_at_most_one_missing_kind() drifted from (is_saturated() || has_unique_missing_kind()) — pair=({a:?}, {b:?})",
);
}
}
}
/// Generic parent-state-middle-arm Boolean testkit — pins that
/// [`TaggedUnion::is_partially_populated`] agrees with the paired
/// scalar-cardinality strict-inequality composition
/// `(populated_kind_count() > 0 && missing_kind_count() > 0)` across
/// every [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-
/// slot arrangement, every off-diagonal two-slot pair, AND the empty-
/// parent baseline.
///
/// Parent-state-axis substrate primitive for the Boolean middle-arm
/// projection of the `{Empty | Partial | Saturated}` trichotomy —
/// orthogonal to the {0, 1, ≥2} cardinality trichotomies already
/// closed on the populated / missing axes. The four sub-assertions
/// swept per populated slot + the four baseline sub-assertions on the
/// empty parent + the four sub-assertions swept per off-diagonal pair
/// bind FOUR composition laws per arm:
///
/// 1. **Widened negation-of-both-endpoints composition law**:
/// `is_partially_populated() == !is_empty() && !is_saturated()` —
/// the natural composition that the trait's default body's fused
/// walk collapses into ONE closed-set traversal. Pinned so a
/// regression that overrides `is_partially_populated` to skip the
/// sweep or return the wrong Boolean fails here at the widened
/// negation.
/// 2. **Paired scalar-cardinality composition law**:
/// `is_partially_populated() == (populated_kind_count() > 0 &&
/// missing_kind_count() > 0)` — the Boolean projection agrees with
/// the paired scalar-cardinality strict-inequality composition on
/// every empty / well-formed / partial / saturated arm.
/// 3. **Single-axis open-interval composition law**:
/// `is_partially_populated() == (0 < populated_kind_count() &&
/// populated_kind_count() < ALL.len())` — the Boolean projection
/// agrees with the single-axis strict-inequality composition
/// (populated cardinality lies in the open interval `(0, ALL.len())`).
/// 4. **Parent-state trichotomy partition law**:
/// `usize::from(is_empty()) + usize::from(is_partially_populated()) + usize::from(is_saturated()) == 1`
/// — EXACTLY ONE of the three parent-state Boolean primitives
/// returns `true` on every arm. This is the genuinely new proof
/// this testkit adds: the natural parent-state trichotomy
/// partitions every tagged-union state coherently, and this law
/// lives at ONE substrate site inside the testkit's per-arm sweep,
/// pinned across every production tagged union.
///
/// The three arm expectations:
///
/// - **Empty-parent baseline** (swept once outside the per-`k` loop):
/// `empty_parent().is_partially_populated() == false` (zero
/// populated, so the negation `!is_empty()` fails). Pins the
/// primitive's opposite-arm on the same fixture the empty-Boolean
/// peer pins its zero-arm.
/// - **Single-slot diagonal** (on `ALL.len() ≥ 2` closed sets):
/// `single_slot(k).is_partially_populated() == true` — a well-formed
/// parent from `single_slot` populates exactly one slot (0 <
/// populated < N), so the middle arm returns `true`. Pins the
/// primitive doesn't drift onto either endpoint.
/// - **Two-slot sweep** (on `ALL.len() ≥ 3` closed sets, which every
/// production tagged union in the workspace satisfies):
/// `two_slot(a, b).is_partially_populated() == true` — an
/// off-diagonal pair populates exactly two slots (0 < 2 <= N-1 < N
/// for N ≥ 3), so the middle arm returns `true`. On `ALL.len() ==
/// 2` (production `Lifetime` excluded via the `TaggedUnion` bound)
/// two_slot would be saturated (`false`), but no production tagged
/// union has `ALL.len() == 2`.
///
/// A fifth sibling tagged-union parent picks up the middle-arm-
/// Boolean check through ONE `impl TaggedUnion for X` block plus ONE
/// per-site `single_slot_X` factory plus ONE per-site `two_slot_X`
/// factory plus ONE per-site `empty_X` factory plus ONE call site —
/// no re-authored `is_partially_populated` sweep at the test surface.
///
/// Same `Lifetime` exclusion as the sibling primitives — see
/// [`assert_two_slots_ambiguous`].
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs. The
/// Boolean parent-state middle-arm projection binds through the
/// SAME shape the two endpoint primitives bind through (a closed-
/// set walk under `Self::has`), differing only in the fused
/// short-circuit gate (both flags flipped) versus the endpoint
/// primitives' single-flag `any` / `all` short-circuits. The
/// trichotomy partition law lives at ONE substrate site inside the
/// testkit's per-arm sweep — pinned across every production tagged
/// union at compile time via the trait's default body composition,
/// not per-parent.
/// - THEORY.md §VI.1 — generation over composition. A new
/// [`Self::Kind`] variant added to `ALL` reaches this primitive
/// mechanically through the fused walk at the trait's default body.
#[track_caller]
pub fn assert_is_partially_populated_matches_cardinality<T, F, G, H>(
single_slot: F,
two_slot: G,
empty_parent: H,
) where
T: TaggedUnion,
T::Kind: PartialEq + std::fmt::Debug,
F: Fn(T::Kind) -> T,
G: Fn(T::Kind, T::Kind) -> T,
H: Fn() -> T,
{
let all_len = <T::Kind as tatara_closed_set::ClosedSet>::ALL.len();
// Empty-parent baseline — zero populated slots, so
// `is_partially_populated()` returns `false` (the empty arm of the
// parent-state trichotomy, not the partial arm).
let empty = empty_parent();
// Anchor the baseline factory on the genuine empty arm — a saturated
// factory would also return `false` from `is_partially_populated()`
// (both endpoints of the trichotomy sit on the `false` side of the
// middle-arm), so this explicit `is_empty()` pin distinguishes the
// empty arm from the saturated arm on the baseline.
assert!(
empty.is_empty(),
"TaggedUnion::is_partially_populated() testkit: empty_parent() must satisfy is_empty() == true",
);
assert!(
!empty.is_partially_populated(),
"TaggedUnion::is_partially_populated() on empty_parent() must equal false",
);
// Widened negation-of-both-endpoints composition law on the empty
// arm.
assert_eq!(
empty.is_partially_populated(),
!empty.is_empty() && !empty.is_saturated(),
"empty_parent().is_partially_populated() drifted from (!is_empty() && !is_saturated())",
);
// Paired scalar-cardinality composition law on the empty arm.
assert_eq!(
empty.is_partially_populated(),
empty.populated_kind_count() > 0 && empty.missing_kind_count() > 0,
"empty_parent().is_partially_populated() drifted from (populated_kind_count() > 0 && missing_kind_count() > 0)",
);
// Parent-state trichotomy partition law on the empty arm —
// is_empty is true, the other two are false.
assert_eq!(
usize::from(empty.is_empty())
+ usize::from(empty.is_partially_populated())
+ usize::from(empty.is_saturated()),
1,
"empty_parent() must satisfy EXACTLY ONE of is_empty / is_partially_populated / is_saturated",
);
for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let parent = single_slot(populated);
let is_partial = parent.is_partially_populated();
// Widened negation-of-both-endpoints composition law.
assert_eq!(
is_partial,
!parent.is_empty() && !parent.is_saturated(),
"TaggedUnion::is_partially_populated() drifted from (!is_empty() && !is_saturated()) — populated={populated:?}",
);
// Paired scalar-cardinality composition law.
assert_eq!(
is_partial,
parent.populated_kind_count() > 0 && parent.missing_kind_count() > 0,
"TaggedUnion::is_partially_populated() drifted from (populated_kind_count() > 0 && missing_kind_count() > 0) — populated={populated:?}",
);
// Single-axis open-interval composition law.
assert_eq!(
is_partial,
0 < parent.populated_kind_count() && parent.populated_kind_count() < all_len,
"TaggedUnion::is_partially_populated() drifted from (0 < populated_kind_count() < ALL.len()) — populated={populated:?}",
);
// Single-slot diagonal (on any `ALL.len() ≥ 2` closed set) —
// well-formed has 1 populated + `ALL.len() - 1 ≥ 1` missing,
// so the middle arm returns `true`. This holds for every
// production tagged union in the workspace (all have
// `ALL.len() ≥ 2`).
assert!(
is_partial,
"TaggedUnion::is_partially_populated() on single_slot({populated:?}) must equal true — ALL.len() >= 2",
);
// Parent-state trichotomy partition on the well-formed arm.
assert_eq!(
usize::from(parent.is_empty())
+ usize::from(is_partial)
+ usize::from(parent.is_saturated()),
1,
"single_slot({populated:?}) must satisfy EXACTLY ONE of is_empty / is_partially_populated / is_saturated",
);
}
// Two-slot sweep — every off-diagonal pair has 2 populated
// + `ALL.len() - 2` missing.
for a in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
for b in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
if a == b {
continue;
}
let parent = two_slot(a, b);
let is_partial = parent.is_partially_populated();
// Widened negation-of-both-endpoints composition law.
assert_eq!(
is_partial,
!parent.is_empty() && !parent.is_saturated(),
"TaggedUnion::is_partially_populated() drifted from (!is_empty() && !is_saturated()) — pair=({a:?}, {b:?})",
);
// Paired scalar-cardinality composition law.
assert_eq!(
is_partial,
parent.populated_kind_count() > 0 && parent.missing_kind_count() > 0,
"TaggedUnion::is_partially_populated() drifted from (populated_kind_count() > 0 && missing_kind_count() > 0) — pair=({a:?}, {b:?})",
);
// Two-slot diagonal — on `ALL.len() >= 3` the two-slot
// parent has 2 populated + `ALL.len() - 2 >= 1` missing,
// so the middle arm returns `true`. On `ALL.len() == 2`
// (excluded via the `TaggedUnion` bound anyway) two_slot
// would be saturated (`false`).
let expected_two_slot = all_len >= 3;
assert_eq!(
is_partial,
expected_two_slot,
"TaggedUnion::is_partially_populated() on two_slot({a:?}, {b:?}) must equal {expected_two_slot} (ALL.len() == {all_len})",
);
// Parent-state trichotomy partition on the two-slot arm.
assert_eq!(
usize::from(parent.is_empty())
+ usize::from(is_partial)
+ usize::from(parent.is_saturated()),
1,
"two_slot({a:?}, {b:?}) must satisfy EXACTLY ONE of is_empty / is_partially_populated / is_saturated",
);
}
}
}
/// Generic kind-scoped strict-refinement testkit — pins that
/// [`TaggedUnion::has_only`] agrees with the widened composition
/// `unique_populated_kind() == Some(kind)` across every
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) `× ALL`
/// single-slot (populated, probed) pair, every off-diagonal two-slot
/// pair `× ALL`, AND the empty-parent baseline `× ALL`.
///
/// Kind-scoped-strict-refinement-axis substrate primitive for the
/// argument-taking uniqueness peer of [`TaggedUnion::has`] — the
/// EQUAL predicate to `has`'s SUBSET predicate. FIVE composition laws
/// per arm are pinned per (populated / pair / empty × probed) sub-
/// assertion:
///
/// 1. **Widened uniqueness composition law**:
/// `has_only(kind) == (unique_populated_kind() == Some(kind))` —
/// the canonical composition that the trait's default body's fused
/// walk collapses into ONE short-circuit closed-set traversal.
/// Pinned so a regression that overrides `has_only` to skip the
/// sweep, drop the "no other populated" check, or return the wrong
/// Boolean fails here at the widened uniqueness composition.
/// 2. **Cardinality-refinement composition law**:
/// `has_only(kind) == (has(kind) && has_unique_populated_kind())`
/// — the paired-endpoint composition binding the strict refinement
/// to the arg-less uniqueness predicate. Pinned so a regression
/// that drops the "exactly one populated" check (returning `true`
/// on a multi-populated parent whose SET of populated kinds
/// contains `kind`) is caught here.
/// 3. **Kind-scoped implication law**:
/// `has_only(kind) → has(kind)` — every arm where `has_only`
/// returns `true` must satisfy `has(kind) == true` (the SUBSET
/// predicate must accept every parent the EQUAL predicate
/// accepts). Pinned so a regression that returns `true` on an
/// empty parent or a parent that populates a DIFFERENT kind is
/// caught here.
/// 4. **Kind-domain exhaustivity law**:
/// `<Kind as ClosedSet>::ALL.iter().filter(|k|
/// parent.has_only(*k)).count() ≤ 1` on every arm — a parent
/// satisfies `has_only(k)` for AT MOST one `k`, since two distinct
/// kinds cannot both be the sole populated slot. On the well-
/// formed arm the count is exactly 1 (the addressed kind); on the
/// empty AND multi-populated arms the count is 0. This kind-domain
/// exhaustivity law binds the argument-scoped projection to the
/// arg-less uniqueness predicate at ONE substrate site.
/// 5. **Well-formed diagonal law**:
/// `single_slot(k).has_only(k) == true` on every `k ∈
/// ClosedSet::ALL` — the single-slot factory constructs a well-
/// formed parent, so every `has_only(k)` on the diagonal is
/// `true`. Pinned so a regression that returns `false` on the
/// well-formed arm (e.g. a typo `!self.has(k)` in the trait
/// default) is caught here.
///
/// The three arm expectations:
///
/// - **Empty-parent baseline** (swept `× ALL` outside the per-slot
/// loop): `empty_parent().has_only(k) == false` for every `k` — no
/// populated slot, so no kind is the sole populated kind.
/// - **Single-slot sweep** (swept on `ClosedSet::ALL × ALL`):
/// `single_slot(populated).has_only(kind) == (populated == kind)`
/// — the well-formed truth table.
/// - **Two-slot sweep** (swept on the off-diagonal `× ALL`):
/// `two_slot(a, b).has_only(k) == false` for every `k` — multi-
/// populated parents satisfy `has_only(k)` for NO kind.
///
/// A fifth sibling tagged-union parent picks up the kind-scoped-
/// strict-refinement check through ONE `impl TaggedUnion for X`
/// block plus ONE per-site `single_slot_X` factory plus ONE per-site
/// `two_slot_X` factory plus ONE per-site `empty_X` factory plus ONE
/// call site — no re-authored `has_only` sweep at the test surface.
///
/// Same [`crate::lifetime::Lifetime`] exclusion as the sibling
/// primitives — the `T: TaggedUnion` bound doesn't reach it.
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs. The
/// kind-scoped strict-refinement projection binds through the SAME
/// shape the arg-less uniqueness peer binds through (a closed-set
/// walk under `Self::has`), differing only in the argument-scoped
/// short-circuit gate (first populated slot mismatched → `false`).
/// The kind-domain exhaustivity law
/// `count k where has_only(k) ≤ 1` lives at ONE substrate site
/// inside the testkit's per-arm sweep — pinned across every
/// production tagged union at compile time via the trait's default
/// body composition, not per-parent.
/// - THEORY.md §VI.1 — generation over composition. A new
/// [`Self::Kind`] variant added to `ALL` reaches this primitive
/// mechanically through the fused walk at the trait's default body.
#[track_caller]
pub fn assert_has_only_matches_unique_populated_kind<T, F, G, H>(
single_slot: F,
two_slot: G,
empty_parent: H,
) where
T: TaggedUnion,
T::Kind: PartialEq + std::fmt::Debug,
F: Fn(T::Kind) -> T,
G: Fn(T::Kind, T::Kind) -> T,
H: Fn() -> T,
{
// Empty-parent baseline — every `has_only(k)` returns `false`
// because no slot is populated.
let empty = empty_parent();
assert!(
empty.is_empty(),
"TaggedUnion::has_only() testkit: empty_parent() must satisfy is_empty() == true",
);
for k in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let via_has_only = empty.has_only(k);
assert!(
!via_has_only,
"empty_parent().has_only({k:?}) must equal false",
);
// Widened uniqueness composition law on the empty arm.
assert_eq!(
via_has_only,
empty.unique_populated_kind() == Some(k),
"empty_parent().has_only({k:?}) drifted from (unique_populated_kind() == Some({k:?}))",
);
// Cardinality-refinement composition law on the empty arm.
assert_eq!(
via_has_only,
empty.has(k) && empty.has_unique_populated_kind(),
"empty_parent().has_only({k:?}) drifted from (has({k:?}) && has_unique_populated_kind())",
);
}
// Kind-domain exhaustivity on the empty arm — no kind is the sole
// populated kind, so the count is 0.
let empty_count = <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
.filter(|k| empty.has_only(*k))
.count();
assert_eq!(
empty_count, 0,
"empty_parent(): exactly 0 kinds must satisfy has_only, got {empty_count}",
);
// Single-slot sweep — the well-formed truth table across
// `ClosedSet::ALL × ALL`.
for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let parent = single_slot(populated);
for probed in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let expected = probed == populated;
let via_has_only = parent.has_only(probed);
// Truth table on the well-formed diagonal — `true` iff the
// probed kind equals the populated kind.
assert_eq!(
via_has_only, expected,
"single_slot({populated:?}).has_only({probed:?}) must equal {expected}",
);
// Widened uniqueness composition law.
assert_eq!(
via_has_only,
parent.unique_populated_kind() == Some(probed),
"single_slot({populated:?}).has_only({probed:?}) drifted from (unique_populated_kind() == Some({probed:?}))",
);
// Cardinality-refinement composition law.
assert_eq!(
via_has_only,
parent.has(probed) && parent.has_unique_populated_kind(),
"single_slot({populated:?}).has_only({probed:?}) drifted from (has({probed:?}) && has_unique_populated_kind())",
);
// Kind-scoped implication law — has_only implies has.
if via_has_only {
assert!(
parent.has(probed),
"single_slot({populated:?}).has_only({probed:?}) == true but has({probed:?}) == false",
);
}
}
// Kind-domain exhaustivity on the well-formed arm — exactly 1
// kind (the populated one) satisfies has_only.
let well_formed_count = <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
.filter(|k| parent.has_only(*k))
.count();
assert_eq!(
well_formed_count, 1,
"single_slot({populated:?}): exactly 1 kind must satisfy has_only, got {well_formed_count}",
);
}
// Two-slot sweep — every off-diagonal pair populates two slots, so
// has_only(k) == false for every k, and no kind satisfies has_only
// on the multi-populated arm.
for a in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
for b in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
if a == b {
continue;
}
let parent = two_slot(a, b);
for k in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let via_has_only = parent.has_only(k);
assert!(
!via_has_only,
"two_slot({a:?}, {b:?}).has_only({k:?}) must equal false",
);
// Widened uniqueness composition law on the multi-
// populated arm.
assert_eq!(
via_has_only,
parent.unique_populated_kind() == Some(k),
"two_slot({a:?}, {b:?}).has_only({k:?}) drifted from (unique_populated_kind() == Some({k:?}))",
);
// Cardinality-refinement composition law.
assert_eq!(
via_has_only,
parent.has(k) && parent.has_unique_populated_kind(),
"two_slot({a:?}, {b:?}).has_only({k:?}) drifted from (has({k:?}) && has_unique_populated_kind())",
);
}
// Kind-domain exhaustivity on the multi-populated arm — no
// kind is the sole populated kind.
let multi_count = <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
.filter(|k| parent.has_only(*k))
.count();
assert_eq!(
multi_count, 0,
"two_slot({a:?}, {b:?}): exactly 0 kinds must satisfy has_only, got {multi_count}",
);
}
}
}
/// Generic kind-scoped strict-refinement testkit on the MISSING axis —
/// pins that [`TaggedUnion::lacks_only`] agrees with
/// [`TaggedUnion::unique_missing_kind`]'s
/// argument-scoped projection, [`TaggedUnion::has`]'s negated
/// cardinality-refinement, AND the kind-scoped implication
/// `lacks_only(kind) → !has(kind)` across every
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
/// arrangement, every off-diagonal two-slot pair, AND the empty-parent
/// baseline.
///
/// Closed-set-complement mirror of
/// [`assert_has_only_matches_unique_populated_kind`] under the
/// (populated, missing) duality — where the populated-axis primitive
/// binds `has_only(kind)` to `unique_populated_kind()`, this primitive
/// binds `lacks_only(kind)` to `unique_missing_kind()` through the
/// same shape (a closed-set walk under `Self::has`, differing only in
/// the negation of the presence probe). The four sub-assertions swept
/// per single-slot arrangement + the two-slot sweep + the empty-parent
/// baseline:
///
/// 1. **Widened uniqueness composition law**:
/// `lacks_only(kind) == (unique_missing_kind() == Some(kind))` on
/// every arm — the fused walk's argument-scoped projection agrees
/// with the arg-less unique-missing primitive's `Option::eq` on
/// `Some(kind)`. Byte-for-byte peer of
/// [`assert_has_only_matches_unique_populated_kind`]'s widened
/// uniqueness law under complement.
/// 2. **Cardinality-refinement composition law**:
/// `lacks_only(kind) == (!has(kind) && has_unique_missing_kind())`
/// on every arm — the fused walk agrees with the two-step
/// composition of the negated presence probe and the arg-less
/// missing-cardinality Boolean. Closed-set-complement mirror of
/// the populated-axis cardinality-refinement law.
/// 3. **Kind-scoped implication law**:
/// `lacks_only(kind) → !has(kind)` on every arm — if `kind` is the
/// sole missing slot then `kind` cannot be populated. Complement
/// mirror of the `has_only(kind) → has(kind)` implication that
/// binds [`TaggedUnion::has_only`] to [`TaggedUnion::has`] on the
/// strict-refinement axis; here the implication binds `lacks_only`
/// to `!has` on the closed-set-complement axis.
/// 4. **Kind-domain exhaustivity law**: `<T::Kind as ClosedSet>::ALL
/// .iter().filter(|k| parent.lacks_only(*k)).count() ≤ 1` on every
/// arm — a parent satisfies `lacks_only(k)` for AT MOST one `k`,
/// since two distinct kinds cannot both be the sole missing slot.
/// On the near-saturation arm (exactly 1 missing) the count is 1;
/// on every other arm the count is 0. Closed-set-complement mirror
/// of the populated-axis exhaustivity law under complement.
/// 5. **Missing-diagonal well-formed law**:
/// `unique_missing_kind()` is the source of truth for which kind
/// (if any) is uniquely missing on each arm — the testkit reads it
/// directly and asserts `lacks_only(k) == (unique_missing_kind()
/// == Some(k))` for every `k`, so the testkit doesn't hard-code
/// `ALL.len()`-dependent arm expectations (an empty parent on
/// `ALL.len() == 1` is uniquely missing that one kind, whereas on
/// `ALL.len() >= 2` no kind is uniquely missing; a single-slot
/// parent on `ALL.len() == 2` has one missing kind, whereas on
/// `ALL.len() >= 3` it has ≥ 2 missing; a two-slot parent on
/// `ALL.len() == 3` has one missing kind, whereas on `ALL.len()
/// >= 4` it has ≥ 2 missing). The composition-law shape binds
/// every `ALL.len()` regime through the same substrate site.
///
/// The three arm expectations:
///
/// - **Empty-parent baseline** (swept `× ALL` outside the per-slot
/// loop): on any `ALL.len() >= 2` closed set every kind is missing,
/// so `lacks_only(k) == false` for every `k` — no kind is the sole
/// missing kind. Every production parent is `ALL.len() >= 3`.
/// - **Single-slot sweep** (swept on `ClosedSet::ALL × ALL`): the
/// composition-law shape reads `unique_missing_kind()` directly, so
/// the testkit binds every `ALL.len()` regime without a hard-coded
/// arm expectation. Assertion messages carry the (`populated`,
/// `probed`) pair verbatim.
/// - **Two-slot sweep** (swept on the off-diagonal `× ALL`): on
/// `ALL.len() == 3` every off-diagonal pair leaves exactly 1 slot
/// missing (the third kind) — the SOLE `ALL.len()` regime where
/// `lacks_only(third) == true` on the two-slot arm. On `ALL.len()
/// >= 4` the two-slot arm has ≥ 2 missing, so `lacks_only(k) ==
/// false` for every `k`. The composition-law shape binds every
/// regime.
///
/// A fifth sibling tagged-union parent picks up the kind-scoped-
/// strict-refinement check on the missing axis through ONE `impl
/// TaggedUnion for X` block plus ONE per-site `single_slot_X` factory
/// plus ONE per-site `two_slot_X` factory plus ONE per-site `empty_X`
/// factory plus ONE call site — no re-authored `lacks_only` sweep at
/// the test surface.
///
/// Same [`crate::lifetime::Lifetime`] exclusion as the sibling
/// primitives — the `T: TaggedUnion` bound doesn't reach it.
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs. The
/// kind-scoped strict-refinement projection on the MISSING axis
/// binds through the SAME shape the populated-axis peer binds
/// through (a closed-set walk under `Self::has`), differing only in
/// the negation of the presence probe. The composition laws
/// (widened uniqueness on the missing side, cardinality-refinement
/// under complement, kind-scoped implication under complement,
/// kind-domain exhaustivity on the missing side) live at ONE
/// substrate site inside the testkit's per-arm sweep — pinned
/// across every production tagged union at compile time via the
/// trait's default body composition, not per-parent.
/// - THEORY.md §VI.1 — generation over composition. A new
/// [`Self::Kind`] variant added to `ALL` reaches this primitive
/// mechanically through the fused walk at the trait's default body.
#[track_caller]
pub fn assert_lacks_only_matches_unique_missing_kind<T, F, G, H>(
single_slot: F,
two_slot: G,
empty_parent: H,
) where
T: TaggedUnion,
T::Kind: PartialEq + std::fmt::Debug,
F: Fn(T::Kind) -> T,
G: Fn(T::Kind, T::Kind) -> T,
H: Fn() -> T,
{
// Empty-parent baseline — every `lacks_only(k)` returns `false` on
// any `ALL.len() >= 2` closed set (every production union) because
// every kind is missing so no kind is uniquely missing. The
// composition-law shape below reads `unique_missing_kind()`
// directly, so the testkit binds every `ALL.len()` regime without
// a hard-coded arm expectation.
let empty = empty_parent();
assert!(
empty.is_empty(),
"TaggedUnion::lacks_only() testkit: empty_parent() must satisfy is_empty() == true",
);
for k in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let via_lacks_only = empty.lacks_only(k);
// Widened uniqueness composition law on the empty arm.
assert_eq!(
via_lacks_only,
empty.unique_missing_kind() == Some(k),
"empty_parent().lacks_only({k:?}) drifted from (unique_missing_kind() == Some({k:?}))",
);
// Cardinality-refinement composition law on the empty arm
// under complement.
assert_eq!(
via_lacks_only,
!empty.has(k) && empty.has_unique_missing_kind(),
"empty_parent().lacks_only({k:?}) drifted from (!has({k:?}) && has_unique_missing_kind())",
);
// Kind-scoped implication law on the empty arm — lacks_only
// implies !has.
if via_lacks_only {
assert!(
!empty.has(k),
"empty_parent().lacks_only({k:?}) == true but has({k:?}) == true",
);
}
}
// Kind-domain exhaustivity on the empty arm — at most 1 kind is
// the sole missing kind. On `ALL.len() >= 2` the count is 0; on
// the degenerate `ALL.len() == 1` regime (no production parent)
// the count is 1.
let empty_count = <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
.filter(|k| empty.lacks_only(*k))
.count();
assert!(
empty_count <= 1,
"empty_parent(): at most 1 kind may satisfy lacks_only, got {empty_count}",
);
let all_len = <T::Kind as tatara_closed_set::ClosedSet>::ALL.len();
// Single-slot sweep — the composition-law shape across
// `ClosedSet::ALL × ALL`, plus a factory-precondition truth-table
// pin whose expected shape is derived from the abstract factory
// contract (`single_slot(populated)` populates exactly `populated`
// → the missing set is `ALL - {populated}`, size `all_len - 1`).
for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let parent = single_slot(populated);
for probed in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let via_lacks_only = parent.lacks_only(probed);
// Factory-precondition truth table on the well-formed
// single-slot arm: the missing set is `ALL - {populated}`,
// so lacks_only(probed) is `true` iff exactly one slot is
// missing (`all_len == 2`) AND probed names that missing
// slot (`probed != populated`). This hard-codes the well-
// formed diagonal expectation so a factory drift that
// populates the wrong kind — or an empty parent, or the
// saturated parent — surfaces here BEFORE any composition
// law reconciles two internally-drifted trait bodies.
let expected_single = all_len == 2 && probed != populated;
assert_eq!(
via_lacks_only, expected_single,
"single_slot({populated:?}).lacks_only({probed:?}) must equal {expected_single} on ALL.len() == {all_len}",
);
// Widened uniqueness composition law — the primary
// pin-point on the missing axis.
assert_eq!(
via_lacks_only,
parent.unique_missing_kind() == Some(probed),
"single_slot({populated:?}).lacks_only({probed:?}) drifted from (unique_missing_kind() == Some({probed:?}))",
);
// Cardinality-refinement composition law under complement.
assert_eq!(
via_lacks_only,
!parent.has(probed) && parent.has_unique_missing_kind(),
"single_slot({populated:?}).lacks_only({probed:?}) drifted from (!has({probed:?}) && has_unique_missing_kind())",
);
// Kind-scoped implication law under complement —
// lacks_only implies !has.
if via_lacks_only {
assert!(
!parent.has(probed),
"single_slot({populated:?}).lacks_only({probed:?}) == true but has({probed:?}) == true",
);
}
}
// Kind-domain exhaustivity on the well-formed arm — at most 1
// kind satisfies lacks_only. On `ALL.len() == 2` the count is
// exactly 1 (the non-populated kind); on `ALL.len() >= 3` the
// count is 0.
let well_formed_count = <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
.filter(|k| parent.lacks_only(*k))
.count();
let expected_well_formed_count = usize::from(all_len == 2);
assert_eq!(
well_formed_count, expected_well_formed_count,
"single_slot({populated:?}): exactly {expected_well_formed_count} kinds must satisfy lacks_only on ALL.len() == {all_len}, got {well_formed_count}",
);
}
// Two-slot sweep — every off-diagonal pair populates two slots, so
// the missing set is `ALL - {a, b}`, size `all_len - 2`. On
// `ALL.len() == 3` exactly 1 slot is missing (the third kind), so
// exactly 1 kind satisfies lacks_only. On `ALL.len() >= 4` ≥ 2
// slots are missing, so no kind satisfies lacks_only. The
// composition-law shape binds every regime; the factory-
// precondition truth-table pin catches drift like a saturated /
// empty / single-slot two_slot factory that would otherwise slip
// past the internally-consistent composition laws.
for a in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
for b in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
if a == b {
continue;
}
let parent = two_slot(a, b);
for k in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let via_lacks_only = parent.lacks_only(k);
// Factory-precondition truth table on the two-slot
// arm: the missing set is `ALL - {a, b}`, so
// lacks_only(k) is `true` iff exactly one slot is
// missing (`all_len == 3`) AND k names that missing
// slot (`k != a && k != b`).
let expected_two = all_len == 3 && k != a && k != b;
assert_eq!(
via_lacks_only, expected_two,
"two_slot({a:?}, {b:?}).lacks_only({k:?}) must equal {expected_two} on ALL.len() == {all_len}",
);
// Widened uniqueness composition law on the multi-
// populated arm.
assert_eq!(
via_lacks_only,
parent.unique_missing_kind() == Some(k),
"two_slot({a:?}, {b:?}).lacks_only({k:?}) drifted from (unique_missing_kind() == Some({k:?}))",
);
// Cardinality-refinement composition law under
// complement.
assert_eq!(
via_lacks_only,
!parent.has(k) && parent.has_unique_missing_kind(),
"two_slot({a:?}, {b:?}).lacks_only({k:?}) drifted from (!has({k:?}) && has_unique_missing_kind())",
);
// Kind-scoped implication law under complement.
if via_lacks_only {
assert!(
!parent.has(k),
"two_slot({a:?}, {b:?}).lacks_only({k:?}) == true but has({k:?}) == true",
);
}
}
// Kind-domain exhaustivity on the multi-populated arm — at
// most 1 kind is the sole missing kind. On `ALL.len() ==
// 3` the count is exactly 1 (the third kind); on
// `ALL.len() >= 4` the count is 0.
let multi_count = <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
.filter(|k| parent.lacks_only(*k))
.count();
let expected_multi_count = usize::from(all_len == 3);
assert_eq!(
multi_count, expected_multi_count,
"two_slot({a:?}, {b:?}): exactly {expected_multi_count} kinds must satisfy lacks_only on ALL.len() == {all_len}, got {multi_count}",
);
}
}
}
/// Generic closed-set-complement testkit on the kind-scoped SUBSET
/// axis — pins that [`TaggedUnion::lacks`] agrees with the negated
/// [`TaggedUnion::has`], the missing-set membership projection
/// [`TaggedUnion::missing_kinds`], the kind-scoped strict-refinement
/// peer [`TaggedUnion::lacks_only`], AND the missing-axis cardinality
/// scalar [`TaggedUnion::missing_kind_count`] across every
/// [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL) single-slot
/// arrangement, every off-diagonal two-slot pair, AND the empty-
/// parent baseline.
///
/// Closed-set-complement mirror of [`TaggedUnion::has`] under the
/// (populated, missing) duality — where `has(kind)` is the populated-
/// axis SUBSET primitive, `lacks(kind)` is the missing-axis SUBSET
/// primitive. Together with [`TaggedUnion::has_only`] (populated-axis
/// EQUAL) and [`TaggedUnion::lacks_only`] (missing-axis EQUAL) they
/// close the 2×2 kind-scoped (populated, missing) × (subset, equal)
/// grid. The five sub-assertions swept per arrangement + the empty-
/// parent baseline:
///
/// 1. **Definitional complement law**: `lacks(kind) == !has(kind)`
/// on every arm — the trait's default body composition is a
/// single bit-flip past [`TaggedUnion::has`], and no override
/// may drift the two primitives apart.
/// 2. **Missing-set membership composition law**:
/// `lacks(kind) == missing_kinds().contains(&kind)` on every
/// arm — closed-set-complement peer of the populated-axis law
/// `has(kind) == populated_kinds().contains(&kind)` swept by
/// [`assert_populated_kinds_matches_has`].
/// 3. **Kind-scoped implication law**: `lacks_only(kind) →
/// lacks(kind)` on every arm — if `kind` is the SOLE missing
/// slot then `kind` is missing. Byte-for-byte missing-axis peer
/// of the `has_only(kind) → has(kind)` implication that binds
/// [`TaggedUnion::has_only`] to [`TaggedUnion::has`] on the
/// strict-refinement axis.
/// 4. **Cardinality-partition law**: `<T::Kind as ClosedSet>::ALL
/// .iter().filter(|k| parent.lacks(*k)).count() ==
/// parent.missing_kind_count()` on every arm — the count of
/// kinds satisfying `lacks` equals the parent's missing-slot
/// count. Closed-set-complement peer of the populated-axis law
/// `count k where has(k) == populated_kind_count()`.
/// 5. **Factory-precondition truth table** whose expected shape is
/// derived from the abstract factory contract (`empty_parent()`
/// missing set is all of `ALL`, size `all_len`;
/// `single_slot(populated)` missing set is `ALL - {populated}`,
/// size `all_len - 1`; `two_slot(a, b)` missing set is `ALL -
/// {a, b}`, size `all_len - 2`) — hard-codes the arm expectation
/// across every `ALL.len()` regime so a factory drift that
/// yields a saturated / drifted parent surfaces BEFORE any
/// composition law reconciles two internally-drifted trait
/// bodies.
///
/// A fifth sibling tagged-union parent picks up the closed-set-
/// complement check on the kind-scoped SUBSET axis through ONE
/// `impl TaggedUnion for X` block plus ONE per-site `single_slot_X`
/// factory plus ONE per-site `two_slot_X` factory plus ONE per-site
/// `empty_X` factory plus ONE call site — no re-authored `lacks`
/// sweep at the test surface.
///
/// Same [`crate::lifetime::Lifetime`] exclusion as the sibling
/// primitives — the `T: TaggedUnion` bound doesn't reach it.
///
/// # Theory grounding
///
/// - THEORY.md §II.1 invariant 5 — composition preserves proofs.
/// The kind-scoped closed-set-complement projection lives at ONE
/// substrate site as a definitional negation of
/// [`TaggedUnion::has`]. The five composition laws (definitional
/// complement, missing-set membership, kind-scoped implication
/// from `lacks_only`, cardinality partition against
/// `missing_kind_count`, factory-precondition truth table) live at
/// ONE substrate site inside the testkit's per-arm sweep — pinned
/// across every production tagged union at compile time via the
/// trait's default body composition, not per-parent.
/// - THEORY.md §VI.1 — generation over composition. A new
/// [`Self::Kind`] variant added to `ALL` reaches this primitive
/// mechanically through the delegated [`Self::has`] — the five
/// laws hold on the widened kind set without further per-caller
/// edit.
#[track_caller]
pub fn assert_lacks_matches_has_complement<T, F, G, H>(single_slot: F, two_slot: G, empty_parent: H)
where
T: TaggedUnion,
T::Kind: PartialEq + std::fmt::Debug,
F: Fn(T::Kind) -> T,
G: Fn(T::Kind, T::Kind) -> T,
H: Fn() -> T,
{
let all_len = <T::Kind as tatara_closed_set::ClosedSet>::ALL.len();
// Empty-parent baseline — every `lacks(k)` returns `true`
// (empty parent has every slot missing). The factory-
// precondition truth-table pin catches an `empty_parent` that
// drifts from empty (a single-slot or saturated factory
// masquerading as empty) BEFORE any composition law reconciles
// two internally-drifted trait bodies.
let empty = empty_parent();
assert!(
empty.is_empty(),
"TaggedUnion::lacks() testkit: empty_parent() must satisfy is_empty() == true",
);
let empty_missing_count = empty.missing_kind_count();
for k in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let via_lacks = empty.lacks(k);
// Factory-precondition truth table on the empty arm: the
// missing set is all of `ALL`, so `lacks(k) == true` for
// every `k`.
assert!(
via_lacks,
"empty_parent().lacks({k:?}) must equal true (empty parent has every slot missing)",
);
// Definitional complement law on the empty arm.
assert_eq!(
via_lacks,
!empty.has(k),
"empty_parent().lacks({k:?}) drifted from !has({k:?})",
);
// Missing-set membership composition law on the empty arm.
assert_eq!(
via_lacks,
empty.missing_kinds().contains(&k),
"empty_parent().lacks({k:?}) drifted from missing_kinds().contains(&{k:?})",
);
// Kind-scoped implication law on the empty arm — lacks_only
// implies lacks. On any `ALL.len() >= 2` closed set the
// empty parent has ≥ 2 missing so lacks_only(k) == false on
// every k, and the implication is vacuously true; on the
// degenerate `ALL.len() == 1` regime lacks_only(k) == true
// on the sole k, and the implication holds because lacks(k)
// == true too.
if empty.lacks_only(k) {
assert!(
via_lacks,
"empty_parent().lacks_only({k:?}) == true but lacks({k:?}) == false",
);
}
}
// Cardinality-partition law on the empty arm — every kind
// satisfies lacks, so the count equals missing_kind_count()
// which equals ALL.len().
let empty_count = <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
.filter(|k| empty.lacks(*k))
.count();
assert_eq!(
empty_count, empty_missing_count,
"empty_parent(): count of kinds satisfying lacks ({empty_count}) drifted from missing_kind_count() ({empty_missing_count})",
);
assert_eq!(
empty_count, all_len,
"empty_parent(): count of kinds satisfying lacks must equal ALL.len() ({all_len}), got {empty_count}",
);
// Single-slot sweep — the composition-law shape across
// `ClosedSet::ALL × ALL`, plus a factory-precondition truth-
// table pin whose expected shape is derived from the abstract
// factory contract (`single_slot(populated)` populates exactly
// `populated` → the missing set is `ALL - {populated}`, so
// `lacks(probed) == true` iff `probed != populated`).
for populated in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let parent = single_slot(populated);
let parent_missing_count = parent.missing_kind_count();
for probed in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let via_lacks = parent.lacks(probed);
// Factory-precondition truth table on the well-formed
// single-slot arm.
let expected_single = probed != populated;
assert_eq!(
via_lacks, expected_single,
"single_slot({populated:?}).lacks({probed:?}) must equal {expected_single}",
);
// Definitional complement law.
assert_eq!(
via_lacks,
!parent.has(probed),
"single_slot({populated:?}).lacks({probed:?}) drifted from !has({probed:?})",
);
// Missing-set membership composition law.
assert_eq!(
via_lacks,
parent.missing_kinds().contains(&probed),
"single_slot({populated:?}).lacks({probed:?}) drifted from missing_kinds().contains(&{probed:?})",
);
// Kind-scoped implication law — lacks_only implies
// lacks.
if parent.lacks_only(probed) {
assert!(
via_lacks,
"single_slot({populated:?}).lacks_only({probed:?}) == true but lacks({probed:?}) == false",
);
}
}
// Cardinality-partition law on the well-formed arm — the
// count of kinds satisfying lacks equals
// missing_kind_count() which equals ALL.len() - 1.
let well_formed_count = <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
.filter(|k| parent.lacks(*k))
.count();
assert_eq!(
well_formed_count, parent_missing_count,
"single_slot({populated:?}): count of kinds satisfying lacks ({well_formed_count}) drifted from missing_kind_count() ({parent_missing_count})",
);
let expected_single_missing = all_len - 1;
assert_eq!(
well_formed_count, expected_single_missing,
"single_slot({populated:?}): count of kinds satisfying lacks must equal ALL.len() - 1 ({expected_single_missing}), got {well_formed_count}",
);
}
// Two-slot sweep — every off-diagonal pair populates two slots,
// so the missing set is `ALL - {a, b}`, size `all_len - 2`, and
// `lacks(k) == true` iff `k != a && k != b`. On `ALL.len() == 2`
// `all_len - 2 == 0` (the two-slot arm saturates), so `lacks(k)
// == false` on every k; the composition-law shape binds every
// regime.
for a in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
for b in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
if a == b {
continue;
}
let parent = two_slot(a, b);
let parent_missing_count = parent.missing_kind_count();
for k in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let via_lacks = parent.lacks(k);
// Factory-precondition truth table on the two-slot
// arm.
let expected_two = k != a && k != b;
assert_eq!(
via_lacks, expected_two,
"two_slot({a:?}, {b:?}).lacks({k:?}) must equal {expected_two}",
);
// Definitional complement law.
assert_eq!(
via_lacks,
!parent.has(k),
"two_slot({a:?}, {b:?}).lacks({k:?}) drifted from !has({k:?})",
);
// Missing-set membership composition law.
assert_eq!(
via_lacks,
parent.missing_kinds().contains(&k),
"two_slot({a:?}, {b:?}).lacks({k:?}) drifted from missing_kinds().contains(&{k:?})",
);
// Kind-scoped implication law.
if parent.lacks_only(k) {
assert!(
via_lacks,
"two_slot({a:?}, {b:?}).lacks_only({k:?}) == true but lacks({k:?}) == false",
);
}
}
// Cardinality-partition law on the two-slot arm.
let multi_count = <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
.filter(|k| parent.lacks(*k))
.count();
assert_eq!(
multi_count, parent_missing_count,
"two_slot({a:?}, {b:?}): count of kinds satisfying lacks ({multi_count}) drifted from missing_kind_count() ({parent_missing_count})",
);
let expected_two_missing = all_len - 2;
assert_eq!(
multi_count, expected_two_missing,
"two_slot({a:?}, {b:?}): count of kinds satisfying lacks must equal ALL.len() - 2 ({expected_two_missing}), got {multi_count}",
);
}
}
}
/// Generic ambiguity testkit — pins that [`TaggedUnion::variant`]
/// resolves to [`TaggedUnionError::ambiguous`] on EVERY off-diagonal
/// `(a, b)` pair in [`ClosedSet::ALL`](tatara_closed_set::ClosedSet::ALL)
/// `× ALL`.
///
/// Substrate primitive for the sibling
/// `_two_slots_is_ambiguous_across_every_pair` tests on `ProcessSpec`
/// ([`crate::encapsulates::EncapsulationKind`],
/// [`crate::export::ArtifactSource`], [`crate::export::VectorChannel`])
/// that pre-lift each restated the same nested-`for a in K::ALL { for
/// b in K::ALL { if a == b { continue; } … } }` sweep at their own
/// test bodies — byte-identical projections whose only per-carrier
/// knobs are the (Kind type + the `two_slot_X(a, b) -> Parent`
/// two-slot factory) pair. Post-lift each site collapses to ONE
/// `assert_two_slots_ambiguous::<Xxx, _>(two_slot_X)` invocation.
///
/// The `two_slot` closure stays per-site — every one of the three
/// production sites already owns a `two_slot_kind /
/// two_slot_source / two_slot_channel` helper that composes two
/// `single_slot_X`s per-field. The closure IS the "populate both
/// slots a and b" ground truth for the carrier's field structure;
/// lifting it into the primitive would collapse per-site field-
/// composition knowledge that stays deliberately local.
///
/// The pair sweep excludes the diagonal (`a == b`) — a single slot
/// populated is exactly-one, not many, and the round-trip primitive
/// [`assert_variant_round_trip`] already pins that populated slot's
/// resolution. This primitive is the peer contract for the Many arm.
///
/// A fifth sibling tagged-union parent picks up the ambiguity check
/// through ONE `impl TaggedUnion for X` block + ONE per-site
/// `two_slot_X` helper + ONE `assert_two_slots_ambiguous::<X, _>`
/// call site — no re-authored nested-for sweep at the test surface,
/// no re-authored `assert_eq!(..., X::Error::Ambiguous, ...)` arm.
///
/// The [`crate::lifetime::Lifetime`] site is DELIBERATELY excluded
/// — `Lifetime` doesn't impl [`TaggedUnion`] (its error carrier has
/// no `Empty` arm; its `variant()` returns `Ok(Permanent)` on empty
/// rather than an `Empty` typed error), so the `<T: TaggedUnion>`
/// bound doesn't reach it. Its per-site ambiguity assertion binds
/// through the inherent `.variant()` + hand-authored two-slot
/// probe. Same reasoning as [`resolve_or_err`]'s and
/// [`assert_variant_round_trip`]'s exclusions.
#[track_caller]
pub fn assert_two_slots_ambiguous<T, F>(two_slot: F)
where
T: TaggedUnion,
T::Kind: PartialEq + std::fmt::Debug,
T::Error: PartialEq + std::fmt::Debug,
F: Fn(T::Kind, T::Kind) -> T,
{
let expected = T::Error::ambiguous();
for a in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
for b in <T::Kind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
if a == b {
continue;
}
let parent = two_slot(a, b);
let err = parent.variant().err().unwrap_or_else(|| {
panic!("({a:?}, {b:?}) two-slot parent must not resolve to a variant")
});
assert_eq!(err, expected, "({a:?}, {b:?}) should resolve Ambiguous");
}
}
}
/// Generic wire-key / kind-label alignment testkit — pins that every
/// single-slot parent serializes to a JSON object with EXACTLY ONE key
/// whose name equals `<T::Kind as tatara_closed_set::ClosedSet>::label`
/// on the populated slot's kind.
///
/// Substrate primitive for the four sibling
/// `X_kind_as_str_matches_field_name` / `intent_kind_as_str_matches_intent_field_name`
/// tests on `ProcessSpec` ([`crate::intent::Intent`],
/// [`crate::encapsulates::EncapsulationKind`],
/// [`crate::export::ArtifactSource`], [`crate::export::VectorChannel`])
/// that pre-lift each restated the same wire-format sweep at their own
/// test bodies:
///
/// 1. For each `k in K::ALL`, construct a single-slot parent via
/// the site-local `single_slot_X(k) -> Parent` factory.
/// 2. Serialize it to the wire format and assert that the emitted
/// key matches `k.as_str()`.
///
/// Post-lift each site's alignment test collapses to ONE
/// `assert_single_slot_key_matches_label::<T, _>(single_slot_X)`
/// invocation whose body IS the substrate primitive's own dispatch.
/// A fifth sibling picks up the alignment check through ONE call site.
///
/// The primitive projects through `serde_json::to_value` rather than
/// `serde_yaml::to_string` for two reasons: (1) the check is
/// structural (exactly-one-key + name equality), not textual (substring
/// against a `"{key}:"` YAML fragment), so a future site that gains
/// non-tagged-union metadata fields is caught HERE at the exactly-one
/// arm — the YAML-substring check the three encapsulates / export sites
/// carried pre-lift would silently pass on such drift. (2) serde's
/// field-rename projection (`rename_all = "camelCase"`) is format-
/// agnostic, so a JSON check pins the SAME invariant a YAML check
/// would pin, byte-identically. Every one of the four production
/// parents already emits exactly one key on a single-slot populate —
/// their `#[serde(default, skip_serializing_if = "Option::is_none")]`
/// annotations on every tagged-union slot guarantee it — so upgrading
/// the three YAML sites to the JSON exactly-one check is a strict
/// strengthening.
///
/// The `single_slot` closure stays per-site — every one of the four
/// production sites already owns a `single_slot_intent /
/// single_slot_kind / single_slot_source / single_slot_channel` helper
/// that constructs a minimally-valid parent with the addressed slot's
/// inner spec populated; the closure IS the "populate slot k" ground
/// truth for the carrier's field structure. Reused verbatim from the
/// [`assert_variant_round_trip`] primitive.
///
/// The [`crate::lifetime::Lifetime`] site is DELIBERATELY excluded
/// from THIS trait-projected surface — `Lifetime` doesn't impl
/// [`TaggedUnion`] (its `variant()` returns `Ok(Permanent)` on empty
/// rather than an `Empty` typed error), so the `<T: TaggedUnion>`
/// bound doesn't reach it. The bound-relaxed peer
/// [`assert_wire_key_matches_label`] carries the SAME sweep body
/// under `<T: Serialize>` + `<K: ClosedSet>` alone — Lifetime binds
/// through it directly and this trait-projected surface becomes a
/// one-line delegation whose only load-bearing purpose is to name
/// the TaggedUnion parent's `T::Kind` associated type at the call
/// site (existing `assert_single_slot_key_matches_label::<T, _>(f)`
/// callers stay unchanged; the peer inflects the same body onto
/// non-TaggedUnion parents).
#[track_caller]
pub fn assert_single_slot_key_matches_label<T, F>(single_slot: F)
where
T: TaggedUnion + serde::Serialize,
T::Kind: PartialEq + std::fmt::Debug,
F: Fn(T::Kind) -> T,
{
assert_wire_key_matches_label::<T, T::Kind, F>(single_slot);
}
/// Bound-relaxed peer of [`assert_single_slot_key_matches_label`] —
/// the SAME wire-key alignment sweep, but on any `(K, T)` pair where
/// `K: ClosedSet` addresses `T: Serialize` through a caller-supplied
/// `single_slot: Fn(K) -> T` factory. Drops the `T: TaggedUnion`
/// bound the sibling primitive carries so parents whose empty
/// resolution shape diverges from the tagged-union convention (the
/// canonical example: [`crate::lifetime::Lifetime`], whose empty
/// resolves to `Permanent(&DEFAULT_PERMANENT)` rather than to an
/// [`TaggedUnionError::empty`] carrier) still bind through ONE
/// substrate wire-key alignment site.
///
/// The two primitives share ONE sweep body; the trait-projected
/// [`assert_single_slot_key_matches_label`] is now a one-line
/// delegation to this bound-relaxed peer, so every drift-arm the
/// sibling `#[should_panic]` probe pins on the delegating surface
/// mechanically pins here too. The compounding gain: a fifth parent
/// whose closed-set kind K doesn't ride the TaggedUnion trait (a
/// future variant surface with a default-arm on empty; a wire-only
/// enum whose parent is a wrapper struct that never publishes a
/// resolver; a K-addressed `HashMap<K, Payload>` where the payload
/// isn't a tagged-union variant carrier at all) picks up wire-key
/// alignment through ONE call site — no re-authored serialize +
/// exactly-one-key + name-equality body at the test surface, no
/// per-parent drift risk where the trait-projected surface catches
/// it and the bespoke surface forgets.
///
/// The primitive binds `<K: ClosedSet + PartialEq + Debug>` (the
/// strict union of the sweep body's projection + the panic-message
/// substrate-wide shape) — every production `ClosedSet` implementor
/// across the crate carries `Debug + PartialEq` through the
/// substrate-wide `#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash,
/// DeriveClosedSet)]` shape, so no site pays a bound-widening cost
/// to bind through this peer.
#[track_caller]
pub fn assert_wire_key_matches_label<T, K, F>(single_slot: F)
where
T: serde::Serialize,
K: tatara_closed_set::ClosedSet + PartialEq + std::fmt::Debug,
F: Fn(K) -> T,
{
for k in <K as tatara_closed_set::ClosedSet>::ALL.iter().copied() {
let parent = single_slot(k);
let value = serde_json::to_value(&parent)
.unwrap_or_else(|e| panic!("single_slot({k:?}) must serialize as JSON: {e}"));
let obj = value.as_object().unwrap_or_else(|| {
panic!("single_slot({k:?}) must serialize to a JSON object, got {value}")
});
let keys: Vec<&String> = obj.keys().collect();
assert_eq!(
keys.len(),
1,
"single_slot({k:?}) must serialize to exactly one populated field, got keys: {keys:?}",
);
let expected = <K as tatara_closed_set::ClosedSet>::label(k);
assert_eq!(
keys[0].as_str(),
expected,
"wire-key drift for {k:?}: single_slot's populated field '{}' must equal <K as ClosedSet>::label ({expected:?})",
keys[0],
);
}
}
/// Generic Display / [`ClosedSet::label`](tatara_closed_set::ClosedSet::label)
/// alignment testkit — pins that [`core::fmt::Display`] renders each variant
/// BYTE-IDENTICALLY to the trait-visible `ClosedSet::label` projection for
/// every implementor.
///
/// Substrate primitive for the 29 sibling
/// `X_display_matches_as_str` tests across `tatara-process`
/// (`AllocationPhase`, `IntentKind`, `WorkloadKind`, `EncapsulationMode`,
/// `EncapsulationTarget`, `ConditionKind`, `TerminateReasonKind`,
/// `AutoTerminateKind`, `SighupStrategy`, `ReplacementPolicy`,
/// `ReturnPolicy`, `MemberState`, `PoolPhase`, `VerificationPhase`,
/// `SelectStrategyKind`, `MustReachPhase`, `ExportTrigger`,
/// `ReportFormat`, `ReportPayloadShape`, `ArtifactKind`, `ChannelKind`,
/// `DataClassification`, `ConvergencePointType`, `Arity`,
/// `SubstrateType`, `CalmClassification`, `OptimizationDirection`,
/// `HorizonKind`, `TeardownPolicy`) that pre-lift each restated the
/// same
/// ```text
/// for v in K::ALL {
/// assert_eq!(v.to_string(), v.as_str());
/// }
/// ```
/// two-line probe verbatim at their own test bodies — byte-identical
/// projections whose only per-carrier knob is the closed-set type name.
/// Post-lift each site collapses to ONE
/// `assert_display_matches_label::<X>()` invocation whose body IS the
/// substrate primitive's own dispatch.
///
/// The primitive projects through the STABLE trait-visible name
/// [`ClosedSet::label`](tatara_closed_set::ClosedSet::label) rather
/// than the inherent `.as_str()` each site publishes locally. Every
/// production implementor here derives its `label` body from `as_str`
/// via `#[closed_set(via = "as_str", display)]` (the substrate-wide
/// derive shape), so the two are byte-identical by construction; the
/// primitive's projection through `label` therefore pins the SAME
/// invariant the pre-lift bodies pinned while binding to the
/// stable trait-visible surface. A future implementor whose inherent
/// canonical projection is named something other than `as_str` (e.g.
/// `.keyword()`, `.spelling()`) but still routes through
/// `#[closed_set(via = "...", display)]` picks up the alignment check
/// through ONE `assert_display_matches_label::<X>()` invocation with
/// no inherent-name coupling at the test site.
///
/// A fifth (or thirtieth, or hundredth) implementor picks up the
/// Display-alignment check through ONE
/// `#[derive(tatara_closed_set::DeriveClosedSet)]` + `display`
/// attribute + ONE `assert_display_matches_label::<X>()` call site —
/// no re-authored two-line
/// `for v in K::ALL { assert_eq!(v.to_string(), v.as_str()) }` body
/// at the test surface, no per-site drift risk where 28 sibling
/// tests carry the assertion and the 29th forgets.
///
/// Sibling shape to [`assert_kind_list_matches_closed_set`] on the
/// (`T::KIND_LIST` slash-join, `Display` byte-identity) axis: both
/// project the closed-set's label surface onto ONE typed contract
/// and pin it against a per-implementor rendering; the former for
/// the tagged-union parent's [`TaggedUnion::KIND_LIST`] `&'static str`,
/// this one for the enum's `Display` byte stream. Together they close
/// the "label surface must round-trip verbatim" invariant every
/// closed-set-carrying implementor across the crate publishes.
#[track_caller]
pub fn assert_display_matches_label<T>()
where
T: tatara_closed_set::ClosedSet + core::fmt::Display + PartialEq + core::fmt::Debug,
{
let type_name = core::any::type_name::<T>();
for &v in <T as tatara_closed_set::ClosedSet>::ALL {
let rendered = v.to_string();
let expected = <T as tatara_closed_set::ClosedSet>::label(v);
assert_eq!(
rendered.as_str(),
expected,
"{type_name}: Display drifted from ClosedSet::label for {v:?} — expected {expected:?}, got {rendered:?}",
);
}
}
/// CANONICAL-KEY CONTRACT testkit — pins that each variant's serde
/// serialization (as a JSON string value, unquoted) matches its
/// canonical [`ClosedSet::label`](tatara_closed_set::ClosedSet::label)
/// projection BYTE-IDENTICALLY for every implementor.
///
/// Substrate primitive for the 20 sibling
/// `X_as_str_matches_serde` tests across `tatara-process`
/// (`TeardownPolicy`, `EncapsulationMode`, `ConditionKind`,
/// `SighupStrategy`, `ReplacementPolicy`, `ReturnPolicy`, `MemberState`,
/// `PoolPhase`, `VerificationPhase`, `MustReachPhase`, `WorkloadKind`,
/// `ExportTrigger`, `ReportFormat`, `DataClassification`,
/// `ConvergencePointType`, `SubstrateType`, `CalmClassification`,
/// `OptimizationDirection`, `HorizonKind`, `AllocationPhase`) that
/// pre-lift each restated the same
/// ```text
/// for v in K::ALL {
/// let serialized = serde_json::to_string(&v).expect("serialize");
/// let unquoted = serialized
/// .trim_start_matches('"')
/// .trim_end_matches('"')
/// .to_string();
/// assert_eq!(unquoted, v.as_str(), "as_str drift for {v:?}: ...");
/// }
/// ```
/// four-line probe verbatim at their own test bodies — byte-identical
/// projections whose only per-carrier knob is the closed-set type name.
/// Post-lift each site collapses to ONE
/// `assert_label_matches_serde_serialization::<X>()` invocation whose
/// body IS the substrate primitive's own dispatch.
///
/// The primitive projects through the STABLE trait-visible name
/// [`ClosedSet::label`](tatara_closed_set::ClosedSet::label) rather
/// than the inherent `.as_str()` each site publishes locally. Every
/// production implementor here derives its `label` body from `as_str`
/// via `#[closed_set(via = "as_str", display)]` + `#[serde(rename_all
/// = "PascalCase")]` (the substrate-wide derive shape), so the two are
/// byte-identical by construction; the primitive's projection through
/// `label` therefore pins the SAME invariant the pre-lift bodies
/// pinned while binding to the stable trait-visible surface. A future
/// implementor whose canonical inherent projection is named something
/// other than `as_str` (e.g. `.keyword()`, `.spelling()`) but still
/// routes through `#[closed_set(via = "...")]` picks up the wire-format
/// alignment check through ONE call with no inherent-name coupling at
/// the test site.
///
/// A twenty-first (or hundredth) implementor picks up the alignment
/// check through ONE `#[derive(tatara_closed_set::DeriveClosedSet)]` +
/// `#[derive(serde::Serialize)]` + `#[serde(rename_all = "...")]`
/// attribute + ONE `assert_label_matches_serde_serialization::<X>()`
/// call site — no re-authored four-line probe body at the test surface,
/// no per-site drift risk where 19 sibling tests carry the assertion
/// and the 20th forgets, no `serde_json::to_string`+`trim_matches`+
/// `assert_eq!` composition re-derived per implementor.
///
/// Sibling shape to [`assert_display_matches_label`] on the
/// (Display byte-identity, serde-wire-format byte-identity) axis: both
/// project the closed-set's label surface onto ONE typed contract and
/// pin it against a per-implementor rendering; the former for the
/// enum's [`Display`](core::fmt::Display) byte stream, this one for
/// the serde JSON-string wire format. Together they close the "label
/// surface renders verbatim across every projection consumers reach
/// for" invariant every closed-set-carrying implementor across the
/// crate publishes.
#[track_caller]
pub fn assert_label_matches_serde_serialization<T>()
where
T: tatara_closed_set::ClosedSet + serde::Serialize + core::fmt::Debug,
{
let type_name = core::any::type_name::<T>();
for &v in <T as tatara_closed_set::ClosedSet>::ALL {
let serialized = serde_json::to_string(&v).unwrap_or_else(|e| {
panic!("{type_name}: closed-set variant {v:?} must serialize: {e}")
});
let unquoted = serialized.trim_start_matches('"').trim_end_matches('"');
let expected = <T as tatara_closed_set::ClosedSet>::label(v);
assert_eq!(
unquoted,
expected,
"{type_name}: serde output drifted from ClosedSet::label for {v:?} — expected {expected:?}, got {unquoted:?} (full serialization {serialized:?})",
);
}
}
/// CLOSED-SET CONVENTION PANEL testkit — pins the FULL three-axis
/// label-surface convention (parse round-trip, Display byte-identity,
/// serde-JSON-string byte-identity) at ONE substrate call site per
/// implementor.
///
/// Compound-lift of [`tatara_closed_set::assert_closed_set_well_formed`]
/// + [`assert_display_matches_label`] + [`assert_label_matches_serde_
/// serialization`] — every closed-set enum on `ProcessSpec` that
/// carries the substrate-wide `#[derive(DeriveClosedSet)] +
/// #[derive(Serialize)] + #[closed_set(via = "as_str", display)] +
/// #[serde(rename_all = "PascalCase")]` shape publishes ALL THREE
/// axes of the label surface, and pre-lift each production test
/// module hand-authored three sibling one-line tests
/// (`X_is_well_formed_closed_set`, `X_display_matches_as_str`,
/// `X_as_str_matches_serde`) that each restated the SAME
/// `crate::tagged_union::assert_<axis>::<X>()` invocation with only
/// the axis name varying between siblings. Post-lift each site
/// collapses to ONE `assert_closed_set_convention_panel::<X>()`
/// invocation whose body IS the three-axis composition dispatched
/// through the substrate primitive here.
///
/// The three sub-assertions stay independently callable — a future
/// implementor that publishes only two of the three axes (a
/// `Display`-less internal enum, e.g., or a `Serialize`-less
/// runtime-only enum) still binds through the two sibling primitives
/// individually. The compound is a strict superset: any implementor
/// that satisfies the compound's bounds already satisfies each
/// sub-assertion's bounds by construction, and the failure mode of
/// each sub-assertion still surfaces with the exact-message
/// granularity `#[track_caller]` gives the individual primitives
/// (the compound is `#[track_caller]` too, so a sub-assertion panic
/// surfaces at the compound's call site — a future promotion could
/// wrap each sub-assertion in a `std::panic::catch_unwind` to
/// aggregate all three axis failures into ONE panic message, but the
/// pre-lift discipline is that each axis's failure surfaces with its
/// own diagnostic).
///
/// The compound's bounds are the strict union of the three sub-
/// assertions' bounds:
/// - [`assert_closed_set_well_formed`] requires
/// `T: ClosedSet + PartialEq + Debug` + `T::Unknown: Display`;
/// - [`assert_display_matches_label`] requires
/// `T: ClosedSet + Display + PartialEq + Debug`;
/// - [`assert_label_matches_serde_serialization`] requires
/// `T: ClosedSet + Serialize + Debug`.
/// The union `T: ClosedSet + Serialize + Display + PartialEq + Debug`
/// + `T::Unknown: Display` is what every 3-axis production consumer
/// already satisfies through the substrate-wide derive shape — any
/// implementor that fails the compound's bounds would ALSO fail the
/// individual sub-assertions' bounds, so the compound doesn't shrink
/// the reachable set of implementors relative to hand-authoring the
/// three sibling calls.
///
/// A future FOURTH label-surface projection (e.g. a `serde_yaml`
/// byte-identity axis if the crate gains a YAML wire form on closed-
/// set enums, or a `kubectl_annotation` axis if the reconciler grows
/// an annotation-carried label surface) lands as ONE new
/// `assert_<axis>_matches_label::<T>()` substrate primitive + ONE
/// new line inside this compound's body. Every one of the ~20
/// production implementors of the panel picks up the fourth-axis
/// alignment check mechanically at their sole `assert_closed_set_
/// convention_panel::<X>()` call site — no per-implementor test-site
/// authoring, no per-crate test-site drop pathway where 19 sibling
/// call sites carry the check and the 20th forgets. The exact
/// promise `e4a4eba`'s future gain #2 named after
/// `assert_label_matches_serde_serialization` opened the wire-format
/// axis: a workspace-wide panel with byte-identical calling shapes
/// (`assert_X::<T>()`) that composes as freely as its sub-primitives.
///
/// Sibling shape to [`assert_variant_round_trip`] +
/// [`assert_kind_list_matches_closed_set`] +
/// [`assert_two_slots_ambiguous`] +
/// [`assert_single_slot_key_matches_label`] on the tagged-union
/// PARENT axis: the parent-side compound would compose the four
/// parent-side per-axis primitives, this one composes the three
/// child-side per-axis primitives on the child's [`ClosedSet`]
/// surface. Together the two compounds close the "closed-set
/// convention holds across every projection consumers reach for" at
/// two adjacent panels — one per closed-set-carrying enum, one per
/// tagged-union parent.
///
/// Theory anchor: THEORY.md §V.1 (knowable platform) — the
/// three-axis label-surface convention becomes ONE typed theorem
/// provable generically over any
/// `T: ClosedSet + Serialize + Display + PartialEq + Debug` bound
/// rather than THREE hand-authored per-implementor one-line probes
/// held coherent by test-module convention. THEORY.md §II.1
/// invariant 5 (composition preserves proofs) — the three sub-
/// assertions compose structurally through ONE primitive here, so a
/// regression at ONE axis surfaces at the sub-assertion's own
/// panic message rather than as silent drift at every consumer that
/// might otherwise forget to include the axis in its per-site
/// author-time enumeration.
#[track_caller]
pub fn assert_closed_set_convention_panel<T>()
where
T: tatara_closed_set::ClosedSet
+ serde::Serialize
+ core::fmt::Display
+ PartialEq
+ core::fmt::Debug,
T::Unknown: core::fmt::Display,
{
tatara_closed_set::assert_closed_set_well_formed::<T>();
assert_display_matches_label::<T>();
assert_label_matches_serde_serialization::<T>();
}
/// TAGGED-UNION CONVENTION PANEL testkit — pins the FULL four-axis
/// tagged-union parent convention (KIND_LIST diagnostic-stability,
/// variant round-trip on the single-slot side, ALL×ALL two-slot
/// ambiguity, wire-key alignment on the single-slot side) at ONE
/// substrate call site per parent.
///
/// Parent-side compound-lift, sibling to
/// [`assert_closed_set_convention_panel`] on the child's
/// [`tatara_closed_set::ClosedSet`] axis. Composes
/// [`assert_kind_list_matches_closed_set`] (no fixture) +
/// [`assert_variant_round_trip`] (`single_slot`) +
/// [`assert_two_slots_ambiguous`] (`two_slot`) +
/// [`assert_single_slot_key_matches_label`] (`single_slot`).
///
/// Every one of the four production `.variant()` parents on
/// `ProcessSpec` ([`crate::intent::Intent`],
/// [`crate::encapsulates::EncapsulationKind`],
/// [`crate::export::ArtifactSource`],
/// [`crate::export::VectorChannel`]) publishes the four-axis
/// convention through the shared substrate-wide attribute-set:
/// `#[derive(DeriveClosedSet)]` on the addressing `Kind`,
/// `declare_tagged_union_impls!` for the resolver+selector+trait
/// triple, `#[serde(rename_all = "camelCase")]` +
/// `#[serde(default, skip_serializing_if = "Option::is_none")]` on
/// every tagged-union slot. Pre-lift each production site
/// hand-authored FOUR sibling per-axis tests (`X_kind_round_trips_through_variant_kind`
/// / `X_kind_list_matches_ClosedSet_labels` /
/// `X_two_slots_are_ambiguous` /
/// `X_kind_as_str_matches_field_name`) that each restated the
/// SAME `crate::tagged_union::assert_<axis>::<T, _>(fixture)`
/// invocation with only the axis name + fixture arity varying
/// between siblings. Post-lift each site's four per-axis sibling
/// tests can collapse to ONE
/// `assert_tagged_union_convention_panel::<T, _, _>(
/// single_slot_X, two_slot_X)` invocation whose body IS the
/// four-axis composition dispatched through the substrate
/// primitive here.
///
/// The two closures stay per-site — every one of the four
/// production parents already owns a `single_slot_X(k) -> Parent`
/// / `two_slot_X(a, b) -> Parent` pair, and the substrate-local
/// `{single,two}_slot_*_probe` peers (siblings to the wire-key
/// sweep's substrate-local probes) let the substrate-wide sweep
/// below bind through the compound without reaching across the
/// per-crate test-module boundaries. Lifting the two closures
/// into the primitive would collapse the per-site construction
/// knowledge that stays deliberately local — the closure IS the
/// "populate slot k" / "populate the (a, b) pair" ground truth
/// for the parent's field structure.
///
/// Bounds are the strict union of the four sub-assertions' bounds:
/// [`assert_kind_list_matches_closed_set`] requires
/// `T: TaggedUnion`; [`assert_variant_round_trip`] requires
/// `T: TaggedUnion` + `T::Kind: PartialEq + Debug`
/// + `F: Fn(T::Kind) -> T`; [`assert_two_slots_ambiguous`] requires
/// `T: TaggedUnion` + `T::Kind: PartialEq + Debug`
/// + `T::Error: PartialEq + Debug` + `F: Fn(T::Kind, T::Kind) -> T`;
/// [`assert_single_slot_key_matches_label`] requires
/// `T: TaggedUnion + Serialize` + `T::Kind: PartialEq + Debug`
/// + `F: Fn(T::Kind) -> T`. The union
/// `T: TaggedUnion + Serialize` + `T::Kind: PartialEq + Debug`
/// + `T::Error: PartialEq + Debug` + `F1: Fn(T::Kind) -> T`
/// + `F2: Fn(T::Kind, T::Kind) -> T` is what every one of the four
/// production parents already satisfies through the shared
/// substrate-wide impls — any implementor that fails the compound's
/// bounds would ALSO fail the individual sub-assertions' bounds,
/// so the compound doesn't shrink the reachable set of
/// implementors relative to hand-authoring the four sibling calls.
/// The `single_slot` closure is dispatched to
/// [`assert_variant_round_trip`] by reference so the compound can
/// re-dispatch it to [`assert_single_slot_key_matches_label`] by
/// value on the final call — a caller passes ONE `Fn(T::Kind) -> T`
/// factory (not `FnOnce`) at the two axes that need it.
///
/// `#[track_caller]` on both the compound and each sub-primitive,
/// so a sub-assertion panic surfaces at the compound's caller site
/// with the failing axis's exact panic-message substring
/// (e.g. "TaggedUnion KIND_LIST drift", "select→variant_kind
/// round-trip failed", "should resolve Ambiguous", "wire-key
/// drift"). The four sub-assertions stay independently callable —
/// a future parent that publishes only three of the four axes (a
/// wire-format-less runtime parent, e.g., or an
/// ambiguity-less parent whose `.variant()` short-circuits on
/// the first populated slot) still binds through the sibling
/// primitives individually.
///
/// A future FIFTH parent-side projection (e.g. a
/// `two_slots_have_stable_diagnostic` axis if the ambiguity error
/// gains a per-parent operator-facing message, or a
/// `variant_kind_stays_stable_across_generation` axis if the
/// resolver's iteration order becomes load-bearing) lands as ONE
/// new `assert_<axis>::<T, _>(...)` substrate primitive + ONE new
/// line inside this compound's body. Every one of the four
/// production parents picks up the fifth-axis alignment check
/// mechanically at their sole
/// `assert_tagged_union_convention_panel::<T, _, _>(single_slot,
/// two_slot)` call site — no per-parent test-site authoring, no
/// per-crate test-site drop pathway where 3 sibling call sites
/// carry the check and the 4th forgets. The exact promise the
/// child-side [`assert_closed_set_convention_panel`] compound's
/// docstring named on the child axis, extended here to the parent
/// axis: a workspace-wide panel with byte-identical calling shapes
/// (`assert_<compound>::<T, _, _>(single_slot, two_slot)`) that
/// composes as freely as its sub-primitives.
///
/// The [`crate::lifetime::Lifetime`] site is DELIBERATELY excluded
/// through the `T: TaggedUnion` bound — `Lifetime`'s `variant()`
/// returns `Ok(Permanent)` on empty rather than an `Empty` typed
/// error, so its projection shape diverges from the four
/// Empty-projecting parents. Same reasoning as [`resolve_or_err`]'s
/// / [`assert_variant_round_trip`]'s / [`assert_two_slots_ambiguous`]'s
/// / [`assert_single_slot_key_matches_label`]'s exclusions.
///
/// Theory anchor: THEORY.md §V.1 (knowable platform) — the
/// four-axis parent-side tagged-union convention becomes ONE typed
/// theorem provable generically over any
/// `T: TaggedUnion + Serialize` bound rather than FOUR
/// hand-authored per-parent tests held coherent by test-module
/// convention. THEORY.md §II.1 invariant 5 (composition preserves
/// proofs) — the four sub-assertions compose structurally through
/// ONE primitive here, so a regression at ONE axis surfaces at the
/// sub-assertion's own panic message rather than as silent drift
/// at every parent that might otherwise forget to include the
/// axis in its per-site author-time enumeration.
#[track_caller]
pub fn assert_tagged_union_convention_panel<T, F1, F2>(single_slot: F1, two_slot: F2)
where
T: TaggedUnion + serde::Serialize,
T::Kind: PartialEq + std::fmt::Debug,
T::Error: PartialEq + std::fmt::Debug,
F1: Fn(T::Kind) -> T,
F2: Fn(T::Kind, T::Kind) -> T,
{
assert_kind_list_matches_closed_set::<T>();
assert_variant_round_trip::<T, _>(&single_slot);
assert_two_slots_ambiguous::<T, _>(two_slot);
assert_has_matches_select::<T, _>(&single_slot);
assert_find_agrees_with_has::<T, _>(&single_slot);
assert_single_slot_key_matches_label::<T, _>(single_slot);
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum V {
A,
B,
C,
}
#[test]
fn empty_candidate_list_is_none() {
let r: Result<V, _> = resolve(std::iter::empty());
assert_eq!(r.unwrap_err(), ResolveError::None);
}
#[test]
fn all_none_is_none() {
let r: Result<V, _> = resolve([None, None, None]);
assert_eq!(r.unwrap_err(), ResolveError::None);
}
#[test]
fn single_some_is_resolved_regardless_of_position() {
assert_eq!(resolve([Some(V::A), None, None]).unwrap(), V::A);
assert_eq!(resolve([None, Some(V::B), None]).unwrap(), V::B);
assert_eq!(resolve([None, None, Some(V::C)]).unwrap(), V::C);
}
#[test]
fn two_or_more_some_is_many() {
assert_eq!(
resolve([Some(V::A), Some(V::B), None]).unwrap_err(),
ResolveError::Many
);
assert_eq!(
resolve([Some(V::A), None, Some(V::C)]).unwrap_err(),
ResolveError::Many
);
assert_eq!(
resolve([None, Some(V::B), Some(V::C)]).unwrap_err(),
ResolveError::Many
);
assert_eq!(
resolve([Some(V::A), Some(V::B), Some(V::C)]).unwrap_err(),
ResolveError::Many
);
}
/// Short-circuit invariant: once `Many` is decided, the sweep does
/// NOT inspect further candidates. Encode it as a side-effect probe.
#[test]
fn many_short_circuits_after_second_some() {
let mut visited = 0usize;
let candidates = (0..4).map(|i| {
visited += 1;
// first two are Some, the rest would be Some too if we got there.
Some(i)
});
// We can't actually consume `visited` here because it's borrowed in
// the closure — fold the count via the resolver's short-circuit.
let _ = resolve(candidates);
// The resolver evaluates the iterator lazily up to the second
// Some — index 0 (found = Some(0)), index 1 (Many → return).
assert_eq!(visited, 2);
}
/// The helper is value-agnostic — works with borrowed enum-view
/// types matching the actual on-the-typescape callsites.
#[test]
fn works_with_borrowed_enum_view() {
#[derive(Debug, PartialEq)]
enum View<'a> {
X(&'a u32),
Y(&'a String),
}
let x = 7u32;
let r = resolve([Some(View::X(&x)), None]).unwrap();
assert_eq!(r, View::X(&7));
}
/// Local sibling-shaped carrier used to pin the trait +
/// [`resolve_or_err`] dispatch without depending on the
/// crate's real error types.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum E {
Empty(&'static str),
Ambiguous,
}
impl TaggedUnionError for E {
fn empty(kinds: &'static str) -> Self {
E::Empty(kinds)
}
fn ambiguous() -> Self {
E::Ambiguous
}
}
/// Four-outcome truth table at the compound-lift boundary.
/// Pins that the two failure arms of [`resolve`] project onto
/// the trait's two typed constructors byte-identically, and
/// that the Ok arm falls through untouched.
#[test]
fn resolve_or_err_dispatches_each_arm_through_the_trait() {
const KINDS: &str = "a/b/c";
assert_eq!(
resolve_or_err::<V, E>([Some(V::A), None, None], KINDS).unwrap(),
V::A
);
assert_eq!(
resolve_or_err::<V, E>([None, Some(V::B), None], KINDS).unwrap(),
V::B
);
assert_eq!(
resolve_or_err::<V, E>([None, None, None], KINDS).unwrap_err(),
E::Empty(KINDS)
);
assert_eq!(
resolve_or_err::<V, E>([Some(V::A), Some(V::B), None], KINDS).unwrap_err(),
E::Ambiguous
);
}
/// The trait's Empty arm carries the &'static str the caller
/// hands `resolve_or_err`, verbatim — a rename at the caller's
/// `KINDS` constant reaches the diagnostic surface intact.
#[test]
fn resolve_or_err_empty_carries_the_caller_kinds_verbatim() {
const KINDS_ALPHA: &str = "alpha/beta";
const KINDS_GAMMA: &str = "gamma/delta/epsilon";
assert_eq!(
resolve_or_err::<V, E>([None, None], KINDS_ALPHA).unwrap_err(),
E::Empty(KINDS_ALPHA)
);
assert_eq!(
resolve_or_err::<V, E>([None, None, None], KINDS_GAMMA).unwrap_err(),
E::Empty(KINDS_GAMMA)
);
}
/// The compound-lift preserves [`resolve`]'s short-circuit at
/// the Many arm — a third-and-later candidate is not
/// inspected once the second populated entry is seen.
#[test]
fn resolve_or_err_short_circuits_on_many() {
let mut visited = 0usize;
let candidates = (0..4).map(|i| {
visited += 1;
Some(i)
});
let _ = resolve_or_err::<i32, E>(candidates, "irrelevant");
assert_eq!(visited, 2);
}
// -------------------------------------------------------------------
// `declare_tagged_union_error!` macro-emitted carrier — pins the
// shape a fifth sibling would land through the macro instead of
// hand-rolling the enum + `impl TaggedUnionError` block.
// -------------------------------------------------------------------
crate::declare_tagged_union_error! {
pub(super) MacroEmittedError,
empty = "test carrier has no variant set (one of {0} required)",
ambiguous = "test carrier has multiple variants set; exactly one required",
}
/// The macro-emitted carrier's [`TaggedUnionError`] impl dispatches
/// the same four-outcome truth table [`resolve_or_err`] pins for a
/// hand-rolled carrier — pins that swapping a hand-rolled carrier
/// for a macro-emitted one preserves the compound-lift's projection
/// byte-identically.
#[test]
fn macro_emitted_carrier_projects_through_resolve_or_err() {
const KINDS: &str = "one/two/three";
assert_eq!(
resolve_or_err::<V, MacroEmittedError>([Some(V::A), None, None], KINDS).unwrap(),
V::A
);
assert_eq!(
resolve_or_err::<V, MacroEmittedError>([None, None, None], KINDS).unwrap_err(),
MacroEmittedError::Empty(KINDS)
);
assert_eq!(
resolve_or_err::<V, MacroEmittedError>([Some(V::A), Some(V::B), None], KINDS)
.unwrap_err(),
MacroEmittedError::Ambiguous
);
}
/// The macro-emitted carrier's `#[error(...)]` messages render the
/// two operator-facing diagnostic strings the caller handed the
/// macro, verbatim — a rename at the caller's literal reaches the
/// operator diagnostic surface intact.
#[test]
fn macro_emitted_carrier_display_renders_caller_literals_verbatim() {
assert_eq!(
MacroEmittedError::Empty("alpha/beta").to_string(),
"test carrier has no variant set (one of alpha/beta required)",
);
assert_eq!(
MacroEmittedError::Ambiguous.to_string(),
"test carrier has multiple variants set; exactly one required",
);
}
/// The macro-emitted carrier is `Copy` — a substrate-wide promise
/// pinned by the macro's `#[derive(..., Copy, ...)]` header so a
/// consumer treating the carrier as a value type (memcpy-cheap
/// return, `.copied()` on an `Option<&E>`) stays valid across every
/// carrier the macro emits.
#[test]
fn macro_emitted_carrier_is_copy() {
fn assert_copy<T: Copy>() {}
assert_copy::<MacroEmittedError>();
}
// -------------------------------------------------------------------
// `TaggedUnion` trait — declarative surface pinning the
// (Kind, Error, KIND_LIST) triple. `assert_kind_list_matches_closed_set`
// is the generic diagnostic-stability testkit primitive shared by
// every implementor's `_error_empty_lists_every_kind_in_canonical_order`
// site.
// -------------------------------------------------------------------
/// Local sibling-shaped Kind enum used to pin the trait's
/// diagnostic-stability primitive without depending on the crate's
/// four production tagged unions. Uses [`tatara_closed_set::DeriveClosedSet`]
/// so `<Self as ClosedSet>::labels_joined("/")` reaches the same
/// substrate composition the four production sites bind through.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, tatara_closed_set::DeriveClosedSet)]
#[closed_set(via = "as_str", generate_unknown, display)]
enum LocalKind {
Alpha,
Beta,
Gamma,
}
impl LocalKind {
const ALL: [Self; 3] = [Self::Alpha, Self::Beta, Self::Gamma];
const fn as_str(self) -> &'static str {
match self {
Self::Alpha => "alpha",
Self::Beta => "beta",
Self::Gamma => "gamma",
}
}
}
/// Local parent type — impls [`TaggedUnion`] with a `KIND_LIST`
/// literal that matches the canonical `<LocalKind as
/// ClosedSet>::labels_joined("/")` projection. Carries three
/// `Option<u32>` slots so the substrate-primitive
/// [`TaggedUnion::variant`] default method can be exercised
/// directly on a sibling-shaped-but-crate-local parent, isolated
/// from the four production tagged unions.
///
/// Derives [`serde::Serialize`] with `skip_serializing_if =
/// "Option::is_none"` on every slot so the wire-format primitive
/// [`assert_single_slot_key_matches_label`] can be exercised
/// directly against the sibling-shaped scaffold — mirrors the
/// `#[serde(default, skip_serializing_if = "Option::is_none")]`
/// annotation every one of the four production tagged unions
/// carries on its own slots.
#[derive(Default, serde::Serialize)]
struct LocalParent {
#[serde(skip_serializing_if = "Option::is_none")]
alpha: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
beta: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
gamma: Option<u32>,
}
/// Borrowed-view of a populated slot on [`LocalParent`] — the
/// return type of [`LocalKind::select`] and the substrate-primitive
/// [`TaggedUnion::variant`] default on `LocalParent`.
#[derive(Debug, PartialEq)]
enum LocalVariant<'a> {
Alpha(&'a u32),
Beta(&'a u32),
Gamma(&'a u32),
}
impl VariantSelector<LocalParent> for LocalKind {
type Variant<'a> = LocalVariant<'a>;
fn select<'a>(self, parent: &'a LocalParent) -> Option<LocalVariant<'a>>
where
Self: 'a,
{
match self {
Self::Alpha => parent.alpha.as_ref().map(LocalVariant::Alpha),
Self::Beta => parent.beta.as_ref().map(LocalVariant::Beta),
Self::Gamma => parent.gamma.as_ref().map(LocalVariant::Gamma),
}
}
}
impl VariantKind<LocalKind> for LocalVariant<'_> {
fn variant_kind(&self) -> LocalKind {
match self {
Self::Alpha(_) => LocalKind::Alpha,
Self::Beta(_) => LocalKind::Beta,
Self::Gamma(_) => LocalKind::Gamma,
}
}
}
crate::declare_tagged_union_error! {
pub(super) LocalParentError,
empty = "local carrier has no variant set (one of {0} required)",
ambiguous = "local carrier has multiple variants set; exactly one required",
}
impl TaggedUnion for LocalParent {
type Kind = LocalKind;
type Error = LocalParentError;
const KIND_LIST: &'static str = "alpha/beta/gamma";
}
/// The testkit primitive resolves the canonical join of every
/// `LocalKind` variant's label against the trait's `KIND_LIST`
/// constant byte-identically — the four production sites bind
/// through this exact dispatch. The Ok arm is the "no drift"
/// outcome; a divergence surfaces as a labeled assertion failure.
#[test]
fn assert_kind_list_matches_closed_set_accepts_coherent_impl() {
assert_kind_list_matches_closed_set::<LocalParent>();
}
/// The testkit primitive is a `#[track_caller]` compound-lift:
/// a drift between `<T::Kind as ClosedSet>::labels_joined("/")`
/// and `T::KIND_LIST` fails the assertion at the caller's site,
/// not inside the primitive body. Pin the failing case with a
/// local parent whose `KIND_LIST` is deliberately mis-authored
/// (a variant reorder), so a regression that drops the drift
/// detection fails-loudly here.
#[test]
#[should_panic(expected = "TaggedUnion KIND_LIST drift")]
fn assert_kind_list_matches_closed_set_rejects_drifted_impl() {
struct Drifted;
// The `TaggedUnion` trait bounds `Kind: VariantSelector<Self>`
// with `Variant<'a>: VariantKind<Self>`; the drift test only
// exercises `assert_kind_list_matches_closed_set` (which reaches
// the (Kind, KIND_LIST) pair, not the sweep body), so reusing
// the sibling `LocalVariant<'a>` (with its already-load-bearing
// `impl VariantKind<LocalKind>`) + always-`None` `select`
// satisfies both bounds without wiring a real projection.
impl VariantSelector<Drifted> for LocalKind {
type Variant<'a> = LocalVariant<'a>;
fn select<'a>(self, _: &'a Drifted) -> Option<LocalVariant<'a>>
where
Self: 'a,
{
None
}
}
impl TaggedUnion for Drifted {
type Kind = LocalKind;
type Error = LocalParentError;
// Deliberate drift — canonical join is "alpha/beta/gamma".
const KIND_LIST: &'static str = "beta/alpha/gamma";
}
assert_kind_list_matches_closed_set::<Drifted>();
}
/// Every one of the four production `.variant()` sites on
/// `ProcessSpec` impls [`TaggedUnion`] with `KIND_LIST` reaching
/// the substrate primitive `assert_kind_list_matches_closed_set`
/// coherently. Sweep every production implementor at ONE
/// substrate boundary so a regression that drifts a production
/// site's `KIND_LIST` (or renames a `Kind` variant without
/// updating the constant) fails BOTH at the per-crate test site
/// AND at this substrate-wide sweep — no per-implementor test
/// site can drop the check silently.
#[test]
fn every_production_tagged_union_binds_through_the_testkit_primitive() {
assert_kind_list_matches_closed_set::<crate::intent::Intent>();
assert_kind_list_matches_closed_set::<crate::encapsulates::EncapsulationKind>();
assert_kind_list_matches_closed_set::<crate::export::ArtifactSource>();
assert_kind_list_matches_closed_set::<crate::export::VectorChannel>();
}
/// Every one of the four production `.variant()` sites on
/// `ProcessSpec` binds through the wire-key primitive
/// [`assert_single_slot_key_matches_label`] coherently — every
/// per-site `single_slot_X(k)` factory serializes to a JSON object
/// with EXACTLY ONE key whose name equals `k.label()` (delegating
/// to each Kind's inherent `as_str`, matching the parent's serde
/// `rename_all = "camelCase"` projection). Sweep every production
/// implementor at ONE substrate boundary so a regression that
/// drifts a production site's `single_slot_X` factory (populates
/// the wrong slot; leaks residual slots between calls) OR the
/// parent's field-to-kind alignment (`as_str` returns "receipts"
/// but the field is named `receipt`) fails BOTH at the per-crate
/// test site AND at this substrate-wide sweep — no per-implementor
/// test site can drop the check silently.
#[test]
fn every_production_tagged_union_binds_through_the_wire_key_testkit_primitive() {
assert_single_slot_key_matches_label::<crate::intent::Intent, _>(single_slot_intent_probe);
assert_single_slot_key_matches_label::<crate::encapsulates::EncapsulationKind, _>(
single_slot_encapsulation_kind_probe,
);
assert_single_slot_key_matches_label::<crate::export::ArtifactSource, _>(
single_slot_artifact_source_probe,
);
assert_single_slot_key_matches_label::<crate::export::VectorChannel, _>(
single_slot_vector_channel_probe,
);
}
/// The parent-side four-axis compound-lift dispatches Ok on a
/// coherent implementor — the [`LocalParent`] scaffold publishes
/// every axis (`TaggedUnion` via
/// [`crate::declare_tagged_union_error`]-emitted `LocalParentError`
/// + Serialize via `#[derive(serde::Serialize)]` +
/// `LocalKind: PartialEq + Debug` +
/// `LocalParentError: PartialEq + Debug`), matching the
/// substrate-wide four-axis convention every one of the four
/// production parents carries. The Ok arm is the "no drift"
/// outcome; a divergence at ANY sub-assertion's composition
/// inside the compound (accidentally dropped, silently reordered,
/// or short-circuited) surfaces at the sub-primitive's own
/// panic message (each sub-primitive is `#[track_caller]`), and
/// the per-axis failing arms are pinned by the sibling
/// `#[should_panic]` probes already at the per-axis primitive
/// layer (`assert_kind_list_matches_closed_set_rejects_drifted_impl`,
/// `assert_variant_round_trip_rejects_factory_that_leaves_slot_empty`,
/// `assert_two_slots_ambiguous_rejects_factory_that_populates_only_one_slot`,
/// `assert_single_slot_key_matches_label_rejects_factory_that_populates_wrong_slot`).
/// Re-authoring per-axis drift probes at the compound layer
/// would restate the SAME four axis-typed contracts through a
/// compound wrapper without adding a new gate.
#[test]
fn assert_tagged_union_convention_panel_accepts_coherent_local_impl() {
fn single_slot(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(11),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(22),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(33),
..Default::default()
},
}
}
fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
let mut p = LocalParent::default();
for k in [a, b] {
match k {
LocalKind::Alpha => p.alpha = Some(11),
LocalKind::Beta => p.beta = Some(22),
LocalKind::Gamma => p.gamma = Some(33),
}
}
p
}
assert_tagged_union_convention_panel::<LocalParent, _, _>(single_slot, two_slot);
}
/// Every one of the four production `.variant()` parents on
/// `ProcessSpec` binds through the four-axis convention-panel
/// primitive [`assert_tagged_union_convention_panel`] coherently.
/// Sweep every production parent at ONE substrate boundary so a
/// regression that (a) drops ANY of the four sub-assertions from
/// the compound's body, (b) reorders them in a way that skips
/// one on Ok, (c) silently binds the compound against a
/// hollowed-out sub-assertion body, or (d) drifts a substrate-
/// local `{single,two}_slot_*_probe` fixture (populates the
/// wrong slot; leaks residual slots between calls; the `.or()`
/// composition drops a slot on the two-slot side) fails BOTH at
/// the per-crate test site AND at this substrate-wide sweep.
///
/// Pinned in lock-step with the sibling
/// `every_production_tagged_union_binds_through_the_testkit_primitive`
/// (KIND_LIST axis) and
/// `every_production_tagged_union_binds_through_the_wire_key_testkit_primitive`
/// (wire-key axis) sweeps — every parent enumerated below is a
/// member of BOTH sibling sweeps (their bounds are strict
/// subsets of the compound's `T: TaggedUnion + Serialize` +
/// `T::Kind: PartialEq + Debug` + `T::Error: PartialEq + Debug`
/// bound), and every parent additionally publishes both a
/// substrate-local `single_slot_*_probe` and a
/// substrate-local `two_slot_*_probe` peer above. Post-sweep the
/// substrate-wide four-axis parent-side convention-panel
/// discipline is a property of the workspace, not a per-file
/// convention — even before any per-site test-body sweep
/// collapses the four per-parent sibling tests into ONE compound
/// call each.
#[test]
fn every_production_tagged_union_binds_through_the_convention_panel_testkit_primitive() {
assert_tagged_union_convention_panel::<crate::intent::Intent, _, _>(
single_slot_intent_probe,
two_slot_intent_probe,
);
assert_tagged_union_convention_panel::<crate::encapsulates::EncapsulationKind, _, _>(
single_slot_encapsulation_kind_probe,
two_slot_encapsulation_kind_probe,
);
assert_tagged_union_convention_panel::<crate::export::ArtifactSource, _, _>(
single_slot_artifact_source_probe,
two_slot_artifact_source_probe,
);
assert_tagged_union_convention_panel::<crate::export::VectorChannel, _, _>(
single_slot_vector_channel_probe,
two_slot_vector_channel_probe,
);
}
/// The Display / label alignment primitive dispatches Ok on a
/// coherent implementor — the [`LocalKind`] scaffold derives
/// `Display` from `label` via `#[closed_set(via = "as_str",
/// display)]`, matching the substrate-wide derive shape every
/// production implementor across the crate carries. The Ok arm
/// is the "no drift" outcome; a divergence surfaces as a labeled
/// assertion failure at the caller site (this test's own line).
#[test]
fn assert_display_matches_label_accepts_coherent_impl() {
assert_display_matches_label::<LocalKind>();
}
/// A local closed-set scaffold whose `Display` deliberately
/// diverges from `label` — pins the failing arm of the primitive.
/// The `#[closed_set(via = "as_str")]` attribute WITHOUT `display`
/// leaves the `Display` impl uncovered by the derive, and the
/// hand-authored `impl Display` below emits a suffixed rendering
/// that no `label` projection returns. A regression that drops
/// the alignment assertion inside
/// [`assert_display_matches_label`] fails-loudly at this
/// `#[should_panic]` probe before it can silently thread through
/// the 29 production `X_display_matches_as_str` sites.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, tatara_closed_set::DeriveClosedSet)]
#[closed_set(via = "as_str", generate_unknown)]
enum DisplayDriftKind {
Alpha,
Beta,
}
impl DisplayDriftKind {
const ALL: [Self; 2] = [Self::Alpha, Self::Beta];
const fn as_str(self) -> &'static str {
match self {
Self::Alpha => "alpha",
Self::Beta => "beta",
}
}
}
impl std::fmt::Display for DisplayDriftKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// Deliberate drift — Display suffixes the label with a
// marker no `label` projection returns.
write!(f, "{}!", self.as_str())
}
}
#[test]
#[should_panic(expected = "Display drifted from ClosedSet::label")]
fn assert_display_matches_label_rejects_drifted_impl() {
assert_display_matches_label::<DisplayDriftKind>();
}
/// Every closed-set enum across `tatara-process` that carried a
/// hand-rolled `X_display_matches_as_str` test pre-lift now binds
/// through the substrate primitive at ONE call site each. This
/// substrate-wide sweep pins every production Display-alignment
/// consumer at ONE boundary so a per-crate test-site drop cannot
/// silently disable the check — the sweep here catches the drift
/// even when the per-site test body is removed. Mirrors the
/// `every_production_tagged_union_binds_through_the_testkit_primitive`
/// and `every_production_tagged_union_binds_through_the_wire_key_testkit_primitive`
/// sibling sweeps on the (`KIND_LIST` slash-join, wire-key)
/// axes; this one closes the (`Display` byte-identity) axis.
#[test]
fn every_production_display_impl_binds_through_the_testkit_primitive() {
assert_display_matches_label::<crate::allocation::AllocationPhase>();
assert_display_matches_label::<crate::boundary::ConditionKind>();
assert_display_matches_label::<crate::classification::Arity>();
assert_display_matches_label::<crate::classification::CalmClassification>();
assert_display_matches_label::<crate::classification::ConvergencePointType>();
assert_display_matches_label::<crate::classification::DataClassification>();
assert_display_matches_label::<crate::classification::HorizonKind>();
assert_display_matches_label::<crate::classification::OptimizationDirection>();
assert_display_matches_label::<crate::classification::SubstrateType>();
assert_display_matches_label::<crate::compliance::VerificationPhase>();
assert_display_matches_label::<crate::encapsulates::EncapsulationMode>();
assert_display_matches_label::<crate::encapsulates::EncapsulationTarget>();
assert_display_matches_label::<crate::export::ArtifactKind>();
assert_display_matches_label::<crate::export::ChannelKind>();
assert_display_matches_label::<crate::export::ExportTrigger>();
assert_display_matches_label::<crate::export::ReportFormat>();
assert_display_matches_label::<crate::export::ReportPayloadShape>();
assert_display_matches_label::<crate::intent::IntentKind>();
assert_display_matches_label::<crate::intent::WorkloadKind>();
assert_display_matches_label::<crate::lifetime::LifetimeKind>();
assert_display_matches_label::<crate::lifetime::TeardownPolicy>();
assert_display_matches_label::<crate::lifetime_clock::AutoTerminateKind>();
assert_display_matches_label::<crate::lifetime_clock::TerminateReasonKind>();
assert_display_matches_label::<crate::matrix::SelectStrategyKind>();
assert_display_matches_label::<crate::pool::MemberState>();
assert_display_matches_label::<crate::pool::PoolPhase>();
assert_display_matches_label::<crate::pool::ReplacementPolicy>();
assert_display_matches_label::<crate::pool::ReturnPolicy>();
assert_display_matches_label::<crate::signal::SighupStrategy>();
assert_display_matches_label::<crate::spec::MustReachPhase>();
}
/// Local closed-set scaffold whose serde `rename_all = "lowercase"`
/// projection matches its `via = "as_str"` label byte-identically —
/// pins the Ok arm of the wire-format primitive. Every production
/// implementor across the crate carries the substrate-wide
/// `#[closed_set(via = "as_str")]` + `#[serde(rename_all = ...)]`
/// pair whose alignment this scaffold pins on the sibling-shaped
/// local surface.
#[derive(
Clone,
Copy,
Debug,
PartialEq,
Eq,
Hash,
serde::Serialize,
tatara_closed_set::DeriveClosedSet,
)]
#[serde(rename_all = "lowercase")]
#[closed_set(via = "as_str", generate_unknown)]
enum SerdeAlignedKind {
Alpha,
Beta,
}
impl SerdeAlignedKind {
const ALL: [Self; 2] = [Self::Alpha, Self::Beta];
const fn as_str(self) -> &'static str {
match self {
Self::Alpha => "alpha",
Self::Beta => "beta",
}
}
}
#[test]
fn assert_label_matches_serde_serialization_accepts_coherent_impl() {
assert_label_matches_serde_serialization::<SerdeAlignedKind>();
}
/// A local closed-set scaffold whose serde output deliberately
/// diverges from `label` — pins the failing arm of the wire-format
/// primitive. The `#[serde(rename_all = "UPPERCASE")]` projection
/// emits uppercase JSON strings while the `via = "as_str"` label
/// stays lowercase. A regression that drops the alignment assertion
/// inside [`assert_label_matches_serde_serialization`] fails-loudly
/// at this `#[should_panic]` probe before it can silently thread
/// through the 20 production `X_as_str_matches_serde` sites.
#[derive(
Clone,
Copy,
Debug,
PartialEq,
Eq,
Hash,
serde::Serialize,
tatara_closed_set::DeriveClosedSet,
)]
#[serde(rename_all = "UPPERCASE")]
#[closed_set(via = "as_str", generate_unknown)]
enum SerdeDriftKind {
Alpha,
Beta,
}
impl SerdeDriftKind {
const ALL: [Self; 2] = [Self::Alpha, Self::Beta];
const fn as_str(self) -> &'static str {
match self {
Self::Alpha => "alpha",
Self::Beta => "beta",
}
}
}
#[test]
#[should_panic(expected = "serde output drifted from ClosedSet::label")]
fn assert_label_matches_serde_serialization_rejects_drifted_impl() {
assert_label_matches_serde_serialization::<SerdeDriftKind>();
}
/// Local closed-set scaffold whose ALL THREE axes of the label-
/// surface convention align by construction — pins the Ok arm of
/// the compound-panel primitive.
///
/// `#[serde(rename_all = "lowercase")]` matches the `via = "as_str"`
/// labels byte-identically (the serde-alignment axis). The
/// `display` sub-attribute on `#[closed_set(via = "as_str",
/// display)]` derives `impl Display` from the same `as_str`
/// projection (the Display-alignment axis). The `generate_unknown`
/// sub-attribute emits the `T::Unknown` carrier the round-trip
/// axis's `parse_label` returns on unknown input. Together these
/// three attributes stamp the substrate-wide derive shape every
/// production 3-axis-panel consumer carries; a caller that lands
/// through this scaffold satisfies EVERY bound the compound's
/// where-clause names.
///
/// Peer to the sibling per-axis fixtures [`LocalKind`] (Display
/// axis, no serde) and [`SerdeAlignedKind`] (serde axis, no
/// Display) on the label-surface primitive family; this fixture
/// closes the diagonal by carrying both attribute-sets at once,
/// so a regression at ANY sub-assertion's composition inside the
/// compound (the compound accidentally dropping the well-formed
/// call, silently reordering the three calls, wrapping them in a
/// short-circuit that skips the middle one on Ok, …) fails the
/// compound's happy-path pin below rather than as silent drift at
/// every 3-axis consumer.
#[derive(
Clone,
Copy,
Debug,
PartialEq,
Eq,
Hash,
serde::Serialize,
tatara_closed_set::DeriveClosedSet,
)]
#[serde(rename_all = "lowercase")]
#[closed_set(via = "as_str", generate_unknown, display)]
enum PanelAlignedKind {
Alpha,
Beta,
}
impl PanelAlignedKind {
const ALL: [Self; 2] = [Self::Alpha, Self::Beta];
const fn as_str(self) -> &'static str {
match self {
Self::Alpha => "alpha",
Self::Beta => "beta",
}
}
}
/// The compound-panel primitive dispatches Ok on a coherent
/// implementor — [`PanelAlignedKind`] carries every attribute the
/// substrate-wide 3-axis derive shape publishes, so all three
/// sub-assertions the compound composes (well-formed, Display /
/// label, serde / label) pass by construction. The Ok arm is the
/// "no drift on any axis" outcome; a divergence at any single
/// sub-assertion surfaces as that sub-assertion's own labeled
/// panic message (with the caller-attributed line via
/// `#[track_caller]` on both the compound and its sub-
/// primitives), NOT as a silent pass.
///
/// The per-axis failing arms are pinned by the sibling per-axis
/// #[should_panic] probes above:
/// - the round-trip axis's failing arm is pinned by
/// [`tatara_closed_set::assert_closed_set_well_formed`]'s own
/// `#[should_panic]` probe in the `tatara-closed-set` crate;
/// - the Display axis's failing arm is pinned by
/// [`assert_display_matches_label_rejects_drifted_impl`] on
/// [`DisplayDriftKind`];
/// - the serde axis's failing arm is pinned by
/// [`assert_label_matches_serde_serialization_rejects_drifted_impl`]
/// on [`SerdeDriftKind`].
/// Each per-axis drift fixture already surfaces its axis's exact
/// panic-message substring, so re-authoring per-axis
/// `#[should_panic]` probes at the compound layer would restate
/// the SAME three axis-typed contracts through a compound
/// wrapper — one more copy of the same three pins, not a new
/// gate. The compound's happy-path pin here suffices to verify
/// the composition doesn't lose ANY sub-assertion (a regression
/// that swallows one axis silently would still fail the sibling
/// sub-assertion's own drift probe on the drift fixture).
#[test]
fn assert_closed_set_convention_panel_accepts_coherent_impl() {
assert_closed_set_convention_panel::<PanelAlignedKind>();
}
/// Every closed-set enum across `tatara-process` that publishes
/// ALL THREE axes of the label-surface convention (well-formed +
/// Display-alignment + serde-alignment) now binds through the
/// substrate compound-panel primitive at ONE call site each in
/// this sweep. Pinned in lock-step with the sibling
/// `every_production_serde_serialization_binds_through_the_testkit_primitive`
/// sweep — every enum enumerated below is a member of BOTH sweeps
/// (the compound's `T: Serialize + Display + ClosedSet + ...`
/// bound is a strict superset of `assert_label_matches_serde_
/// serialization`'s `T: ClosedSet + Serialize + Debug` bound, and
/// the 20 wire-format consumers all additionally impl Display via
/// `#[closed_set(via = "as_str", display)]`).
///
/// A regression that (a) drops the compound's `assert_closed_set_
/// well_formed` dispatch, (b) reorders the three sub-assertions
/// in a way that skips one on Ok, or (c) silently binds the
/// compound against a hollowed-out sub-assertion body catches
/// here at the substrate-wide boundary — the sweep pins every
/// production 3-axis consumer's compound-panel discipline through
/// ONE test even before any per-site test-body sweep collapses
/// the three per-enum sibling tests into ONE compound call each.
/// Post-sweep the substrate-wide compound-panel discipline is a
/// property of the workspace, not a per-file convention.
#[test]
fn every_production_convention_panel_binds_through_the_testkit_primitive() {
assert_closed_set_convention_panel::<crate::allocation::AllocationPhase>();
assert_closed_set_convention_panel::<crate::boundary::ConditionKind>();
assert_closed_set_convention_panel::<crate::classification::CalmClassification>();
assert_closed_set_convention_panel::<crate::classification::ConvergencePointType>();
assert_closed_set_convention_panel::<crate::classification::DataClassification>();
assert_closed_set_convention_panel::<crate::classification::HorizonKind>();
assert_closed_set_convention_panel::<crate::classification::OptimizationDirection>();
assert_closed_set_convention_panel::<crate::classification::SubstrateType>();
assert_closed_set_convention_panel::<crate::compliance::VerificationPhase>();
assert_closed_set_convention_panel::<crate::encapsulates::EncapsulationMode>();
assert_closed_set_convention_panel::<crate::export::ExportTrigger>();
assert_closed_set_convention_panel::<crate::export::ReportFormat>();
assert_closed_set_convention_panel::<crate::intent::WorkloadKind>();
assert_closed_set_convention_panel::<crate::lifetime::TeardownPolicy>();
assert_closed_set_convention_panel::<crate::pool::MemberState>();
assert_closed_set_convention_panel::<crate::pool::PoolPhase>();
assert_closed_set_convention_panel::<crate::pool::ReplacementPolicy>();
assert_closed_set_convention_panel::<crate::pool::ReturnPolicy>();
assert_closed_set_convention_panel::<crate::signal::SighupStrategy>();
assert_closed_set_convention_panel::<crate::spec::MustReachPhase>();
}
/// Every closed-set enum across `tatara-process` that carried a
/// hand-rolled `X_as_str_matches_serde` test pre-lift now binds
/// through the substrate primitive at ONE call site each. This
/// substrate-wide sweep pins every production wire-format alignment
/// consumer at ONE boundary so a per-crate test-site drop cannot
/// silently disable the check — the sweep here catches the drift
/// even when the per-site test body is removed. Mirrors the sibling
/// `every_production_display_impl_binds_through_the_testkit_primitive`
/// sweep on the (Display byte-identity) axis; this one closes the
/// (serde JSON-string byte-identity) axis.
#[test]
fn every_production_serde_serialization_binds_through_the_testkit_primitive() {
assert_label_matches_serde_serialization::<crate::allocation::AllocationPhase>();
assert_label_matches_serde_serialization::<crate::boundary::ConditionKind>();
assert_label_matches_serde_serialization::<crate::classification::CalmClassification>();
assert_label_matches_serde_serialization::<crate::classification::ConvergencePointType>();
assert_label_matches_serde_serialization::<crate::classification::DataClassification>();
assert_label_matches_serde_serialization::<crate::classification::HorizonKind>();
assert_label_matches_serde_serialization::<crate::classification::OptimizationDirection>();
assert_label_matches_serde_serialization::<crate::classification::SubstrateType>();
assert_label_matches_serde_serialization::<crate::compliance::VerificationPhase>();
assert_label_matches_serde_serialization::<crate::encapsulates::EncapsulationMode>();
assert_label_matches_serde_serialization::<crate::export::ExportTrigger>();
assert_label_matches_serde_serialization::<crate::export::ReportFormat>();
assert_label_matches_serde_serialization::<crate::intent::WorkloadKind>();
assert_label_matches_serde_serialization::<crate::lifetime::TeardownPolicy>();
assert_label_matches_serde_serialization::<crate::pool::MemberState>();
assert_label_matches_serde_serialization::<crate::pool::PoolPhase>();
assert_label_matches_serde_serialization::<crate::pool::ReplacementPolicy>();
assert_label_matches_serde_serialization::<crate::pool::ReturnPolicy>();
assert_label_matches_serde_serialization::<crate::signal::SighupStrategy>();
assert_label_matches_serde_serialization::<crate::spec::MustReachPhase>();
}
// Substrate-local single-slot factories — mirror the per-site
// `single_slot_X` test helpers each production site owns, so the
// substrate-wide sweep above binds through the wire-key primitive
// without reaching across the per-crate test-module boundaries the
// per-site helpers are scoped to. The primitive only requires that
// the addressed slot on the parent is populated; the inner spec's
// exact field values are irrelevant to the wire-key check.
fn single_slot_intent_probe(kind: crate::intent::IntentKind) -> crate::intent::Intent {
use crate::intent::{
AplicacaoIntent, ContainerIntent, FluxIntent, GuestIntent, Intent, IntentKind,
LispIntent, NixIntent, WorkloadKind,
};
match kind {
IntentKind::Nix => Intent {
nix: Some(NixIntent {
flake_ref: "f".into(),
attribute: "a".into(),
system: None,
attic_cache: None,
extra_args: vec![],
delegate_to_nix_build: false,
}),
..Intent::default()
},
IntentKind::Flux => Intent {
flux: Some(FluxIntent {
git_repository: "g".into(),
path: "p".into(),
git_repository_namespace: None,
target_namespace: None,
decrypt_sops: true,
helm_chart: None,
helm_values: None,
}),
..Intent::default()
},
IntentKind::Lisp => Intent {
lisp: Some(LispIntent {
source: "()".into(),
reader: "tatara-lisp".into(),
version: "v1".into(),
bindings: std::collections::BTreeMap::new(),
}),
..Intent::default()
},
IntentKind::Container => Intent {
container: Some(ContainerIntent {
image: "x".into(),
replicas: None,
command: vec![],
args: vec![],
env: std::collections::BTreeMap::new(),
workload_kind: WorkloadKind::default(),
}),
..Intent::default()
},
IntentKind::Aplicacao => Intent {
aplicacao: Some(AplicacaoIntent::chart_only("x", "1")),
..Intent::default()
},
IntentKind::Guest => Intent {
guest: Some(GuestIntent {
spec: serde_json::json!({"name": "x"}),
state_dir: None,
allow_remote_build: None,
}),
..Intent::default()
},
}
}
fn single_slot_encapsulation_kind_probe(
target: crate::encapsulates::EncapsulationTarget,
) -> crate::encapsulates::EncapsulationKind {
use crate::encapsulates::{
BareWorkload, EncapsulationKind, EncapsulationTarget, ExistingHelmRelease,
ExistingKustomization,
};
match target {
EncapsulationTarget::ExistingHelmRelease => EncapsulationKind {
existing_helm_release: Some(ExistingHelmRelease {
namespace: "ns".into(),
name: "hr".into(),
release_name: "rel".into(),
}),
..EncapsulationKind::default()
},
EncapsulationTarget::ExistingKustomization => EncapsulationKind {
existing_kustomization: Some(ExistingKustomization {
namespace: "ns".into(),
name: "ks".into(),
}),
..EncapsulationKind::default()
},
EncapsulationTarget::BareWorkload => {
let mut sel = std::collections::BTreeMap::new();
sel.insert("app".into(), "x".into());
EncapsulationKind {
bare_workload: Some(BareWorkload {
namespace: "ns".into(),
selector: sel,
}),
..EncapsulationKind::default()
}
}
}
}
fn single_slot_artifact_source_probe(
kind: crate::export::ArtifactKind,
) -> crate::export::ArtifactSource {
use crate::export::{
ArtifactKind, ArtifactSource, ProcessSnapshotSource, ReceiptsSource, ReportFormat,
RunMarkerSource, TestReportSource,
};
match kind {
ArtifactKind::Receipts => ArtifactSource {
receipts: Some(ReceiptsSource::default()),
..ArtifactSource::default()
},
ArtifactKind::TestReport => ArtifactSource {
test_report: Some(TestReportSource {
configmap: "cm".into(),
key: "k".into(),
format: ReportFormat::Junit,
namespace: None,
}),
..ArtifactSource::default()
},
ArtifactKind::ProcessSnapshot => ArtifactSource {
process_snapshot: Some(ProcessSnapshotSource::default()),
..ArtifactSource::default()
},
ArtifactKind::RunMarker => ArtifactSource {
run_marker: Some(RunMarkerSource::default()),
..ArtifactSource::default()
},
}
}
fn single_slot_vector_channel_probe(
kind: crate::export::ChannelKind,
) -> crate::export::VectorChannel {
use crate::export::{
ChannelKind, HttpEventChannel, NatsSubjectChannel, StdoutChannel, VectorChannel,
};
match kind {
ChannelKind::HttpEvent => VectorChannel {
http_event: Some(HttpEventChannel::signal("x")),
..VectorChannel::default()
},
ChannelKind::NatsSubject => VectorChannel {
nats_subject: Some(NatsSubjectChannel::publish("s", "S")),
..VectorChannel::default()
},
ChannelKind::Stdout => VectorChannel {
stdout: Some(StdoutChannel::default()),
..VectorChannel::default()
},
}
}
// Substrate-local two-slot factories — peers to the sibling
// `single_slot_*_probe` block above. Each composes
// `single_slot_*_probe(a)` with `single_slot_*_probe(b)`
// through per-field `Option::or` on the parent's tagged-union
// slots, matching the shape every per-site `two_slot_X(a, b)`
// helper across the four production parents already carries.
// The ambiguity-primitive only requires that BOTH addressed
// slots on the parent are populated; the inner spec's exact
// field values are irrelevant to the two-slot ambiguity check.
fn two_slot_intent_probe(
a: crate::intent::IntentKind,
b: crate::intent::IntentKind,
) -> crate::intent::Intent {
let ia = single_slot_intent_probe(a);
let ib = single_slot_intent_probe(b);
crate::intent::Intent {
nix: ia.nix.or(ib.nix),
flux: ia.flux.or(ib.flux),
lisp: ia.lisp.or(ib.lisp),
container: ia.container.or(ib.container),
aplicacao: ia.aplicacao.or(ib.aplicacao),
guest: ia.guest.or(ib.guest),
}
}
fn two_slot_encapsulation_kind_probe(
a: crate::encapsulates::EncapsulationTarget,
b: crate::encapsulates::EncapsulationTarget,
) -> crate::encapsulates::EncapsulationKind {
let ka = single_slot_encapsulation_kind_probe(a);
let kb = single_slot_encapsulation_kind_probe(b);
crate::encapsulates::EncapsulationKind {
existing_helm_release: ka.existing_helm_release.or(kb.existing_helm_release),
existing_kustomization: ka.existing_kustomization.or(kb.existing_kustomization),
bare_workload: ka.bare_workload.or(kb.bare_workload),
}
}
fn two_slot_artifact_source_probe(
a: crate::export::ArtifactKind,
b: crate::export::ArtifactKind,
) -> crate::export::ArtifactSource {
let sa = single_slot_artifact_source_probe(a);
let sb = single_slot_artifact_source_probe(b);
crate::export::ArtifactSource {
receipts: sa.receipts.or(sb.receipts),
test_report: sa.test_report.or(sb.test_report),
process_snapshot: sa.process_snapshot.or(sb.process_snapshot),
run_marker: sa.run_marker.or(sb.run_marker),
}
}
fn two_slot_vector_channel_probe(
a: crate::export::ChannelKind,
b: crate::export::ChannelKind,
) -> crate::export::VectorChannel {
let ca = single_slot_vector_channel_probe(a);
let cb = single_slot_vector_channel_probe(b);
crate::export::VectorChannel {
http_event: ca.http_event.or(cb.http_event),
nats_subject: ca.nats_subject.or(cb.nats_subject),
stdout: ca.stdout.or(cb.stdout),
}
}
/// The trait's `KIND_LIST` associated const IS the same
/// `&'static str` the inherent `_LIST` constant publishes at
/// each production site — pin identity via `std::ptr::eq` so a
/// future silent copy (e.g. `const KIND_LIST: &'static str =
/// "...literal...";` at the impl block) is caught here.
#[test]
fn production_tagged_union_kind_list_borrows_the_inherent_constant() {
assert!(std::ptr::eq(
<crate::intent::Intent as TaggedUnion>::KIND_LIST,
crate::intent::INTENT_KIND_LIST,
));
assert!(std::ptr::eq(
<crate::encapsulates::EncapsulationKind as TaggedUnion>::KIND_LIST,
crate::encapsulates::ENCAPSULATION_TARGET_LIST,
));
assert!(std::ptr::eq(
<crate::export::ArtifactSource as TaggedUnion>::KIND_LIST,
crate::export::ARTIFACT_KIND_LIST,
));
assert!(std::ptr::eq(
<crate::export::VectorChannel as TaggedUnion>::KIND_LIST,
crate::export::CHANNEL_KIND_LIST,
));
}
// -------------------------------------------------------------------
// `TaggedUnion::variant` default method — substrate primitive every
// production `.variant()` inherent method delegates to. Pin the
// four-outcome truth table (Empty on all-none, Ambiguous on many,
// Ok on exactly-one at every position) directly on the sibling-
// shaped local parent + local kind + local variant scaffold, so a
// regression on the default body's short-circuit or
// ClosedSet::ALL iteration shape fails here — before any per-parent
// inherent test surfaces the drift.
// -------------------------------------------------------------------
/// Every populated position across [`LocalKind::ALL`] resolves to
/// its own [`LocalVariant`] arm through the default body's
/// `resolve_or_err(<Kind as ClosedSet>::ALL.iter().copied()
/// .map(|k| k.select(self)), KIND_LIST)` sweep. Pin every position
/// so a regression that drifts the iteration order (or drops the
/// `.iter().copied()` bridge to owned-`Copy` Kinds) fails at ONE
/// substrate boundary rather than at four per-parent inherent test
/// sites.
#[test]
fn tagged_union_default_variant_resolves_each_populated_slot() {
let mut p = LocalParent {
alpha: Some(11),
..Default::default()
};
assert_eq!(
<LocalParent as TaggedUnion>::variant(&p).unwrap(),
LocalVariant::Alpha(&11)
);
p = LocalParent {
beta: Some(22),
..Default::default()
};
assert_eq!(
<LocalParent as TaggedUnion>::variant(&p).unwrap(),
LocalVariant::Beta(&22)
);
p = LocalParent {
gamma: Some(33),
..Default::default()
};
assert_eq!(
<LocalParent as TaggedUnion>::variant(&p).unwrap(),
LocalVariant::Gamma(&33)
);
}
/// A [`LocalParent`] with no populated slot resolves through the
/// default body to a [`TaggedUnionError::empty`] carrier whose
/// payload IS the trait's [`TaggedUnion::KIND_LIST`] constant —
/// pin identity via [`std::ptr::eq`] so a regression that
/// composes a fresh `&'static str` at the empty arm (instead of
/// carrying the trait's constant verbatim) is caught here. This
/// is the substrate-wide guarantee the four production sites'
/// operator diagnostics depend on: a rename at
/// `<Parent as TaggedUnion>::KIND_LIST` reaches the error surface
/// intact through ONE `&'static str` handoff.
#[test]
fn tagged_union_default_variant_empty_carries_kind_list_by_pointer() {
let empty = LocalParent::default();
let err = <LocalParent as TaggedUnion>::variant(&empty).unwrap_err();
match err {
LocalParentError::Empty(list) => {
assert!(
std::ptr::eq(list, <LocalParent as TaggedUnion>::KIND_LIST),
"TaggedUnion::variant default must carry KIND_LIST by pointer, not by re-composition",
);
}
LocalParentError::Ambiguous => {
panic!("expected Empty carrier, got Ambiguous");
}
}
}
/// A [`LocalParent`] with two populated slots resolves through
/// the default body to a [`TaggedUnionError::ambiguous`] carrier —
/// pin the Many arm at the substrate boundary so a regression
/// that drops the short-circuit (or misroutes the Many arm to
/// Empty) is caught here.
#[test]
fn tagged_union_default_variant_ambiguous_on_multiple_populated_slots() {
let p = LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: None,
};
assert_eq!(
<LocalParent as TaggedUnion>::variant(&p).unwrap_err(),
LocalParentError::Ambiguous
);
}
/// Every one of the four production `.variant()` inherent methods
/// dispatches through the trait's default body byte-identically —
/// pin the delegation shape (inherent forwarder → trait default)
/// on a probe per parent so a regression that copies the pre-lift
/// hand-rolled `resolve_or_err(...)` body back into the inherent
/// method (instead of the `<Self as TaggedUnion>::variant(self)`
/// one-line delegation) reaches this substrate boundary before it
/// reaches any operator diagnostic.
#[test]
fn every_production_inherent_variant_dispatches_through_trait_default() {
use crate::encapsulates::{EncapsulationKind, EncapsulationKindError};
use crate::export::{ArtifactError, ArtifactSource, ChannelError, VectorChannel};
use crate::intent::{Intent, IntentError};
// Intent: default of all-None resolves to Empty via the delegation.
let i = Intent::default();
match (i.variant(), <Intent as TaggedUnion>::variant(&i)) {
(Err(IntentError::Empty(a)), Err(IntentError::Empty(b))) => assert!(
std::ptr::eq(a, b),
"Intent inherent and trait dispatch must return the same &'static str",
),
(a, b) => panic!("Intent inherent/trait mismatch: inherent={a:?}, trait={b:?}"),
}
// EncapsulationKind: same Empty projection through both dispatch paths.
let k = EncapsulationKind::default();
match (k.variant(), <EncapsulationKind as TaggedUnion>::variant(&k)) {
(Err(EncapsulationKindError::Empty(a)), Err(EncapsulationKindError::Empty(b))) => {
assert!(
std::ptr::eq(a, b),
"EncapsulationKind inherent and trait dispatch must return the same &'static str",
)
}
(a, b) => {
panic!("EncapsulationKind inherent/trait mismatch: inherent={a:?}, trait={b:?}")
}
}
// ArtifactSource: same Empty projection through both dispatch paths.
let s = ArtifactSource::default();
match (s.variant(), <ArtifactSource as TaggedUnion>::variant(&s)) {
(Err(ArtifactError::Empty(a)), Err(ArtifactError::Empty(b))) => assert!(
std::ptr::eq(a, b),
"ArtifactSource inherent and trait dispatch must return the same &'static str",
),
(a, b) => panic!("ArtifactSource inherent/trait mismatch: inherent={a:?}, trait={b:?}"),
}
// VectorChannel: same Empty projection through both dispatch paths.
let c = VectorChannel::default();
match (c.variant(), <VectorChannel as TaggedUnion>::variant(&c)) {
(Err(ChannelError::Empty(a)), Err(ChannelError::Empty(b))) => assert!(
std::ptr::eq(a, b),
"VectorChannel inherent and trait dispatch must return the same &'static str",
),
(a, b) => panic!("VectorChannel inherent/trait mismatch: inherent={a:?}, trait={b:?}"),
}
}
// -------------------------------------------------------------------
// `declare_tagged_union_impls!` macro — the three-block impl stanza
// (inherent `.variant()` forwarder + `VariantSelector<Parent>` on
// the Kind + `TaggedUnion` on the parent) as ONE authoring surface.
// Pin the macro's shape against a sibling-shaped local family so a
// regression on any of the three emitted blocks fails here before
// it reaches the four production sites.
// -------------------------------------------------------------------
/// Local sibling-shaped Kind for the macro-emitted-impls test — a
/// dedicated closed set so this test can't share substrate with the
/// hand-rolled [`LocalKind`] block above. Uses
/// [`tatara_closed_set::DeriveClosedSet`] so the macro's
/// `TaggedUnion` bound (`Kind: ClosedSet + VariantSelector<Self>`)
/// is satisfied through the derive.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, tatara_closed_set::DeriveClosedSet)]
#[closed_set(via = "as_str", generate_unknown)]
enum MacroLocalKind {
Foo,
Bar,
}
impl MacroLocalKind {
const ALL: [Self; 2] = [Self::Foo, Self::Bar];
const fn as_str(self) -> &'static str {
match self {
Self::Foo => "foo",
Self::Bar => "bar",
}
}
fn select<'a>(self, parent: &'a MacroLocalParent) -> Option<MacroLocalVariant<'a>> {
match self {
Self::Foo => parent.foo.as_ref().map(MacroLocalVariant::Foo),
Self::Bar => parent.bar.as_ref().map(MacroLocalVariant::Bar),
}
}
}
/// Local sibling-shaped parent for the macro-emitted-impls test —
/// distinct from [`LocalParent`] so the macro's emitted impls
/// don't collide with the hand-rolled trait impls above.
///
/// Derives [`serde::Serialize`] with `skip_serializing_if =
/// "Option::is_none"` on every slot so the wire-format primitive
/// [`assert_single_slot_key_matches_label`] can be exercised
/// through the macro-emitted `TaggedUnion` impl path — pins the
/// substrate-wide guarantee that a fifth sibling landing through
/// [`declare_tagged_union_impls!`] picks up the wire-alignment
/// check for free.
#[derive(Default, serde::Serialize)]
struct MacroLocalParent {
#[serde(skip_serializing_if = "Option::is_none")]
foo: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
bar: Option<u32>,
}
/// Borrowed-view of a populated slot on [`MacroLocalParent`] — the
/// return type of the macro-emitted inherent `.variant()`.
#[derive(Debug, PartialEq)]
enum MacroLocalVariant<'a> {
Foo(&'a u32),
Bar(&'a u32),
}
impl VariantKind<MacroLocalKind> for MacroLocalVariant<'_> {
fn variant_kind(&self) -> MacroLocalKind {
match self {
Self::Foo(_) => MacroLocalKind::Foo,
Self::Bar(_) => MacroLocalKind::Bar,
}
}
}
crate::declare_tagged_union_error! {
pub(super) MacroLocalError,
empty = "macro-local parent has no variant set (one of {0} required)",
ambiguous = "macro-local parent has multiple variants set; exactly one required",
}
/// Slash-joined kind list — literal peer of
/// [`crate::intent::INTENT_KIND_LIST`] etc. that the macro's
/// `KIND_LIST` associated const borrows verbatim.
const MACRO_LOCAL_KIND_LIST: &str = "foo/bar";
// ONE macro call emits: inherent `MacroLocalParent::variant`,
// `impl VariantSelector<MacroLocalParent> for MacroLocalKind`, and
// `impl TaggedUnion for MacroLocalParent`. The four production
// sites bind through this exact same call shape.
crate::declare_tagged_union_impls! {
parent = MacroLocalParent,
kind = MacroLocalKind,
variant = MacroLocalVariant,
error = MacroLocalError,
kind_list = MACRO_LOCAL_KIND_LIST,
}
/// The macro-emitted `impl TaggedUnion` binds the (Kind, Error,
/// KIND_LIST) triple exactly as a hand-rolled block would — pin
/// the diagnostic-stability testkit primitive through the macro's
/// output so a regression on any of the three associated items
/// (say the macro pulling `KIND_LIST` from the wrong argument
/// slot) fails here.
#[test]
fn macro_emitted_tagged_union_impl_binds_kind_list_coherently() {
assert_kind_list_matches_closed_set::<MacroLocalParent>();
assert!(std::ptr::eq(
<MacroLocalParent as TaggedUnion>::KIND_LIST,
MACRO_LOCAL_KIND_LIST,
));
}
/// The macro-emitted inherent `.variant()` forwarder dispatches
/// through the trait default body — every populated slot resolves
/// to its own [`MacroLocalVariant`] arm, all-none resolves to
/// [`TaggedUnionError::empty`] carrying the trait's `KIND_LIST`
/// by pointer, two-populated resolves to
/// [`TaggedUnionError::ambiguous`]. The four production sites
/// exercise the same four-outcome truth table through the same
/// macro-emitted delegation shape.
#[test]
fn macro_emitted_inherent_variant_dispatches_the_four_outcome_truth_table() {
// Foo populated.
let p = MacroLocalParent {
foo: Some(11),
bar: None,
};
assert_eq!(p.variant().unwrap(), MacroLocalVariant::Foo(&11));
// Bar populated.
let p = MacroLocalParent {
foo: None,
bar: Some(22),
};
assert_eq!(p.variant().unwrap(), MacroLocalVariant::Bar(&22));
// All none — Empty arm carries the trait's KIND_LIST value.
// The by-pointer preservation across the trait default body is
// pinned substrate-wide by
// `tagged_union_default_variant_empty_carries_kind_list_by_pointer`
// on the sibling hand-rolled `LocalParent`; this test only pins
// that the macro-emitted `KIND_LIST = MACRO_LOCAL_KIND_LIST`
// assignment reaches the operator diagnostic value-identically.
let p = MacroLocalParent::default();
match p.variant().unwrap_err() {
MacroLocalError::Empty(list) => assert_eq!(list, MACRO_LOCAL_KIND_LIST),
MacroLocalError::Ambiguous => panic!("expected Empty, got Ambiguous"),
}
// Two populated — Ambiguous.
let p = MacroLocalParent {
foo: Some(1),
bar: Some(2),
};
assert_eq!(p.variant().unwrap_err(), MacroLocalError::Ambiguous);
}
/// The macro-emitted inherent `.has()` forwarder dispatches
/// through the trait default body — the presence probe agrees
/// with `Kind::select(&parent).is_some()` on the diagonal
/// (populated slot AND matching Kind → `true`) and off the
/// diagonal (populated slot BUT other Kind → `false`) for the
/// same four-outcome truth table the macro-emitted `.variant()`
/// covers. The four production sites bind through this exact
/// same macro-emitted delegation shape; the substrate testkit
/// primitive [`assert_has_matches_select`] sweeps this contract
/// generically once each production Kind picks up the macro's
/// output.
#[test]
fn macro_emitted_inherent_has_dispatches_the_presence_probe_diagonal() {
// Foo populated → has(Foo) is true, has(Bar) is false.
let p = MacroLocalParent {
foo: Some(11),
bar: None,
};
assert!(p.has(MacroLocalKind::Foo));
assert!(!p.has(MacroLocalKind::Bar));
// Bar populated → has(Bar) is true, has(Foo) is false.
let p = MacroLocalParent {
foo: None,
bar: Some(22),
};
assert!(!p.has(MacroLocalKind::Foo));
assert!(p.has(MacroLocalKind::Bar));
// All none — every probe is false; no Empty carrier
// allocation on this path (the presence-probe half of the
// resolve contract deliberately elides diagnostic composition
// when the caller only needs yes/no).
let p = MacroLocalParent::default();
assert!(!p.has(MacroLocalKind::Foo));
assert!(!p.has(MacroLocalKind::Bar));
// Two populated — has(k) is true for BOTH populated slots
// (the probe is a per-slot projection, not the parent-wide
// resolver — Ambiguous is a resolve outcome, not a presence
// outcome).
let p = MacroLocalParent {
foo: Some(1),
bar: Some(2),
};
assert!(p.has(MacroLocalKind::Foo));
assert!(p.has(MacroLocalKind::Bar));
}
/// The macro-emitted inherent `.find()` forwarder dispatches
/// through the trait default body — every populated slot resolves
/// to `Some(matching-borrow)`, empty slots to `None`, and the
/// composition law `parent.has(k) == parent.find(k).is_some()`
/// holds at every arm of the four-outcome truth table. Additional
/// pointer-identity pin: the borrowed reference returned by
/// `p.find(k)` on a populated slot IS the same reference that
/// `<Kind>::select(k, &p)` returns — a regression that inlines a
/// divergent projection body at the macro's emitted forwarder
/// (rather than reaching the trait's `<Self as
/// TaggedUnion>::find(self, kind)` one-line delegation) is caught
/// here.
#[test]
fn macro_emitted_inherent_find_dispatches_the_presence_probe_diagonal() {
// Foo populated → find(Foo) borrows the inner ref, find(Bar)
// is None, and `has` agrees with `find(...).is_some()` on
// both arms.
let p = MacroLocalParent {
foo: Some(77),
bar: None,
};
match p.find(MacroLocalKind::Foo) {
Some(MacroLocalVariant::Foo(v)) => {
assert_eq!(*v, 77, "find must borrow the populated inner");
assert_eq!(
p.has(MacroLocalKind::Foo),
true,
"composition law: has must agree with find(...).is_some() on populated slot",
);
// Pointer-identity check: `find` delegates to
// `kind.select(self)` byte-identically. The returned
// borrow IS the borrow `select` returns.
let via_select = MacroLocalKind::Foo.select(&p).unwrap();
match via_select {
MacroLocalVariant::Foo(w) => assert!(
std::ptr::eq(v, w),
"macro-emitted find must return the SAME borrow as VariantSelector::select",
),
MacroLocalVariant::Bar(_) => {
panic!(
"VariantSelector::select disagreed with find on the populated Foo slot"
)
}
}
}
other => panic!("expected Foo populated, got {other:?}"),
}
assert!(p.find(MacroLocalKind::Bar).is_none());
assert_eq!(
p.has(MacroLocalKind::Bar),
false,
"composition law: has must agree with find(...).is_some() on empty slot",
);
// All none — find returns None for every kind; has agrees.
let p = MacroLocalParent::default();
for kind in MacroLocalKind::ALL {
assert!(p.find(kind).is_none());
assert_eq!(
p.has(kind),
false,
"composition law on empty parent: has must equal find(...).is_some()",
);
}
// Two populated — find(k) is Some for BOTH populated slots
// (the widened primitive is a per-slot projection, not the
// parent-wide resolver — Ambiguous is a resolve outcome, not
// a find outcome).
let p = MacroLocalParent {
foo: Some(1),
bar: Some(2),
};
assert!(p.find(MacroLocalKind::Foo).is_some());
assert!(p.find(MacroLocalKind::Bar).is_some());
}
/// The macro-emitted `VariantSelector` impl's `select` body
/// delegates to the Kind's inherent `<Kind>::select(self, parent)`
/// — pin the delegation via `std::ptr::eq` on the returned
/// borrowed view so a regression that inlines a divergent select
/// body (rather than reaching the inherent method) is caught here.
#[test]
fn macro_emitted_variant_selector_delegates_to_inherent_select() {
let p = MacroLocalParent {
foo: Some(7),
bar: None,
};
// Trait-dispatched select projects through the macro-emitted body.
let via_trait =
<MacroLocalKind as VariantSelector<MacroLocalParent>>::select(MacroLocalKind::Foo, &p)
.unwrap();
// Inherent select projects through the direct impl.
let via_inherent = MacroLocalKind::Foo.select(&p).unwrap();
match (via_trait, via_inherent) {
(MacroLocalVariant::Foo(a), MacroLocalVariant::Foo(b)) => {
assert!(
std::ptr::eq(a, b),
"macro-emitted VariantSelector::select must delegate to <Kind>::select — same borrow, not a copy",
);
}
_ => panic!("expected Foo arm on both dispatch paths"),
}
}
/// The trait's default body sweeps `<Kind as ClosedSet>::ALL` in
/// declaration order — pin the iteration order against the
/// production `Kind::ALL` inherent const on every implementor so
/// a regression on `DeriveClosedSet`'s ALL-projection (or a
/// silent reorder of the enum's variant declarations that drifts
/// only ONE of the two arrays) fails at ONE substrate boundary.
#[test]
fn every_production_kind_closedset_all_matches_inherent_all() {
use crate::encapsulates::EncapsulationTarget;
use crate::export::{ArtifactKind, ChannelKind};
use crate::intent::IntentKind;
assert_eq!(
<IntentKind as tatara_closed_set::ClosedSet>::ALL,
IntentKind::ALL.as_slice(),
);
assert_eq!(
<EncapsulationTarget as tatara_closed_set::ClosedSet>::ALL,
EncapsulationTarget::ALL.as_slice(),
);
assert_eq!(
<ArtifactKind as tatara_closed_set::ClosedSet>::ALL,
ArtifactKind::ALL.as_slice(),
);
assert_eq!(
<ChannelKind as tatara_closed_set::ClosedSet>::ALL,
ChannelKind::ALL.as_slice(),
);
}
// -------------------------------------------------------------------
// `VariantKind<K>` trait — reverse projection from a borrowed-variant
// view back into its addressing Kind, and `assert_variant_round_trip`
// as the substrate testkit primitive that composes it with
// `VariantSelector::select` on the populated side. Pin the four-arm
// truth table (every position round-trips through select→variant_kind
// AND through variant()→variant_kind) directly on the sibling-shaped
// local scaffold, so a regression on either projection or on the
// resolver default body fails here — before any per-parent inherent
// test surfaces the drift.
// -------------------------------------------------------------------
/// Every populated position across [`LocalKind::ALL`] round-trips
/// through both `select→variant_kind` AND `variant()→variant_kind`
/// on the sibling-shaped local scaffold. Pins the substrate
/// primitive's four-arm truth table at ONE boundary — a regression
/// on either projection direction (or on the resolver default
/// short-circuit / iteration order) fails here before any per-parent
/// inherent test surfaces the drift.
#[test]
fn assert_variant_round_trip_accepts_coherent_local_impl() {
fn make_local(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(11),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(22),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(33),
..Default::default()
},
}
}
assert_variant_round_trip::<LocalParent, _>(make_local);
}
/// The testkit primitive is a `#[track_caller]` compound-lift: a
/// factory that fails to populate the addressed slot fails at the
/// caller's site with a labeled panic message, not silently. Pin
/// the failing case with a deliberately empty parent factory so a
/// regression that drops the "select must return Some" check
/// fails-loudly here — the missing-slot arm is the substrate
/// primitive's first failure mode.
#[test]
#[should_panic(expected = "VariantSelector::select must return Some for populated slot")]
fn assert_variant_round_trip_rejects_factory_that_leaves_slot_empty() {
// Factory that returns an all-empty parent regardless of k —
// every `k.select(&parent)` returns None, so the primitive
// panics at the "must return Some" arm.
fn empty_factory(_: LocalKind) -> LocalParent {
LocalParent::default()
}
assert_variant_round_trip::<LocalParent, _>(empty_factory);
}
// -------------------------------------------------------------------
// `TaggedUnion::find` — the widened peer of `TaggedUnion::has` on the
// presence-probe algebra. Pin every arm of the four-outcome truth
// table (empty parent → None, populated-diagonal → Some(matching
// borrow), populated-off-diagonal → None, two-populated → Some for
// BOTH populated slots) directly on the sibling-shaped local scaffold
// AND on the macro-emitted inherent surface. A regression on the
// default body's `kind.select(self)` delegation (or on the emitted
// inherent forwarder's `<Self as TaggedUnion>::find(self, kind)`
// one-line body) fails here before it reaches any of the four
// production sites.
// -------------------------------------------------------------------
/// EMPTY-PARENT pin — a default [`LocalParent`] returns `None` at
/// `find` for EVERY [`LocalKind`], sweeping `ClosedSet::ALL` so a
/// new variant added without a matching arm in the primitive
/// surfaces at rustc's exhaustiveness gate on the ALL literal
/// rather than as a silent false-positive at every downstream
/// consumer composing this primitive.
#[test]
fn tagged_union_default_find_returns_none_on_empty_parent_for_every_kind() {
let empty = LocalParent::default();
for kind in <LocalKind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
assert!(
<LocalParent as TaggedUnion>::find(&empty, kind).is_none(),
"empty parent must return None at find for {kind:?}",
);
}
}
/// DELEGATION pin — every populated position across
/// [`LocalKind::ALL`] returns `Some(matching-borrow)` at `find`,
/// AND the returned borrowed view carries the SAME reference as
/// `probed.select(&parent).unwrap()` (byte-identical delegation:
/// `find` IS `kind.select(self)`, not a re-projection).
/// Composition-law pin: `has(k) == find(k).is_some()` on both
/// diagonal (populated slot AND matching Kind → true) and
/// off-diagonal (populated slot BUT other Kind → false).
#[test]
fn tagged_union_default_find_delegates_to_select_across_every_kind() {
for populated in <LocalKind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let parent = match populated {
LocalKind::Alpha => LocalParent {
alpha: Some(101),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(202),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(303),
..Default::default()
},
};
for probed in <LocalKind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let via_find = <LocalParent as TaggedUnion>::find(&parent, probed);
let via_select = probed.select(&parent);
assert_eq!(
via_find.is_some(),
via_select.is_some(),
"find drifted from select — populated={populated:?} probed={probed:?}",
);
assert_eq!(
parent.has(probed),
via_find.is_some(),
"has drifted from find(k).is_some() — populated={populated:?} probed={probed:?}",
);
if let Some(v) = via_find {
assert_eq!(
<LocalVariant<'_> as VariantKind<LocalKind>>::variant_kind(&v),
probed,
"find→variant_kind round-trip failed — populated={populated:?} probed={probed:?}",
);
// Populated iff probed == populated (single-slot
// parent) — off-diagonal arms return None above
// and never reach this Some-branch.
assert_eq!(
probed, populated,
"off-diagonal probe should have returned None at find",
);
}
}
}
}
/// TWO-POPULATED pin — a parent with two populated slots returns
/// `Some(matching-borrow)` at `find` for BOTH populated Kinds
/// (unlike `variant()` which resolves to `Ambiguous`), and `None`
/// for the empty third Kind. Locks the presence-probe axis of the
/// widened primitive against a regression that inlined the
/// resolver's short-circuit body into `find` (silently narrowing
/// two populated to Ambiguous instead of a per-slot borrow).
#[test]
fn tagged_union_default_find_projects_per_slot_on_multi_populated_parent() {
let parent = LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: None,
};
assert!(
<LocalParent as TaggedUnion>::find(&parent, LocalKind::Alpha).is_some(),
"find must project Alpha slot in a two-populated parent",
);
assert!(
<LocalParent as TaggedUnion>::find(&parent, LocalKind::Beta).is_some(),
"find must project Beta slot in a two-populated parent",
);
assert!(
<LocalParent as TaggedUnion>::find(&parent, LocalKind::Gamma).is_none(),
"find must return None for the empty Gamma slot",
);
}
/// `assert_find_agrees_with_has` testkit accepts the coherent
/// local scaffold — sweeping every `(populated, probed)` pair
/// through the three sub-assertions (find↔has, find↔select,
/// diagonal round-trip). A regression on any of the three
/// composition laws fails at the substrate primitive's
/// `#[track_caller]` boundary here rather than at four per-parent
/// production sites downstream.
#[test]
fn assert_find_agrees_with_has_accepts_coherent_local_impl() {
fn make_local(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(11),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(22),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(33),
..Default::default()
},
}
}
assert_find_agrees_with_has::<LocalParent, _>(make_local);
}
// -------------------------------------------------------------------
// `TaggedUnion::populated_kinds` default method + the
// closed-set-inversion refinement's per-parent semantics — pin the
// three arms (empty parent → empty vec, single-slot → vec![k],
// multi-populated → vec[a..b] in ClosedSet::ALL order) directly on
// the sibling-shaped `LocalParent` scaffold. Peer of the boundary-
// side `ConditionSliceExt::distinct_kinds` primitive's three-arm
// pin on the slice-level presence-probe axis.
// -------------------------------------------------------------------
/// EMPTY parent — the default body's `ALL.filter(has).collect()`
/// sweep yields an empty vec when no slot is populated. Pins the
/// zero-cardinality arm: a regression that mis-composed the
/// `ALL.iter()` bridge (short-circuiting past the empty case),
/// returned a non-empty sentinel on empty input, or leaked stale
/// closed-set entries as false-positive members fails HERE at the
/// substrate boundary.
#[test]
fn tagged_union_default_populated_kinds_returns_empty_vec_on_empty_parent() {
let empty = LocalParent::default();
assert!(
<LocalParent as TaggedUnion>::populated_kinds(&empty).is_empty(),
"populated_kinds() must return empty Vec when no slot is populated",
);
}
/// SINGLE-SLOT parent — the default body sweeps `ClosedSet::ALL`
/// with `has(k)` and collects the singleton `[k]` for each
/// single-populated arrangement. Pins the length-1 arm's
/// cardinality (must be exactly 1) AND ordering (the addressed
/// kind's own position in `ClosedSet::ALL`) at ONE `assert_eq!`
/// per kind — a regression that projected the wrong Kind, drifted
/// the walk from `has` to a divergent projection, or paired two
/// kinds together on a single-slot input fails HERE per addressed
/// kind. Sweeps every `LocalKind::ALL` entry so no per-variant
/// specialization can silently drop the check.
#[test]
fn tagged_union_default_populated_kinds_returns_single_element_vec_per_variant() {
for populated in <LocalKind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let parent = match populated {
LocalKind::Alpha => LocalParent {
alpha: Some(11),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(22),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(33),
..Default::default()
},
};
assert_eq!(
<LocalParent as TaggedUnion>::populated_kinds(&parent),
vec![populated],
"single-slot parent must return exactly [{populated:?}] on populated_kinds",
);
}
}
/// MULTI-POPULATED parent — the default body yields the canonical
/// `ClosedSet::ALL`-ordered pair `[Alpha, Beta]` for a two-slot
/// arrangement populated in the CONSTRUCTION order `(Beta, Alpha)`.
/// Pins the walk order arm: a regression that yielded slot-
/// construction-order (`[Beta, Alpha]`) instead of canonical
/// `ALL`-order fails HERE at the equality assert. Also pins the
/// non-short-circuiting arm — a regression that inlined the
/// resolver's short-circuit body into `populated_kinds` (silently
/// narrowing two populated to a length-1 vec containing the first
/// slot) fails at the length side of the equality.
#[test]
fn tagged_union_default_populated_kinds_walks_canonical_all_order_on_multi_populated_parent() {
let parent = LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: None,
};
assert_eq!(
<LocalParent as TaggedUnion>::populated_kinds(&parent),
vec![LocalKind::Alpha, LocalKind::Beta],
"multi-populated parent must return canonical ClosedSet::ALL-ordered kinds",
);
}
/// SATURATED parent — every slot populated returns
/// `LocalKind::ALL.to_vec()` exactly. Pins the full-closed-set-
/// coverage arm: a `[1..]` or `[..ALL.len() - 1]` walk bug that
/// silently truncated the swept range at either end surfaces at
/// the equality assert here.
#[test]
fn tagged_union_default_populated_kinds_covers_full_closed_set_on_saturated_parent() {
let saturated = LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: Some(3),
};
assert_eq!(
<LocalParent as TaggedUnion>::populated_kinds(&saturated),
<LocalKind as tatara_closed_set::ClosedSet>::ALL.to_vec(),
"saturated parent must return ClosedSet::ALL.to_vec() on populated_kinds",
);
}
/// `assert_populated_kinds_matches_has` testkit accepts the
/// coherent local scaffold — sweeping every `(populated, probed)`
/// pair through the three sub-assertions (per-kind membership,
/// canonical `ALL`-filter equality, single-slot diagonal). A
/// regression on any of the three composition laws fails at the
/// substrate primitive's `#[track_caller]` boundary here rather
/// than at four per-parent production sites downstream.
#[test]
fn assert_populated_kinds_matches_has_accepts_coherent_local_impl() {
fn make_local(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(11),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(22),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(33),
..Default::default()
},
}
}
assert_populated_kinds_matches_has::<LocalParent, _>(make_local);
}
/// A factory that yields an all-empty parent (so
/// `populated_kinds()` returns `[]`) MUST fail-loudly at the
/// caller's site through the primitive's single-slot diagonal
/// arm — the empty vec does not equal `vec![populated]` for the
/// swept `populated` kind. Pin the diagonal-arm failure mode so
/// a regression that silently succeeded on an all-empty factory
/// (e.g. the primitive was refactored to skip the diagonal
/// assert on `kinds.is_empty()`) is caught here.
#[test]
#[should_panic(expected = "must return vec![Alpha] exactly")]
fn assert_populated_kinds_matches_has_rejects_factory_that_populates_no_slots() {
fn empty_factory(_: LocalKind) -> LocalParent {
LocalParent::default()
}
assert_populated_kinds_matches_has::<LocalParent, _>(empty_factory);
}
/// A factory that yields a two-slot parent (so
/// `populated_kinds()` returns `[k1, k2]` for TWO populated
/// slots on a supposedly single-slot factory) MUST fail-loudly at
/// the caller's site through the primitive's single-slot diagonal
/// arm — the length-2 vec does not equal `vec![populated]`. Pin
/// the diagonal-arm cardinality failure mode so a regression that
/// silently succeeded on a broken factory (populating both the
/// addressed slot AND an extra one) is caught here.
#[test]
#[should_panic(expected = "must return vec![Alpha] exactly")]
fn assert_populated_kinds_matches_has_rejects_factory_that_populates_extra_slot() {
fn always_pair(k: LocalKind) -> LocalParent {
let mut p = LocalParent {
gamma: Some(99),
..Default::default()
};
match k {
LocalKind::Alpha => p.alpha = Some(11),
LocalKind::Beta => p.beta = Some(22),
LocalKind::Gamma => p.gamma = Some(33),
}
p
}
assert_populated_kinds_matches_has::<LocalParent, _>(always_pair);
}
/// `assert_populated_kinds_across_pairs` testkit accepts the
/// coherent local scaffold — sweeping every off-diagonal `(a, b)`
/// pair through the three sub-assertions (cardinality-2,
/// per-kind membership, canonical `ALL`-filter equality). A
/// regression on any of the three composition laws (or on the
/// diagonal-skip) fails at the substrate primitive's
/// `#[track_caller]` boundary here rather than at four per-parent
/// production sites downstream.
#[test]
fn assert_populated_kinds_across_pairs_accepts_coherent_local_impl() {
fn two_local(a: LocalKind, b: LocalKind) -> LocalParent {
let mut p = LocalParent::default();
for k in [a, b] {
match k {
LocalKind::Alpha => p.alpha = Some(11),
LocalKind::Beta => p.beta = Some(22),
LocalKind::Gamma => p.gamma = Some(33),
}
}
p
}
assert_populated_kinds_across_pairs::<LocalParent, _>(two_local);
}
/// A two-slot factory that yields a single-populated parent (so
/// `populated_kinds()` returns `[k1]` for a two-slot input) MUST
/// fail-loudly at the caller's site through the primitive's
/// cardinality-2 arm — the length-1 vec does not satisfy
/// `kinds.len() == 2`. Pin the cardinality-arm failure mode so a
/// regression that silently succeeded on a broken factory
/// (populating only the first of the two addressed slots) is
/// caught here.
#[test]
#[should_panic(expected = "must return exactly two populated kinds")]
fn assert_populated_kinds_across_pairs_rejects_factory_that_populates_only_one_slot() {
fn single_only(a: LocalKind, _: LocalKind) -> LocalParent {
let mut p = LocalParent::default();
match a {
LocalKind::Alpha => p.alpha = Some(11),
LocalKind::Beta => p.beta = Some(22),
LocalKind::Gamma => p.gamma = Some(33),
}
p
}
assert_populated_kinds_across_pairs::<LocalParent, _>(single_only);
}
/// Every one of the four production `.variant()` sites on
/// `ProcessSpec` binds through the single-slot closed-set-inversion
/// primitive `assert_populated_kinds_matches_has` coherently — every
/// per-site `single_slot_X(k)` factory produces a parent whose
/// `populated_kinds()` equals `vec![k]` and whose per-kind
/// composition law `populated_kinds().contains(&k) == has(k)` holds
/// for every `k ∈ ClosedSet::ALL`. Sweep every production
/// implementor at ONE substrate boundary so a regression that
/// drifts a production site's `single_slot_X` factory OR the
/// default `populated_kinds` body (a specialization that
/// short-circuited, drifted the walk order, or returned duplicates)
/// fails BOTH at any future per-crate test site AND at this
/// substrate-wide sweep.
#[test]
fn every_production_tagged_union_binds_through_the_populated_kinds_testkit_primitive() {
assert_populated_kinds_matches_has::<crate::intent::Intent, _>(single_slot_intent_probe);
assert_populated_kinds_matches_has::<crate::encapsulates::EncapsulationKind, _>(
single_slot_encapsulation_kind_probe,
);
assert_populated_kinds_matches_has::<crate::export::ArtifactSource, _>(
single_slot_artifact_source_probe,
);
assert_populated_kinds_matches_has::<crate::export::VectorChannel, _>(
single_slot_vector_channel_probe,
);
}
/// Peer of
/// `every_production_tagged_union_binds_through_the_populated_kinds_testkit_primitive`
/// on the two-slot ambiguous-parent side — every production
/// `.variant()` parent binds through the pair primitive
/// `assert_populated_kinds_across_pairs` coherently, so a
/// regression that inlined the resolver's short-circuit body into
/// `populated_kinds` on any production site (silently narrowing
/// two populated slots to a length-1 vec) fails at ONE substrate
/// boundary across all four parents.
#[test]
fn every_production_tagged_union_binds_through_the_populated_kinds_pair_testkit_primitive() {
assert_populated_kinds_across_pairs::<crate::intent::Intent, _>(two_slot_intent_probe);
assert_populated_kinds_across_pairs::<crate::encapsulates::EncapsulationKind, _>(
two_slot_encapsulation_kind_probe,
);
assert_populated_kinds_across_pairs::<crate::export::ArtifactSource, _>(
two_slot_artifact_source_probe,
);
assert_populated_kinds_across_pairs::<crate::export::VectorChannel, _>(
two_slot_vector_channel_probe,
);
}
// -------------------------------------------------------------------
// `TaggedUnion::populated_kind_count` — scalar cardinality refinement
// on the closed-set-inversion axis. Pin the three arms (empty parent
// → 0, single-slot → 1, multi-populated → N) directly on the sibling-
// shaped `LocalParent` scaffold and the composition law
// `populated_kind_count() == populated_kinds().len()` at the substrate
// testkit `assert_populated_kind_count_matches_populated_kinds`. Peer
// of the widened primitive `populated_kinds` (see the block above);
// the scalar projection collapses the widened Vec to its length
// without allocating.
// -------------------------------------------------------------------
/// EMPTY parent — the default body's `ALL.filter(has).count()`
/// sweep yields `0` when no slot is populated. Pins the zero-
/// cardinality arm: a regression that mis-composed the
/// `ALL.iter()` bridge (short-circuiting past the empty case),
/// returned a non-zero sentinel on empty input, or leaked stale
/// closed-set entries as false-positive members fails HERE at the
/// substrate boundary.
#[test]
fn tagged_union_default_populated_kind_count_returns_zero_on_empty_parent() {
let empty = LocalParent::default();
assert_eq!(
<LocalParent as TaggedUnion>::populated_kind_count(&empty),
0,
"populated_kind_count() must return 0 when no slot is populated",
);
}
/// SINGLE-SLOT parent — the default body sweeps `ClosedSet::ALL`
/// with `has(k)` and counts the singleton `1` for each single-
/// populated arrangement. Pins the length-1 arm's cardinality at
/// ONE `assert_eq!` per kind — a regression that projected the
/// wrong Kind, drifted the walk from `has` to a divergent
/// projection, or paired two kinds together on a single-slot input
/// fails HERE per addressed kind. Sweeps every `LocalKind::ALL`
/// entry so no per-variant specialization can silently drop the
/// check.
#[test]
fn tagged_union_default_populated_kind_count_returns_one_per_single_slot_variant() {
for populated in <LocalKind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let parent = match populated {
LocalKind::Alpha => LocalParent {
alpha: Some(11),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(22),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(33),
..Default::default()
},
};
assert_eq!(
<LocalParent as TaggedUnion>::populated_kind_count(&parent),
1,
"single-slot parent must return 1 on populated_kind_count for {populated:?}",
);
}
}
/// MULTI-POPULATED parent — the default body yields `2` for a two-
/// slot arrangement, `3` for a fully-saturated three-slot parent.
/// Pins the non-short-circuiting arm — a regression that inlined
/// the resolver's short-circuit body into `populated_kind_count`
/// (silently narrowing two populated to `1`) fails HERE at the
/// equality assert.
#[test]
fn tagged_union_default_populated_kind_count_walks_full_closed_set_on_multi_populated_parent() {
let two = LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: None,
};
assert_eq!(
<LocalParent as TaggedUnion>::populated_kind_count(&two),
2,
"two-populated parent must return 2 on populated_kind_count",
);
let saturated = LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: Some(3),
};
assert_eq!(
<LocalParent as TaggedUnion>::populated_kind_count(&saturated),
3,
"saturated parent must return LocalKind::ALL.len() on populated_kind_count",
);
}
/// Composition law `populated_kind_count() == populated_kinds().len()`
/// binds the scalar cardinality projection to the widened primitive
/// across every `ClosedSet::ALL × {empty, single_slot, two_slot,
/// saturated}` combination. Pins the byte-identity of the two
/// projections on the empty / single / multi / saturated arms — a
/// regression that overrode `populated_kind_count` with an
/// off-by-one walk, a `find(k).is_none()`-inverted body (returning
/// the ABSENT count), or a divergent short-circuit fails HERE at
/// the equality assert.
#[test]
fn tagged_union_default_populated_kind_count_matches_populated_kinds_len() {
let arrangements: [LocalParent; 4] = [
LocalParent::default(),
LocalParent {
alpha: Some(1),
..Default::default()
},
LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: None,
},
LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: Some(3),
},
];
for (idx, parent) in arrangements.iter().enumerate() {
assert_eq!(
<LocalParent as TaggedUnion>::populated_kind_count(parent),
<LocalParent as TaggedUnion>::populated_kinds(parent).len(),
"populated_kind_count() must equal populated_kinds().len() for arrangement idx {idx}",
);
}
}
/// `assert_populated_kind_count_matches_populated_kinds` testkit
/// accepts the coherent local scaffold — sweeping every populated
/// kind through the two sub-assertions (composition law
/// `count == kinds.len()` + single-slot diagonal `count == 1`). A
/// regression on either composition law fails at the substrate
/// primitive's `#[track_caller]` boundary here rather than at four
/// per-parent production sites downstream.
#[test]
fn assert_populated_kind_count_matches_populated_kinds_accepts_coherent_local_impl() {
fn make_local(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(11),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(22),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(33),
..Default::default()
},
}
}
assert_populated_kind_count_matches_populated_kinds::<LocalParent, _>(make_local);
}
/// A factory that yields an all-empty parent (so
/// `populated_kind_count()` returns `0`) MUST fail-loudly at the
/// caller's site through the primitive's single-slot diagonal arm
/// — the `0` cardinality does not satisfy `count == 1` on the
/// swept `populated` kind. Pin the diagonal-arm failure mode so a
/// regression that silently succeeded on an all-empty factory
/// (e.g. the primitive was refactored to skip the diagonal assert
/// on `count == 0`) is caught here.
#[test]
#[should_panic(expected = "must equal 1 exactly (well-formed arm cardinality)")]
fn assert_populated_kind_count_matches_populated_kinds_rejects_empty_factory() {
fn empty_factory(_: LocalKind) -> LocalParent {
LocalParent::default()
}
assert_populated_kind_count_matches_populated_kinds::<LocalParent, _>(empty_factory);
}
/// A factory that yields a two-slot parent (so
/// `populated_kind_count()` returns `2` on a supposedly single-slot
/// factory) MUST fail-loudly at the caller's site through the
/// primitive's single-slot diagonal arm — the `2` cardinality does
/// not satisfy `count == 1`. Pin the diagonal-arm cardinality
/// failure mode so a regression that silently succeeded on a
/// broken factory (populating both the addressed slot AND an extra
/// one) is caught here.
#[test]
#[should_panic(expected = "must equal 1 exactly (well-formed arm cardinality)")]
fn assert_populated_kind_count_matches_populated_kinds_rejects_two_slot_factory() {
fn always_pair(k: LocalKind) -> LocalParent {
let mut p = LocalParent {
gamma: Some(99),
..Default::default()
};
match k {
LocalKind::Alpha => p.alpha = Some(11),
LocalKind::Beta => p.beta = Some(22),
LocalKind::Gamma => p.gamma = Some(33),
}
p
}
assert_populated_kind_count_matches_populated_kinds::<LocalParent, _>(always_pair);
}
/// Every one of the four production `.variant()` sites on
/// `ProcessSpec` binds through the scalar-cardinality primitive
/// `assert_populated_kind_count_matches_populated_kinds` coherently
/// — every per-site `single_slot_X(k)` factory produces a parent
/// whose `populated_kind_count()` equals `1` AND whose composition
/// law `count == populated_kinds().len()` holds. Sweep every
/// production implementor at ONE substrate boundary so a regression
/// that drifts a production site's `single_slot_X` factory OR the
/// default `populated_kind_count` body (a specialization that
/// short-circuited, drifted the walk order, or double-counted a
/// slot) fails BOTH at any future per-crate test site AND at this
/// substrate-wide sweep.
#[test]
fn every_production_tagged_union_binds_through_the_populated_kind_count_testkit_primitive() {
assert_populated_kind_count_matches_populated_kinds::<crate::intent::Intent, _>(
single_slot_intent_probe,
);
assert_populated_kind_count_matches_populated_kinds::<
crate::encapsulates::EncapsulationKind,
_,
>(single_slot_encapsulation_kind_probe);
assert_populated_kind_count_matches_populated_kinds::<crate::export::ArtifactSource, _>(
single_slot_artifact_source_probe,
);
assert_populated_kind_count_matches_populated_kinds::<crate::export::VectorChannel, _>(
single_slot_vector_channel_probe,
);
}
// -------------------------------------------------------------------
// `TaggedUnion::missing_kinds` default method + the
// closed-set-COMPLEMENT refinement's per-parent semantics — pin the
// three arms (empty parent → full closed set, single-slot → ALL \
// {k} in canonical order, saturated → empty vec) directly on the
// sibling-shaped `LocalParent` scaffold. Peer of the boundary-side
// `ConditionSliceExt::missing_kinds` primitive's three-arm pin on
// the slice-level presence-probe axis; closed-set-COMPLEMENT peer
// of the parent-level `populated_kinds` primitive above.
// -------------------------------------------------------------------
/// EMPTY parent — the default body's `ALL.filter(!has).collect()`
/// sweep yields the FULL `ClosedSet::ALL` vec when no slot is
/// populated (every kind is missing). Pins the full-cardinality
/// arm: a regression that mis-composed the `ALL.iter()` bridge
/// (short-circuiting past the empty case), inverted the negation
/// (returning `populated_kinds`), or dropped closed-set entries as
/// false-negative absences fails HERE at the substrate boundary.
#[test]
fn tagged_union_default_missing_kinds_returns_full_closed_set_on_empty_parent() {
let empty = LocalParent::default();
assert_eq!(
<LocalParent as TaggedUnion>::missing_kinds(&empty),
<LocalKind as tatara_closed_set::ClosedSet>::ALL.to_vec(),
"missing_kinds() must return ClosedSet::ALL when no slot is populated",
);
}
/// SINGLE-SLOT parent — the default body sweeps `ClosedSet::ALL`
/// with `!has(k)` and collects `ALL \ {populated}` for each
/// single-populated arrangement. Pins the length-(ALL.len()-1)
/// arm's cardinality AND ordering (canonical `ClosedSet::ALL`
/// order, `populated` absent) at ONE `assert_eq!` per kind — a
/// regression that inverted the negation (returning `vec![populated]`
/// instead of `ALL \ {populated}`) fails HERE per addressed kind.
#[test]
fn tagged_union_default_missing_kinds_returns_complement_per_variant() {
for populated in <LocalKind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let parent = match populated {
LocalKind::Alpha => LocalParent {
alpha: Some(11),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(22),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(33),
..Default::default()
},
};
let expected: Vec<LocalKind> = <LocalKind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
.filter(|k| *k != populated)
.collect();
assert_eq!(
<LocalParent as TaggedUnion>::missing_kinds(&parent),
expected,
"single-slot parent must return ClosedSet::ALL \\ {{{populated:?}}} on missing_kinds",
);
}
}
/// SATURATED parent — every slot populated returns an empty vec on
/// `missing_kinds`. Pins the zero-cardinality arm on the complement
/// side (mirror of `populated_kinds` returning `ALL.to_vec()` on
/// the saturated arm).
#[test]
fn tagged_union_default_missing_kinds_returns_empty_vec_on_saturated_parent() {
let saturated = LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: Some(3),
};
assert!(
<LocalParent as TaggedUnion>::missing_kinds(&saturated).is_empty(),
"saturated parent must return empty Vec on missing_kinds",
);
}
/// Partition law binding `populated_kinds` and `missing_kinds` on
/// every `LocalParent` arrangement: every `k ∈ ClosedSet::ALL`
/// lives on EXACTLY ONE side of the partition (populated OR
/// missing, never both, never neither). Pins the compound-lift's
/// most-load-bearing invariant at ONE `assert!` per (arrangement,
/// kind) pair — a regression that returned overlapping or
/// disjoint-but-incomplete sets fails HERE at the XOR arm.
#[test]
fn tagged_union_default_populated_kinds_and_missing_kinds_partition_the_closed_set() {
let arrangements: [LocalParent; 4] = [
LocalParent::default(),
LocalParent {
alpha: Some(1),
..Default::default()
},
LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: None,
},
LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: Some(3),
},
];
for (idx, parent) in arrangements.iter().enumerate() {
let populated = <LocalParent as TaggedUnion>::populated_kinds(parent);
let missing = <LocalParent as TaggedUnion>::missing_kinds(parent);
for &k in <LocalKind as tatara_closed_set::ClosedSet>::ALL.iter() {
let in_populated = populated.contains(&k);
let in_missing = missing.contains(&k);
assert!(
in_populated ^ in_missing,
"arrangement idx {idx} — {k:?} must live on exactly one side of (populated, missing), got in_populated={in_populated} in_missing={in_missing}",
);
}
}
}
/// `assert_missing_kinds_matches_has` testkit accepts the coherent
/// local scaffold — sweeping every populated slot through the
/// per-kind negation + canonical `ALL`-filter + single-slot
/// diagonal + XOR partition arms. A regression on any of the four
/// composition laws fails at the substrate primitive's
/// `#[track_caller]` boundary here rather than at four per-parent
/// production sites downstream.
#[test]
fn assert_missing_kinds_matches_has_accepts_coherent_local_impl() {
fn make_local(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(11),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(22),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(33),
..Default::default()
},
}
}
assert_missing_kinds_matches_has::<LocalParent, _>(make_local);
}
/// A factory that yields an all-empty parent MUST fail-loudly at
/// the caller's site through the primitive's single-slot diagonal
/// arm — the full `ALL` vec (every kind missing) does not equal
/// `ALL \ {populated}` (which excludes `populated`). Pin the
/// diagonal-arm failure mode so a regression that silently
/// succeeded on an all-empty factory is caught here.
#[test]
#[should_panic(expected = "must return ClosedSet::ALL with Alpha removed")]
fn assert_missing_kinds_matches_has_rejects_factory_that_populates_no_slots() {
fn empty_factory(_: LocalKind) -> LocalParent {
LocalParent::default()
}
assert_missing_kinds_matches_has::<LocalParent, _>(empty_factory);
}
/// Every one of the four production `.variant()` sites on
/// `ProcessSpec` binds through the single-slot closed-set-complement
/// primitive `assert_missing_kinds_matches_has` coherently — every
/// per-site `single_slot_X(k)` factory produces a parent whose
/// `missing_kinds()` equals `ALL \ {k}` and whose per-kind
/// negation composition law `missing_kinds().contains(&k) == !has(k)`
/// holds for every `k ∈ ClosedSet::ALL`, AND the XOR partition law
/// with `populated_kinds` binds byte-identically at every closed-
/// set entry. Sweep every production implementor at ONE substrate
/// boundary so a regression that drifts a production site's
/// `single_slot_X` factory OR the default `missing_kinds` body (a
/// specialization that inverted the negation, short-circuited, or
/// drifted the walk order) fails BOTH at any future per-crate test
/// site AND at this substrate-wide sweep.
#[test]
fn every_production_tagged_union_binds_through_the_missing_kinds_testkit_primitive() {
assert_missing_kinds_matches_has::<crate::intent::Intent, _>(single_slot_intent_probe);
assert_missing_kinds_matches_has::<crate::encapsulates::EncapsulationKind, _>(
single_slot_encapsulation_kind_probe,
);
assert_missing_kinds_matches_has::<crate::export::ArtifactSource, _>(
single_slot_artifact_source_probe,
);
assert_missing_kinds_matches_has::<crate::export::VectorChannel, _>(
single_slot_vector_channel_probe,
);
}
// -------------------------------------------------------------------
// `TaggedUnion::missing_kind_count` — scalar cardinality refinement
// on the closed-set-COMPLEMENT axis. Pin the three arms (empty parent
// → ALL.len(), single-slot → ALL.len() - 1, saturated → 0) directly
// on the sibling-shaped `LocalParent` scaffold and the composition
// law `missing_kind_count() == missing_kinds().len()` + the scalar
// partition law `populated_kind_count + missing_kind_count ==
// ALL.len()` at the substrate testkit
// `assert_missing_kind_count_matches_missing_kinds`.
// -------------------------------------------------------------------
/// EMPTY parent — the default body's `ALL.filter(!has).count()`
/// sweep yields `ALL.len()` when no slot is populated. Pins the
/// full-cardinality complement arm.
#[test]
fn tagged_union_default_missing_kind_count_returns_all_len_on_empty_parent() {
let empty = LocalParent::default();
assert_eq!(
<LocalParent as TaggedUnion>::missing_kind_count(&empty),
<LocalKind as tatara_closed_set::ClosedSet>::ALL.len(),
"missing_kind_count() must return ALL.len() when no slot is populated",
);
}
/// SINGLE-SLOT parent — the default body sweeps `ClosedSet::ALL`
/// with `!has(k)` and counts `ALL.len() - 1` for each single-
/// populated arrangement. Pins the well-formed arm's complement
/// cardinality per addressed kind.
#[test]
fn tagged_union_default_missing_kind_count_returns_all_len_minus_one_per_single_slot_variant() {
let expected = <LocalKind as tatara_closed_set::ClosedSet>::ALL.len() - 1;
for populated in <LocalKind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let parent = match populated {
LocalKind::Alpha => LocalParent {
alpha: Some(11),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(22),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(33),
..Default::default()
},
};
assert_eq!(
<LocalParent as TaggedUnion>::missing_kind_count(&parent),
expected,
"single-slot parent must return ALL.len() - 1 on missing_kind_count for {populated:?}",
);
}
}
/// SATURATED parent — every slot populated returns `0` on
/// `missing_kind_count`. Pins the zero-cardinality complement arm
/// (mirror of `populated_kind_count` returning `ALL.len()` on the
/// saturated arm).
#[test]
fn tagged_union_default_missing_kind_count_returns_zero_on_saturated_parent() {
let saturated = LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: Some(3),
};
assert_eq!(
<LocalParent as TaggedUnion>::missing_kind_count(&saturated),
0,
"saturated parent must return 0 on missing_kind_count",
);
}
/// Composition law `missing_kind_count() == missing_kinds().len()`
/// binds the scalar cardinality projection to the widened primitive
/// across every `ClosedSet::ALL × {empty, single_slot, two_slot,
/// saturated}` combination. AND the scalar partition law
/// `populated_kind_count() + missing_kind_count() == ALL.len()`
/// binds the two axes byte-identically. Pins BOTH invariants at
/// ONE test.
#[test]
fn tagged_union_default_missing_kind_count_matches_missing_kinds_len_and_partitions() {
let all_len = <LocalKind as tatara_closed_set::ClosedSet>::ALL.len();
let arrangements: [LocalParent; 4] = [
LocalParent::default(),
LocalParent {
alpha: Some(1),
..Default::default()
},
LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: None,
},
LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: Some(3),
},
];
for (idx, parent) in arrangements.iter().enumerate() {
let count = <LocalParent as TaggedUnion>::missing_kind_count(parent);
let missing_len = <LocalParent as TaggedUnion>::missing_kinds(parent).len();
assert_eq!(
count, missing_len,
"missing_kind_count() must equal missing_kinds().len() for arrangement idx {idx}",
);
let populated_count = <LocalParent as TaggedUnion>::populated_kind_count(parent);
assert_eq!(
populated_count + count,
all_len,
"scalar partition law violated at arrangement idx {idx} — populated_kind_count + missing_kind_count must equal ALL.len()",
);
}
}
/// `assert_missing_kind_count_matches_missing_kinds` testkit
/// accepts the coherent local scaffold — sweeping every populated
/// kind through the three sub-assertions (composition law
/// `count == missing_kinds.len()` + single-slot diagonal `count ==
/// ALL.len() - 1` + scalar partition law
/// `populated_kind_count + missing_kind_count == ALL.len()`). A
/// regression on any of the three fails at the substrate
/// primitive's `#[track_caller]` boundary.
#[test]
fn assert_missing_kind_count_matches_missing_kinds_accepts_coherent_local_impl() {
fn make_local(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(11),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(22),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(33),
..Default::default()
},
}
}
assert_missing_kind_count_matches_missing_kinds::<LocalParent, _>(make_local);
}
/// A factory that yields an all-empty parent (so
/// `missing_kind_count()` returns `ALL.len()`) MUST fail-loudly at
/// the caller's site through the primitive's single-slot diagonal
/// arm — the `ALL.len()` cardinality does not equal `ALL.len() - 1`.
#[test]
#[should_panic(expected = "must equal ALL.len() - 1 exactly")]
fn assert_missing_kind_count_matches_missing_kinds_rejects_empty_factory() {
fn empty_factory(_: LocalKind) -> LocalParent {
LocalParent::default()
}
assert_missing_kind_count_matches_missing_kinds::<LocalParent, _>(empty_factory);
}
/// Every one of the four production `.variant()` sites on
/// `ProcessSpec` binds through the scalar-cardinality complement
/// primitive `assert_missing_kind_count_matches_missing_kinds`
/// coherently — every per-site `single_slot_X(k)` factory produces
/// a parent whose `missing_kind_count()` equals `ALL.len() - 1`
/// AND whose composition law `count == missing_kinds().len()` AND
/// scalar partition law `populated_kind_count + missing_kind_count
/// == ALL.len()` all hold. Sweep every production implementor at
/// ONE substrate boundary.
#[test]
fn every_production_tagged_union_binds_through_the_missing_kind_count_testkit_primitive() {
assert_missing_kind_count_matches_missing_kinds::<crate::intent::Intent, _>(
single_slot_intent_probe,
);
assert_missing_kind_count_matches_missing_kinds::<crate::encapsulates::EncapsulationKind, _>(
single_slot_encapsulation_kind_probe,
);
assert_missing_kind_count_matches_missing_kinds::<crate::export::ArtifactSource, _>(
single_slot_artifact_source_probe,
);
assert_missing_kind_count_matches_missing_kinds::<crate::export::VectorChannel, _>(
single_slot_vector_channel_probe,
);
}
// -------------------------------------------------------------------
// `TaggedUnion::first_populated_kind` / `first_missing_kind` — the
// short-circuiting `Option<Kind>` peers of `populated_kinds` /
// `missing_kinds`. Pin the four-outcome truth table (empty parent
// → `first_populated_kind` is `None`, `first_missing_kind` is
// `Some(ALL[0])`; populated diagonal → `first_populated_kind` is
// `Some(k)`, `first_missing_kind` is the earliest `ALL` entry
// != `k`; multi-populated → `first_populated_kind` names the
// EARLIEST populated slot in canonical `ALL` order) directly on
// the `LocalParent` scaffold AND via the substrate testkit
// primitives, so a regression on the default body's short-circuit
// or negation composition fails here before any per-parent
// inherent test surfaces the drift.
// -------------------------------------------------------------------
/// EMPTY-PARENT pin — a default [`LocalParent`] returns `None` at
/// `first_populated_kind` (no slot populated) and `Some(ALL[0])` at
/// `first_missing_kind` (every slot missing, earliest hit is
/// index 0 of the canonical closed-set walk). Composition-law pin:
/// `first_populated_kind().is_none() == (populated_kind_count() ==
/// 0)` and `first_missing_kind() == Some(ALL[0])` on the empty
/// boundary.
#[test]
fn tagged_union_default_first_kinds_on_empty_parent() {
let empty = LocalParent::default();
assert_eq!(
<LocalParent as TaggedUnion>::first_populated_kind(&empty),
None,
);
assert_eq!(
<LocalParent as TaggedUnion>::first_missing_kind(&empty),
Some(<LocalKind as tatara_closed_set::ClosedSet>::ALL[0]),
);
}
/// SINGLE-SLOT DIAGONAL pin — every populated position across
/// [`LocalKind::ALL`] returns `Some(k)` at `first_populated_kind`
/// (the sole populated slot IS the earliest one) AND the earliest
/// `ALL` entry != `k` at `first_missing_kind`. Both projections
/// agree with the widened primitives via
/// `first_populated_kind() == populated_kinds().first().copied()`
/// and `first_missing_kind() == missing_kinds().first().copied()`.
#[test]
fn tagged_union_default_first_kinds_on_single_slot_diagonal() {
for populated in <LocalKind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let parent = match populated {
LocalKind::Alpha => LocalParent {
alpha: Some(11),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(22),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(33),
..Default::default()
},
};
assert_eq!(
<LocalParent as TaggedUnion>::first_populated_kind(&parent),
Some(populated),
);
let expected_first_missing = <LocalKind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
.find(|k| *k != populated);
assert_eq!(
<LocalParent as TaggedUnion>::first_missing_kind(&parent),
expected_first_missing,
);
// Composition laws vs. widened primitives.
assert_eq!(
parent.first_populated_kind(),
parent.populated_kinds().first().copied(),
);
assert_eq!(
parent.first_missing_kind(),
parent.missing_kinds().first().copied(),
);
}
}
/// TWO-POPULATED pin — a `LocalParent` with two populated slots
/// returns `first_populated_kind() == Some(min_all(a, b))` (the
/// EARLIEST populated slot in canonical `ClosedSet::ALL` order —
/// strictly more informative than the payload-free
/// [`LocalParentError::Ambiguous`] carrier `variant()` returns on
/// the same input). Pins the walk order on the Ambiguous arm at
/// ONE substrate boundary — a regression that iterates `ALL` in
/// reverse or in construction order fails here.
#[test]
fn tagged_union_default_first_populated_kind_names_earliest_of_two_populated_slots() {
// Alpha + Beta populated → earliest is Alpha (ALL[0]).
let p = LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: None,
};
assert_eq!(p.first_populated_kind(), Some(LocalKind::Alpha));
// Missing set is [Gamma]; earliest missing is Gamma.
assert_eq!(p.first_missing_kind(), Some(LocalKind::Gamma));
// Beta + Gamma populated → earliest is Beta.
let p = LocalParent {
alpha: None,
beta: Some(1),
gamma: Some(2),
};
assert_eq!(p.first_populated_kind(), Some(LocalKind::Beta));
assert_eq!(p.first_missing_kind(), Some(LocalKind::Alpha));
// Alpha + Gamma populated → earliest is Alpha.
let p = LocalParent {
alpha: Some(1),
beta: None,
gamma: Some(2),
};
assert_eq!(p.first_populated_kind(), Some(LocalKind::Alpha));
assert_eq!(p.first_missing_kind(), Some(LocalKind::Beta));
}
/// SATURATED-PARENT pin — a `LocalParent` with EVERY slot
/// populated returns `Some(ALL[0])` at `first_populated_kind`
/// (earliest hit on the all-`true` predicate is index 0) and
/// `None` at `first_missing_kind` (no missing slot exists). Pins
/// the earliest-missing projection's `None` arm at ONE substrate
/// boundary — a regression that returned `Some(ALL[0])` (dropping
/// the negation) or `Some(ALL[ALL.len()-1])` (walking in reverse)
/// fails here.
#[test]
fn tagged_union_default_first_missing_kind_returns_none_on_saturated_parent() {
let p = LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: Some(3),
};
assert_eq!(p.first_populated_kind(), Some(LocalKind::Alpha));
assert_eq!(p.first_missing_kind(), None);
}
/// The `assert_first_populated_kind_matches_populated_kinds`
/// primitive accepts the [`LocalParent`] scaffold coherently — the
/// Ok arm is the "no drift" outcome.
#[test]
fn assert_first_populated_kind_matches_populated_kinds_accepts_coherent_local_impl() {
fn make_local(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(11),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(22),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(33),
..Default::default()
},
}
}
assert_first_populated_kind_matches_populated_kinds::<LocalParent, _>(make_local);
}
/// A factory that yields an all-empty parent (so
/// `first_populated_kind()` returns `None`) MUST fail-loudly at
/// the caller's site through the primitive's single-slot diagonal
/// arm — `None` does not equal `Some(populated)`.
#[test]
#[should_panic(expected = "must equal Some(")]
fn assert_first_populated_kind_matches_populated_kinds_rejects_empty_factory() {
fn empty_factory(_: LocalKind) -> LocalParent {
LocalParent::default()
}
assert_first_populated_kind_matches_populated_kinds::<LocalParent, _>(empty_factory);
}
/// The `assert_first_missing_kind_matches_missing_kinds` primitive
/// accepts the [`LocalParent`] scaffold coherently.
#[test]
fn assert_first_missing_kind_matches_missing_kinds_accepts_coherent_local_impl() {
fn make_local(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(11),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(22),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(33),
..Default::default()
},
}
}
assert_first_missing_kind_matches_missing_kinds::<LocalParent, _>(make_local);
}
/// Every one of the four production `.variant()` sites on
/// `ProcessSpec` binds through the earliest-populated primitive
/// coherently — every per-site `single_slot_X(k)` factory produces
/// a parent whose `first_populated_kind()` equals `Some(k)`.
#[test]
fn every_production_tagged_union_binds_through_the_first_populated_kind_testkit_primitive() {
assert_first_populated_kind_matches_populated_kinds::<crate::intent::Intent, _>(
single_slot_intent_probe,
);
assert_first_populated_kind_matches_populated_kinds::<
crate::encapsulates::EncapsulationKind,
_,
>(single_slot_encapsulation_kind_probe);
assert_first_populated_kind_matches_populated_kinds::<crate::export::ArtifactSource, _>(
single_slot_artifact_source_probe,
);
assert_first_populated_kind_matches_populated_kinds::<crate::export::VectorChannel, _>(
single_slot_vector_channel_probe,
);
}
/// Every one of the four production `.variant()` sites on
/// `ProcessSpec` binds through the earliest-missing primitive
/// coherently.
#[test]
fn every_production_tagged_union_binds_through_the_first_missing_kind_testkit_primitive() {
assert_first_missing_kind_matches_missing_kinds::<crate::intent::Intent, _>(
single_slot_intent_probe,
);
assert_first_missing_kind_matches_missing_kinds::<crate::encapsulates::EncapsulationKind, _>(
single_slot_encapsulation_kind_probe,
);
assert_first_missing_kind_matches_missing_kinds::<crate::export::ArtifactSource, _>(
single_slot_artifact_source_probe,
);
assert_first_missing_kind_matches_missing_kinds::<crate::export::VectorChannel, _>(
single_slot_vector_channel_probe,
);
}
// -------------------------------------------------------------------
// `TaggedUnion::last_populated_kind` / `last_missing_kind` — the
// short-circuiting REVERSED-walk `Option<Kind>` peers of
// `first_populated_kind` / `first_missing_kind`. Pin the four-outcome
// truth table (empty parent → `last_populated_kind` is `None`,
// `last_missing_kind` is `Some(ALL[ALL.len()-1])`; populated diagonal
// → `last_populated_kind` is `Some(k)`, `last_missing_kind` is the
// latest `ALL` entry != `k`; multi-populated → `last_populated_kind`
// names the LATEST populated slot in canonical `ALL` order;
// saturated → `last_missing_kind` is `None`) directly on the
// `LocalParent` scaffold AND via the substrate testkit primitives,
// so a regression on the reversed default body's short-circuit or
// negation composition fails here before any per-parent inherent
// test surfaces the drift.
// -------------------------------------------------------------------
/// EMPTY-PARENT pin — a default [`LocalParent`] returns `None` at
/// `last_populated_kind` (no slot populated) and
/// `Some(ALL[ALL.len()-1])` at `last_missing_kind` (every slot
/// missing, latest hit is the last index of the canonical closed-
/// set walk under REVERSED iteration). Composition-law pin:
/// `last_populated_kind().is_none() == (populated_kind_count() ==
/// 0)` and `last_missing_kind() == Some(ALL[ALL.len()-1])` on the
/// empty boundary.
#[test]
fn tagged_union_default_last_kinds_on_empty_parent() {
let empty = LocalParent::default();
assert_eq!(
<LocalParent as TaggedUnion>::last_populated_kind(&empty),
None,
);
let all_len = <LocalKind as tatara_closed_set::ClosedSet>::ALL.len();
assert_eq!(
<LocalParent as TaggedUnion>::last_missing_kind(&empty),
Some(<LocalKind as tatara_closed_set::ClosedSet>::ALL[all_len - 1]),
);
}
/// SINGLE-SLOT DIAGONAL pin — every populated position across
/// [`LocalKind::ALL`] returns `Some(k)` at `last_populated_kind`
/// (the sole populated slot IS both the earliest AND the latest)
/// AND the LATEST `ALL` entry != `k` at `last_missing_kind`. Both
/// projections agree with the widened primitives via
/// `last_populated_kind() == populated_kinds().last().copied()`
/// and `last_missing_kind() == missing_kinds().last().copied()`.
#[test]
fn tagged_union_default_last_kinds_on_single_slot_diagonal() {
for populated in <LocalKind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let parent = match populated {
LocalKind::Alpha => LocalParent {
alpha: Some(11),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(22),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(33),
..Default::default()
},
};
assert_eq!(
<LocalParent as TaggedUnion>::last_populated_kind(&parent),
Some(populated),
);
let expected_last_missing = <LocalKind as tatara_closed_set::ClosedSet>::ALL
.iter()
.rev()
.copied()
.find(|k| *k != populated);
assert_eq!(
<LocalParent as TaggedUnion>::last_missing_kind(&parent),
expected_last_missing,
);
// Composition laws vs. widened primitives.
assert_eq!(
parent.last_populated_kind(),
parent.populated_kinds().last().copied(),
);
assert_eq!(
parent.last_missing_kind(),
parent.missing_kinds().last().copied(),
);
}
}
/// TWO-POPULATED pin — a `LocalParent` with two populated slots
/// returns `last_populated_kind() == Some(max_all(a, b))` (the
/// LATEST populated slot in canonical `ClosedSet::ALL` order —
/// byte-for-byte time-reversed peer of the earliest-populated
/// projection). Pins the walk order on the Ambiguous arm at ONE
/// substrate boundary — a regression that iterates `ALL` forward
/// (defeating the time-reversal) fails here.
#[test]
fn tagged_union_default_last_populated_kind_names_latest_of_two_populated_slots() {
// Alpha + Beta populated → latest is Beta (ALL[1]).
let p = LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: None,
};
assert_eq!(p.last_populated_kind(), Some(LocalKind::Beta));
// Missing set is [Gamma]; latest missing is Gamma.
assert_eq!(p.last_missing_kind(), Some(LocalKind::Gamma));
// Beta + Gamma populated → latest is Gamma.
let p = LocalParent {
alpha: None,
beta: Some(1),
gamma: Some(2),
};
assert_eq!(p.last_populated_kind(), Some(LocalKind::Gamma));
assert_eq!(p.last_missing_kind(), Some(LocalKind::Alpha));
// Alpha + Gamma populated → latest is Gamma.
let p = LocalParent {
alpha: Some(1),
beta: None,
gamma: Some(2),
};
assert_eq!(p.last_populated_kind(), Some(LocalKind::Gamma));
assert_eq!(p.last_missing_kind(), Some(LocalKind::Beta));
}
/// SATURATED-PARENT pin — a `LocalParent` with EVERY slot
/// populated returns `Some(ALL[ALL.len()-1])` at
/// `last_populated_kind` (latest hit on the all-`true` predicate
/// under REVERSED iteration is the last index) and `None` at
/// `last_missing_kind` (no missing slot exists). Pins the latest-
/// missing projection's `None` arm at ONE substrate boundary — a
/// regression that returned `Some(ALL[ALL.len()-1])` (dropping the
/// negation) or `Some(ALL[0])` (defeating the time-reversal)
/// fails here.
#[test]
fn tagged_union_default_last_missing_kind_returns_none_on_saturated_parent() {
let p = LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: Some(3),
};
let all_len = <LocalKind as tatara_closed_set::ClosedSet>::ALL.len();
assert_eq!(
p.last_populated_kind(),
Some(<LocalKind as tatara_closed_set::ClosedSet>::ALL[all_len - 1]),
);
assert_eq!(p.last_missing_kind(), None);
}
/// The `assert_last_populated_kind_matches_populated_kinds`
/// primitive accepts the [`LocalParent`] scaffold coherently — the
/// Ok arm is the "no drift" outcome.
#[test]
fn assert_last_populated_kind_matches_populated_kinds_accepts_coherent_local_impl() {
fn make_local(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(11),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(22),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(33),
..Default::default()
},
}
}
assert_last_populated_kind_matches_populated_kinds::<LocalParent, _>(make_local);
}
/// A factory that yields an all-empty parent (so
/// `last_populated_kind()` returns `None`) MUST fail-loudly at the
/// caller's site through the primitive's single-slot diagonal arm
/// — `None` does not equal `Some(populated)`.
#[test]
#[should_panic(expected = "must equal Some(")]
fn assert_last_populated_kind_matches_populated_kinds_rejects_empty_factory() {
fn empty_factory(_: LocalKind) -> LocalParent {
LocalParent::default()
}
assert_last_populated_kind_matches_populated_kinds::<LocalParent, _>(empty_factory);
}
/// The `assert_last_missing_kind_matches_missing_kinds` primitive
/// accepts the [`LocalParent`] scaffold coherently.
#[test]
fn assert_last_missing_kind_matches_missing_kinds_accepts_coherent_local_impl() {
fn make_local(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(11),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(22),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(33),
..Default::default()
},
}
}
assert_last_missing_kind_matches_missing_kinds::<LocalParent, _>(make_local);
}
/// Every one of the four production `.variant()` sites on
/// `ProcessSpec` binds through the latest-populated primitive
/// coherently — every per-site `single_slot_X(k)` factory produces
/// a parent whose `last_populated_kind()` equals `Some(k)`.
#[test]
fn every_production_tagged_union_binds_through_the_last_populated_kind_testkit_primitive() {
assert_last_populated_kind_matches_populated_kinds::<crate::intent::Intent, _>(
single_slot_intent_probe,
);
assert_last_populated_kind_matches_populated_kinds::<
crate::encapsulates::EncapsulationKind,
_,
>(single_slot_encapsulation_kind_probe);
assert_last_populated_kind_matches_populated_kinds::<crate::export::ArtifactSource, _>(
single_slot_artifact_source_probe,
);
assert_last_populated_kind_matches_populated_kinds::<crate::export::VectorChannel, _>(
single_slot_vector_channel_probe,
);
}
/// Every one of the four production `.variant()` sites on
/// `ProcessSpec` binds through the latest-missing primitive
/// coherently.
#[test]
fn every_production_tagged_union_binds_through_the_last_missing_kind_testkit_primitive() {
assert_last_missing_kind_matches_missing_kinds::<crate::intent::Intent, _>(
single_slot_intent_probe,
);
assert_last_missing_kind_matches_missing_kinds::<crate::encapsulates::EncapsulationKind, _>(
single_slot_encapsulation_kind_probe,
);
assert_last_missing_kind_matches_missing_kinds::<crate::export::ArtifactSource, _>(
single_slot_artifact_source_probe,
);
assert_last_missing_kind_matches_missing_kinds::<crate::export::VectorChannel, _>(
single_slot_vector_channel_probe,
);
}
// -------------------------------------------------------------------
// `TaggedUnion::unique_populated_kind` / `unique_missing_kind` — the
// short-circuiting `Option<Kind>` peers on the exactly-one-hit axis.
// Pin the four-outcome truth table (empty parent → both `None`;
// single-slot diagonal → `unique_populated_kind` is `Some(k)`,
// `unique_missing_kind` is `None` on `ALL.len() > 2`; two-populated
// parent → `unique_populated_kind` is `None`, `unique_missing_kind`
// is `Some(the-one-missing)`; saturated → both `None`) directly on
// the `LocalParent` scaffold AND via the substrate testkit
// primitives, so a regression on the two-step short-circuit's
// second-hit truncation or the negation composition fails here
// before any per-parent inherent test surfaces the drift.
// -------------------------------------------------------------------
/// EMPTY-PARENT pin — a default [`LocalParent`] returns `None` at
/// BOTH `unique_populated_kind` (zero populated, not exactly-one)
/// and `unique_missing_kind` (three missing on a `ALL.len() == 3`
/// closed set, not exactly-one). Pins the empty-arm collapse — the
/// two primitives agree on `None` when the closed-set cardinality
/// is ≥ 3, distinguishing the exactly-one primitive from the
/// endpoint primitives (`first_missing_kind` on an empty parent
/// returns `Some(ALL[0])`, not `None`).
#[test]
fn tagged_union_default_unique_kinds_on_empty_parent() {
let empty = LocalParent::default();
assert_eq!(
<LocalParent as TaggedUnion>::unique_populated_kind(&empty),
None,
);
assert_eq!(
<LocalParent as TaggedUnion>::unique_missing_kind(&empty),
None,
);
}
/// SINGLE-SLOT DIAGONAL pin — every populated position across
/// [`LocalKind::ALL`] returns `Some(k)` at `unique_populated_kind`
/// (the sole populated slot IS the exactly-one hit) AND `None` at
/// `unique_missing_kind` (two missing slots on the `ALL.len() == 3`
/// closed set, not exactly-one). The `Some` arm's endpoint
/// agreement composes with `first_populated_kind` /
/// `last_populated_kind` at the trait defaults (`unique == first
/// == last` on exactly-one).
#[test]
fn tagged_union_default_unique_kinds_on_single_slot_diagonal() {
for populated in <LocalKind as tatara_closed_set::ClosedSet>::ALL
.iter()
.copied()
{
let parent = match populated {
LocalKind::Alpha => LocalParent {
alpha: Some(11),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(22),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(33),
..Default::default()
},
};
assert_eq!(
<LocalParent as TaggedUnion>::unique_populated_kind(&parent),
Some(populated),
);
assert_eq!(
<LocalParent as TaggedUnion>::unique_missing_kind(&parent),
None,
);
// Endpoint-agreement composition — on Some, the three
// endpoint-projection primitives agree.
assert_eq!(
parent.unique_populated_kind(),
parent.first_populated_kind()
);
assert_eq!(parent.unique_populated_kind(), parent.last_populated_kind());
}
}
/// TWO-POPULATED pin — a `LocalParent` with two populated slots
/// returns `unique_populated_kind() == None` (two populated, not
/// exactly-one) and `unique_missing_kind() == Some(the-one-missing)`
/// (one missing, exactly-one — the ONLY arm where the missing-side
/// primitive returns `Some` on a `ALL.len() == 3` closed set). Pins
/// the two-step short-circuit's second-hit collapse at ONE
/// substrate boundary — a regression that returned `Some(first)`
/// after seeing two populated slots (defeating the exactly-one
/// contract) fails here.
#[test]
fn tagged_union_default_unique_kinds_on_two_populated_parent() {
// Alpha + Beta populated → 2 populated (unique_populated=None),
// 1 missing = Gamma (unique_missing=Some(Gamma)).
let p = LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: None,
};
assert_eq!(p.unique_populated_kind(), None);
assert_eq!(p.unique_missing_kind(), Some(LocalKind::Gamma));
// Endpoint-agreement composition on the missing-side Some arm.
assert_eq!(p.unique_missing_kind(), p.first_missing_kind());
assert_eq!(p.unique_missing_kind(), p.last_missing_kind());
// Beta + Gamma populated → unique_missing=Some(Alpha).
let p = LocalParent {
alpha: None,
beta: Some(1),
gamma: Some(2),
};
assert_eq!(p.unique_populated_kind(), None);
assert_eq!(p.unique_missing_kind(), Some(LocalKind::Alpha));
// Alpha + Gamma populated → unique_missing=Some(Beta).
let p = LocalParent {
alpha: Some(1),
beta: None,
gamma: Some(2),
};
assert_eq!(p.unique_populated_kind(), None);
assert_eq!(p.unique_missing_kind(), Some(LocalKind::Beta));
}
/// SATURATED-PARENT pin — a `LocalParent` with EVERY slot
/// populated returns `None` at BOTH `unique_populated_kind` (three
/// populated, not exactly-one) AND `unique_missing_kind` (zero
/// missing, not exactly-one). Pins the saturated-arm collapse — the
/// two primitives agree on `None` when the closed-set cardinality
/// is ≥ 3, distinguishing the exactly-one primitive from the
/// endpoint primitives (`last_populated_kind` on a saturated
/// parent returns `Some(ALL[ALL.len()-1])`, not `None`).
#[test]
fn tagged_union_default_unique_kinds_on_saturated_parent() {
let p = LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: Some(3),
};
assert_eq!(p.unique_populated_kind(), None);
assert_eq!(p.unique_missing_kind(), None);
}
/// The `assert_unique_populated_kind_matches_populated_kinds`
/// primitive accepts the [`LocalParent`] scaffold coherently — the
/// Ok arm is the "no drift" outcome.
#[test]
fn assert_unique_populated_kind_matches_populated_kinds_accepts_coherent_local_impl() {
fn make_local(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(11),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(22),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(33),
..Default::default()
},
}
}
assert_unique_populated_kind_matches_populated_kinds::<LocalParent, _>(make_local);
}
/// A factory that yields an all-empty parent (so
/// `unique_populated_kind()` returns `None`) MUST fail-loudly at
/// the caller's site through the primitive's single-slot diagonal
/// arm — `None` does not equal `Some(populated)`.
#[test]
#[should_panic(expected = "must equal Some(")]
fn assert_unique_populated_kind_matches_populated_kinds_rejects_empty_factory() {
fn empty_factory(_: LocalKind) -> LocalParent {
LocalParent::default()
}
assert_unique_populated_kind_matches_populated_kinds::<LocalParent, _>(empty_factory);
}
/// The `assert_unique_missing_kind_matches_missing_kinds` primitive
/// accepts the [`LocalParent`] scaffold coherently.
#[test]
fn assert_unique_missing_kind_matches_missing_kinds_accepts_coherent_local_impl() {
fn make_local(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(11),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(22),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(33),
..Default::default()
},
}
}
assert_unique_missing_kind_matches_missing_kinds::<LocalParent, _>(make_local);
}
/// Every one of the four production `.variant()` sites on
/// `ProcessSpec` binds through the exactly-one-populated primitive
/// coherently — every per-site `single_slot_X(k)` factory produces
/// a parent whose `unique_populated_kind()` equals `Some(k)`.
#[test]
fn every_production_tagged_union_binds_through_the_unique_populated_kind_testkit_primitive() {
assert_unique_populated_kind_matches_populated_kinds::<crate::intent::Intent, _>(
single_slot_intent_probe,
);
assert_unique_populated_kind_matches_populated_kinds::<
crate::encapsulates::EncapsulationKind,
_,
>(single_slot_encapsulation_kind_probe);
assert_unique_populated_kind_matches_populated_kinds::<crate::export::ArtifactSource, _>(
single_slot_artifact_source_probe,
);
assert_unique_populated_kind_matches_populated_kinds::<crate::export::VectorChannel, _>(
single_slot_vector_channel_probe,
);
}
/// Every one of the four production `.variant()` sites on
/// `ProcessSpec` binds through the exactly-one-missing primitive
/// coherently.
#[test]
fn every_production_tagged_union_binds_through_the_unique_missing_kind_testkit_primitive() {
assert_unique_missing_kind_matches_missing_kinds::<crate::intent::Intent, _>(
single_slot_intent_probe,
);
assert_unique_missing_kind_matches_missing_kinds::<crate::encapsulates::EncapsulationKind, _>(
single_slot_encapsulation_kind_probe,
);
assert_unique_missing_kind_matches_missing_kinds::<crate::export::ArtifactSource, _>(
single_slot_artifact_source_probe,
);
assert_unique_missing_kind_matches_missing_kinds::<crate::export::VectorChannel, _>(
single_slot_vector_channel_probe,
);
}
// -------------------------------------------------------------------
// `TaggedUnion::is_empty` / `TaggedUnion::is_saturated` trait-level
// truth-table pins on the sibling-shaped `LocalParent` scaffold.
// The two primitives are the Boolean cardinality-endpoint peers of
// `populated_kind_count() == 0` and `missing_kind_count() == 0`
// respectively — every arm below pins one truth-table entry directly
// on the trait's default body without reaching for either scalar
// primitive.
// -------------------------------------------------------------------
/// EMPTY-PARENT pin — a default-constructed `LocalParent` (every
/// slot None) returns `true` at `is_empty` (zero populated slots)
/// AND `false` at `is_saturated` (three missing slots, not zero).
/// Pins the zero-arm of the `is_empty` primitive and the negation
/// of the `is_saturated` primitive on the same fixture — a
/// regression that inverted either default body's composition
/// direction fails here.
#[test]
fn tagged_union_default_is_empty_and_is_saturated_on_empty_parent() {
let p = LocalParent::default();
assert!(p.is_empty(), "empty parent must be is_empty");
assert!(!p.is_saturated(), "empty parent must NOT be is_saturated");
// Composition law with the scalar cardinality primitives.
assert_eq!(p.is_empty(), p.populated_kind_count() == 0);
assert_eq!(p.is_saturated(), p.missing_kind_count() == 0);
// Widened-primitive agreement.
assert_eq!(p.is_empty(), p.populated_kinds().is_empty());
assert_eq!(p.is_saturated(), p.missing_kinds().is_empty());
}
/// SINGLE-SLOT-DIAGONAL pin — a `LocalParent` populating exactly
/// one slot returns `false` at BOTH `is_empty` (one populated, not
/// zero) AND `is_saturated` (two missing, not zero). Pins that a
/// well-formed parent lands OUTSIDE both cardinality endpoints —
/// the Boolean primitives coincide on `false` on this arm, and
/// only on the empty parent (`is_empty` true) or a saturated
/// parent (`is_saturated` true) do they diverge.
#[test]
fn tagged_union_default_is_empty_and_is_saturated_on_single_slot_diagonal() {
for (populated, parent) in [
(
LocalKind::Alpha,
LocalParent {
alpha: Some(1),
..Default::default()
},
),
(
LocalKind::Beta,
LocalParent {
beta: Some(2),
..Default::default()
},
),
(
LocalKind::Gamma,
LocalParent {
gamma: Some(3),
..Default::default()
},
),
] {
assert!(
!parent.is_empty(),
"single_slot({populated:?}) must NOT be is_empty",
);
assert!(
!parent.is_saturated(),
"single_slot({populated:?}) must NOT be is_saturated",
);
assert_eq!(parent.is_empty(), parent.populated_kind_count() == 0);
assert_eq!(parent.is_saturated(), parent.missing_kind_count() == 0);
}
}
/// SATURATED-PARENT pin — a `LocalParent` with EVERY slot populated
/// returns `false` at `is_empty` (three populated, not zero) AND
/// `true` at `is_saturated` (zero missing). Pins the top-arm of
/// the `is_saturated` primitive and the negation of the `is_empty`
/// primitive on the same fixture — the mirror of the empty-parent
/// pin above, distinguishing the two cardinality endpoints on
/// opposite arms of the same closed-set walk.
#[test]
fn tagged_union_default_is_empty_and_is_saturated_on_saturated_parent() {
let p = LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: Some(3),
};
assert!(!p.is_empty(), "saturated parent must NOT be is_empty");
assert!(p.is_saturated(), "saturated parent must be is_saturated");
assert_eq!(p.is_empty(), p.populated_kind_count() == 0);
assert_eq!(p.is_saturated(), p.missing_kind_count() == 0);
assert_eq!(p.is_empty(), p.populated_kinds().is_empty());
assert_eq!(p.is_saturated(), p.missing_kinds().is_empty());
}
// -------------------------------------------------------------------
// Truth-table pins for `TaggedUnion::has_unique_populated_kind` and
// `TaggedUnion::has_unique_missing_kind` — three arms (empty,
// single-slot diagonal, saturated) on the sibling-shaped
// `LocalParent` scaffold. The two primitives are the Boolean
// cardinality-mid-endpoint peers of `populated_kind_count() == 1`
// and `missing_kind_count() == 1` respectively — every arm below
// pins one truth-table entry directly on the trait's default body
// without reaching for either scalar primitive.
// -------------------------------------------------------------------
/// EMPTY-PARENT pin — a default-constructed `LocalParent` (every
/// slot None) returns `false` at BOTH `has_unique_populated_kind`
/// (zero populated, not one) AND `has_unique_missing_kind` (three
/// missing on `ALL.len() == 3`, not one). Pins the zero-populated
/// arm of the first primitive and the ALL.len()-missing arm of the
/// second on the same fixture.
#[test]
fn tagged_union_default_has_unique_kinds_on_empty_parent() {
let p = LocalParent::default();
assert!(
!p.has_unique_populated_kind(),
"empty parent must NOT be has_unique_populated_kind (zero populated)",
);
assert!(
!p.has_unique_missing_kind(),
"empty parent must NOT be has_unique_missing_kind (three missing)",
);
// Composition law with the scalar cardinality primitives.
assert_eq!(p.has_unique_populated_kind(), p.populated_kind_count() == 1);
assert_eq!(p.has_unique_missing_kind(), p.missing_kind_count() == 1);
// Unique-primitive agreement.
assert_eq!(
p.has_unique_populated_kind(),
p.unique_populated_kind().is_some()
);
assert_eq!(
p.has_unique_missing_kind(),
p.unique_missing_kind().is_some()
);
}
/// SINGLE-SLOT-DIAGONAL pin — a `LocalParent` populating exactly
/// one slot returns `true` at `has_unique_populated_kind` (one
/// populated) AND `false` at `has_unique_missing_kind` (two
/// missing on `ALL.len() == 3`, not one). Pins that the well-
/// formed arm coincides with the one-arm of the populated
/// cardinality and lies OUTSIDE the one-arm of the missing
/// cardinality on any `ALL.len() ≥ 3` closed set.
#[test]
fn tagged_union_default_has_unique_kinds_on_single_slot_diagonal() {
for (populated, parent) in [
(
LocalKind::Alpha,
LocalParent {
alpha: Some(1),
..Default::default()
},
),
(
LocalKind::Beta,
LocalParent {
beta: Some(2),
..Default::default()
},
),
(
LocalKind::Gamma,
LocalParent {
gamma: Some(3),
..Default::default()
},
),
] {
assert!(
parent.has_unique_populated_kind(),
"single_slot({populated:?}) must be has_unique_populated_kind",
);
assert!(
!parent.has_unique_missing_kind(),
"single_slot({populated:?}) must NOT be has_unique_missing_kind (2 missing on ALL.len()==3)",
);
assert_eq!(
parent.has_unique_populated_kind(),
parent.populated_kind_count() == 1
);
assert_eq!(
parent.has_unique_missing_kind(),
parent.missing_kind_count() == 1
);
}
}
/// SATURATED-PARENT pin — a `LocalParent` with EVERY slot populated
/// returns `false` at BOTH `has_unique_populated_kind` (three
/// populated, not one) AND `has_unique_missing_kind` (zero missing,
/// not one). Pins the top-arm of the populated cardinality (which
/// is NOT the one-arm) and the zero-arm of the missing cardinality
/// (also NOT the one-arm) on the same fixture — the two primitives
/// coincide on `false` here, distinguishing them from the
/// (near-)saturation and near-empty arms outside the LocalParent
/// scaffold's reach.
#[test]
fn tagged_union_default_has_unique_kinds_on_saturated_parent() {
let p = LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: Some(3),
};
assert!(
!p.has_unique_populated_kind(),
"saturated parent must NOT be has_unique_populated_kind (three populated)",
);
assert!(
!p.has_unique_missing_kind(),
"saturated parent must NOT be has_unique_missing_kind (zero missing)",
);
assert_eq!(p.has_unique_populated_kind(), p.populated_kind_count() == 1);
assert_eq!(p.has_unique_missing_kind(), p.missing_kind_count() == 1);
}
/// NEAR-SATURATED (two-slot) pin — a `LocalParent` with exactly
/// two slots populated returns `false` at `has_unique_populated_kind`
/// (two populated, not one) AND `true` at `has_unique_missing_kind`
/// (one missing on `ALL.len() == 3`). This is the SOLE arm on the
/// LocalParent scaffold where the two Boolean cardinality-mid-
/// endpoint peers DIVERGE — the pin distinguishes them from every
/// other truth-table arm where they coincide.
#[test]
fn tagged_union_default_has_unique_kinds_on_near_saturated_parent() {
for parent in [
LocalParent {
alpha: Some(1),
beta: Some(2),
..Default::default()
},
LocalParent {
alpha: Some(1),
gamma: Some(3),
..Default::default()
},
LocalParent {
beta: Some(2),
gamma: Some(3),
..Default::default()
},
] {
assert!(
!parent.has_unique_populated_kind(),
"near-saturated parent must NOT be has_unique_populated_kind (2 populated)",
);
assert!(
parent.has_unique_missing_kind(),
"near-saturated parent must be has_unique_missing_kind (1 missing)",
);
assert_eq!(
parent.has_unique_populated_kind(),
parent.populated_kind_count() == 1,
);
assert_eq!(
parent.has_unique_missing_kind(),
parent.missing_kind_count() == 1,
);
}
}
// -------------------------------------------------------------------
// `TaggedUnion::has_multiple_(populated|missing)_kinds` default-body
// truth table — pin the four cardinality arms (empty, single-slot
// diagonal, near-saturated, saturated) on the sibling-shaped
// `LocalParent` scaffold. These two primitives are the Boolean
// cardinality many-arm peers of `populated_kind_count() >= 2` and
// `missing_kind_count() >= 2` — the third arm of the {0, 1, ≥2}
// cardinality trichotomy that closes alongside `is_empty` /
// `has_unique_populated_kind` (populated axis) and `is_saturated` /
// `has_unique_missing_kind` (missing axis).
// -------------------------------------------------------------------
/// EMPTY-PARENT pin — an empty `LocalParent` returns `false` at
/// `has_multiple_populated_kinds` (zero populated) AND `true` at
/// `has_multiple_missing_kinds` (three missing on `ALL.len() == 3`,
/// which is `>= 2`). Also pins the trichotomy partition law: on
/// the empty arm exactly `is_empty()` is true on the populated
/// axis, and exactly `has_multiple_missing_kinds()` is true on
/// the missing axis.
#[test]
fn tagged_union_default_has_multiple_kinds_on_empty_parent() {
let p = LocalParent::default();
assert!(
!p.has_multiple_populated_kinds(),
"empty parent must NOT be has_multiple_populated_kinds (zero populated)",
);
assert!(
p.has_multiple_missing_kinds(),
"empty parent must be has_multiple_missing_kinds (three missing on ALL.len() == 3)",
);
// Composition laws.
assert_eq!(
p.has_multiple_populated_kinds(),
p.populated_kind_count() >= 2
);
assert_eq!(p.has_multiple_missing_kinds(), p.missing_kind_count() >= 2);
// Trichotomy partition — EXACTLY ONE of the three Boolean
// primitives on each axis is true.
assert_eq!(
usize::from(p.is_empty())
+ usize::from(p.has_unique_populated_kind())
+ usize::from(p.has_multiple_populated_kinds()),
1,
"populated-axis trichotomy must be exactly-one on the empty arm",
);
assert_eq!(
usize::from(p.is_saturated())
+ usize::from(p.has_unique_missing_kind())
+ usize::from(p.has_multiple_missing_kinds()),
1,
"missing-axis trichotomy must be exactly-one on the empty arm",
);
}
/// SINGLE-SLOT-DIAGONAL pin — a `LocalParent` populating exactly
/// one slot returns `false` at `has_multiple_populated_kinds` AND
/// `true` at `has_multiple_missing_kinds` (two missing on
/// `ALL.len() == 3`, which is `>= 2`).
#[test]
fn tagged_union_default_has_multiple_kinds_on_single_slot_diagonal() {
for (populated, parent) in [
(
LocalKind::Alpha,
LocalParent {
alpha: Some(1),
..Default::default()
},
),
(
LocalKind::Beta,
LocalParent {
beta: Some(2),
..Default::default()
},
),
(
LocalKind::Gamma,
LocalParent {
gamma: Some(3),
..Default::default()
},
),
] {
assert!(
!parent.has_multiple_populated_kinds(),
"single_slot({populated:?}) must NOT be has_multiple_populated_kinds",
);
assert!(
parent.has_multiple_missing_kinds(),
"single_slot({populated:?}) must be has_multiple_missing_kinds (2 missing on ALL.len() == 3)",
);
assert_eq!(
parent.has_multiple_populated_kinds(),
parent.populated_kind_count() >= 2,
);
assert_eq!(
parent.has_multiple_missing_kinds(),
parent.missing_kind_count() >= 2,
);
// Trichotomy partition — well-formed arm satisfies
// `has_unique_populated_kind` on the populated axis and
// `has_multiple_missing_kinds` on the missing axis.
assert_eq!(
usize::from(parent.is_empty())
+ usize::from(parent.has_unique_populated_kind())
+ usize::from(parent.has_multiple_populated_kinds()),
1,
"populated-axis trichotomy must be exactly-one on single_slot({populated:?})",
);
assert_eq!(
usize::from(parent.is_saturated())
+ usize::from(parent.has_unique_missing_kind())
+ usize::from(parent.has_multiple_missing_kinds()),
1,
"missing-axis trichotomy must be exactly-one on single_slot({populated:?})",
);
}
}
/// NEAR-SATURATED (two-slot) pin — a `LocalParent` with exactly
/// two slots populated returns `true` at `has_multiple_populated_kinds`
/// (two populated) AND `false` at `has_multiple_missing_kinds`
/// (one missing on `ALL.len() == 3`).
#[test]
fn tagged_union_default_has_multiple_kinds_on_near_saturated_parent() {
for parent in [
LocalParent {
alpha: Some(1),
beta: Some(2),
..Default::default()
},
LocalParent {
alpha: Some(1),
gamma: Some(3),
..Default::default()
},
LocalParent {
beta: Some(2),
gamma: Some(3),
..Default::default()
},
] {
assert!(
parent.has_multiple_populated_kinds(),
"near-saturated parent must be has_multiple_populated_kinds (2 populated)",
);
assert!(
!parent.has_multiple_missing_kinds(),
"near-saturated parent must NOT be has_multiple_missing_kinds (1 missing)",
);
assert_eq!(
parent.has_multiple_populated_kinds(),
parent.populated_kind_count() >= 2,
);
assert_eq!(
parent.has_multiple_missing_kinds(),
parent.missing_kind_count() >= 2,
);
// Trichotomy partition — near-saturated arm satisfies
// `has_multiple_populated_kinds` on the populated axis and
// `has_unique_missing_kind` on the missing axis.
assert_eq!(
usize::from(parent.is_empty())
+ usize::from(parent.has_unique_populated_kind())
+ usize::from(parent.has_multiple_populated_kinds()),
1,
"populated-axis trichotomy must be exactly-one on near-saturated arm",
);
assert_eq!(
usize::from(parent.is_saturated())
+ usize::from(parent.has_unique_missing_kind())
+ usize::from(parent.has_multiple_missing_kinds()),
1,
"missing-axis trichotomy must be exactly-one on near-saturated arm",
);
}
}
/// SATURATED-PARENT pin — a `LocalParent` with EVERY slot
/// populated returns `true` at `has_multiple_populated_kinds`
/// (three populated) AND `false` at `has_multiple_missing_kinds`
/// (zero missing).
#[test]
fn tagged_union_default_has_multiple_kinds_on_saturated_parent() {
let p = LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: Some(3),
};
assert!(
p.has_multiple_populated_kinds(),
"saturated parent must be has_multiple_populated_kinds (three populated)",
);
assert!(
!p.has_multiple_missing_kinds(),
"saturated parent must NOT be has_multiple_missing_kinds (zero missing)",
);
assert_eq!(
p.has_multiple_populated_kinds(),
p.populated_kind_count() >= 2
);
assert_eq!(p.has_multiple_missing_kinds(), p.missing_kind_count() >= 2);
// Trichotomy partition — saturated arm satisfies
// `has_multiple_populated_kinds` on the populated axis and
// `is_saturated` on the missing axis.
assert_eq!(
usize::from(p.is_empty())
+ usize::from(p.has_unique_populated_kind())
+ usize::from(p.has_multiple_populated_kinds()),
1,
"populated-axis trichotomy must be exactly-one on saturated arm",
);
assert_eq!(
usize::from(p.is_saturated())
+ usize::from(p.has_unique_missing_kind())
+ usize::from(p.has_multiple_missing_kinds()),
1,
"missing-axis trichotomy must be exactly-one on saturated arm",
);
}
/// The `assert_is_empty_matches_populated_kind_count` primitive
/// accepts the [`LocalParent`] scaffold coherently.
#[test]
fn assert_is_empty_matches_populated_kind_count_accepts_coherent_local_impl() {
fn make_local(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(11),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(22),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(33),
..Default::default()
},
}
}
assert_is_empty_matches_populated_kind_count::<LocalParent, _, _>(
make_local,
LocalParent::default,
);
}
/// A factory that yields an all-empty parent on the single-slot
/// diagonal (so `is_empty()` returns `true` when the diagonal
/// contract requires `false`) MUST fail-loudly at the caller's
/// site through the primitive's single-slot-diagonal arm — a
/// regression that dropped the `!is_empty` assertion on the
/// well-formed arm surfaces here.
#[test]
#[should_panic(expected = "must equal false")]
fn assert_is_empty_matches_populated_kind_count_rejects_empty_factory() {
fn empty_factory(_: LocalKind) -> LocalParent {
LocalParent::default()
}
assert_is_empty_matches_populated_kind_count::<LocalParent, _, _>(
empty_factory,
LocalParent::default,
);
}
/// A factory that yields a NON-empty parent from `empty_parent()`
/// (so `is_empty()` returns `false` when the baseline contract
/// requires `true`) MUST fail-loudly at the caller's site through
/// the primitive's baseline arm — a regression that dropped the
/// empty-parent baseline assertion surfaces here.
#[test]
#[should_panic(expected = "on empty_parent() must equal true")]
fn assert_is_empty_matches_populated_kind_count_rejects_non_empty_baseline() {
fn make_local(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(11),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(22),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(33),
..Default::default()
},
}
}
fn non_empty_baseline() -> LocalParent {
LocalParent {
alpha: Some(999),
..Default::default()
}
}
assert_is_empty_matches_populated_kind_count::<LocalParent, _, _>(
make_local,
non_empty_baseline,
);
}
/// The `assert_is_saturated_matches_missing_kind_count` primitive
/// accepts the [`LocalParent`] scaffold coherently.
#[test]
fn assert_is_saturated_matches_missing_kind_count_accepts_coherent_local_impl() {
fn make_local(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(11),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(22),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(33),
..Default::default()
},
}
}
assert_is_saturated_matches_missing_kind_count::<LocalParent, _, _>(
make_local,
LocalParent::default,
);
}
/// A factory that yields a saturated parent on the single-slot
/// diagonal (so `is_saturated()` returns `true` when the diagonal
/// contract requires `false`) MUST fail-loudly at the caller's
/// site through the primitive's single-slot-diagonal arm.
#[test]
#[should_panic(expected = "must equal false")]
fn assert_is_saturated_matches_missing_kind_count_rejects_saturated_factory() {
fn saturated_factory(_: LocalKind) -> LocalParent {
LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: Some(3),
}
}
assert_is_saturated_matches_missing_kind_count::<LocalParent, _, _>(
saturated_factory,
LocalParent::default,
);
}
/// A factory that yields a saturated parent from `empty_parent()`
/// (so `is_saturated()` returns `true` when the baseline contract
/// requires `false`) MUST fail-loudly at the caller's site through
/// the primitive's baseline arm.
#[test]
#[should_panic(expected = "on empty_parent() must equal false")]
fn assert_is_saturated_matches_missing_kind_count_rejects_saturated_baseline() {
fn make_local(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(11),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(22),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(33),
..Default::default()
},
}
}
fn saturated_baseline() -> LocalParent {
LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: Some(3),
}
}
assert_is_saturated_matches_missing_kind_count::<LocalParent, _, _>(
make_local,
saturated_baseline,
);
}
/// Every one of the four production `.variant()` sites on
/// `ProcessSpec` binds through the zero-populated-cardinality
/// Boolean primitive coherently — every per-site `single_slot_X(k)`
/// factory produces a `!is_empty()` parent, and
/// `X::default().is_empty() == true` on the empty-parent baseline.
#[test]
fn every_production_tagged_union_binds_through_the_is_empty_testkit_primitive() {
assert_is_empty_matches_populated_kind_count::<crate::intent::Intent, _, _>(
single_slot_intent_probe,
crate::intent::Intent::default,
);
assert_is_empty_matches_populated_kind_count::<crate::encapsulates::EncapsulationKind, _, _>(
single_slot_encapsulation_kind_probe,
crate::encapsulates::EncapsulationKind::default,
);
assert_is_empty_matches_populated_kind_count::<crate::export::ArtifactSource, _, _>(
single_slot_artifact_source_probe,
crate::export::ArtifactSource::default,
);
assert_is_empty_matches_populated_kind_count::<crate::export::VectorChannel, _, _>(
single_slot_vector_channel_probe,
crate::export::VectorChannel::default,
);
}
/// Every one of the four production `.variant()` sites on
/// `ProcessSpec` binds through the zero-missing-cardinality
/// Boolean primitive coherently — every per-site `single_slot_X(k)`
/// factory produces a `!is_saturated()` parent (there are ≥ 2
/// missing slots on every real-world tagged union in the
/// workspace), and `X::default().is_saturated() == false` on the
/// empty-parent baseline.
#[test]
fn every_production_tagged_union_binds_through_the_is_saturated_testkit_primitive() {
assert_is_saturated_matches_missing_kind_count::<crate::intent::Intent, _, _>(
single_slot_intent_probe,
crate::intent::Intent::default,
);
assert_is_saturated_matches_missing_kind_count::<
crate::encapsulates::EncapsulationKind,
_,
_,
>(
single_slot_encapsulation_kind_probe,
crate::encapsulates::EncapsulationKind::default,
);
assert_is_saturated_matches_missing_kind_count::<crate::export::ArtifactSource, _, _>(
single_slot_artifact_source_probe,
crate::export::ArtifactSource::default,
);
assert_is_saturated_matches_missing_kind_count::<crate::export::VectorChannel, _, _>(
single_slot_vector_channel_probe,
crate::export::VectorChannel::default,
);
}
/// The `assert_has_any_populated_kind_matches_populated_kind_count`
/// primitive accepts the [`LocalParent`] scaffold coherently.
#[test]
fn assert_has_any_populated_kind_matches_populated_kind_count_accepts_coherent_local_impl() {
fn make_local(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(11),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(22),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(33),
..Default::default()
},
}
}
assert_has_any_populated_kind_matches_populated_kind_count::<LocalParent, _, _>(
make_local,
LocalParent::default,
);
}
/// A factory that yields an all-empty parent on the single-slot
/// diagonal (so `has_any_populated_kind()` returns `false` when the
/// diagonal contract requires `true`) MUST fail-loudly at the
/// caller's site through the primitive's single-slot-diagonal arm.
#[test]
#[should_panic(expected = "must equal true")]
fn assert_has_any_populated_kind_matches_populated_kind_count_rejects_empty_factory() {
fn empty_factory(_: LocalKind) -> LocalParent {
LocalParent::default()
}
assert_has_any_populated_kind_matches_populated_kind_count::<LocalParent, _, _>(
empty_factory,
LocalParent::default,
);
}
/// A factory that yields a NON-empty parent from `empty_parent()`
/// (so `has_any_populated_kind()` returns `true` when the baseline
/// contract requires `false`) MUST fail-loudly at the caller's site
/// through the primitive's baseline arm.
#[test]
#[should_panic(expected = "on empty_parent() must equal false")]
fn assert_has_any_populated_kind_matches_populated_kind_count_rejects_non_empty_baseline() {
fn make_local(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(11),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(22),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(33),
..Default::default()
},
}
}
fn non_empty_baseline() -> LocalParent {
LocalParent {
alpha: Some(999),
..Default::default()
}
}
assert_has_any_populated_kind_matches_populated_kind_count::<LocalParent, _, _>(
make_local,
non_empty_baseline,
);
}
/// The `assert_has_any_missing_kind_matches_missing_kind_count`
/// primitive accepts the [`LocalParent`] scaffold coherently.
/// `LocalKind::ALL.len() == 3` so a well-formed single-slot parent
/// has `3 - 1 == 2` missing slots, meaning `has_any_missing_kind()
/// == true` on the diagonal.
#[test]
fn assert_has_any_missing_kind_matches_missing_kind_count_accepts_coherent_local_impl() {
fn make_local(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(11),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(22),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(33),
..Default::default()
},
}
}
assert_has_any_missing_kind_matches_missing_kind_count::<LocalParent, _, _>(
make_local,
LocalParent::default,
);
}
/// A factory that yields a saturated parent on the single-slot
/// diagonal (so `has_any_missing_kind()` returns `false` when the
/// diagonal contract requires `true`) MUST fail-loudly at the
/// caller's site through the primitive's single-slot-diagonal arm.
#[test]
#[should_panic(expected = "must equal true")]
fn assert_has_any_missing_kind_matches_missing_kind_count_rejects_saturated_factory() {
fn saturated_factory(_: LocalKind) -> LocalParent {
LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: Some(3),
}
}
assert_has_any_missing_kind_matches_missing_kind_count::<LocalParent, _, _>(
saturated_factory,
LocalParent::default,
);
}
/// A factory that yields a saturated parent from `empty_parent()`
/// (so `has_any_missing_kind()` returns `false` when the baseline
/// contract requires `true`) MUST fail-loudly at the caller's site
/// through the primitive's baseline arm.
#[test]
#[should_panic(expected = "on empty_parent() must equal true")]
fn assert_has_any_missing_kind_matches_missing_kind_count_rejects_saturated_baseline() {
fn make_local(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(11),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(22),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(33),
..Default::default()
},
}
}
fn saturated_baseline() -> LocalParent {
LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: Some(3),
}
}
assert_has_any_missing_kind_matches_missing_kind_count::<LocalParent, _, _>(
make_local,
saturated_baseline,
);
}
/// Every one of the four production `.variant()` sites on
/// `ProcessSpec` binds through the at-least-one-populated-
/// cardinality Boolean primitive coherently — every per-site
/// `single_slot_X(k)` factory produces a `has_any_populated_kind()
/// == true` parent, and `X::default().has_any_populated_kind() ==
/// false` on the empty-parent baseline.
#[test]
fn every_production_tagged_union_binds_through_the_has_any_populated_kind_testkit_primitive() {
assert_has_any_populated_kind_matches_populated_kind_count::<crate::intent::Intent, _, _>(
single_slot_intent_probe,
crate::intent::Intent::default,
);
assert_has_any_populated_kind_matches_populated_kind_count::<
crate::encapsulates::EncapsulationKind,
_,
_,
>(
single_slot_encapsulation_kind_probe,
crate::encapsulates::EncapsulationKind::default,
);
assert_has_any_populated_kind_matches_populated_kind_count::<
crate::export::ArtifactSource,
_,
_,
>(
single_slot_artifact_source_probe,
crate::export::ArtifactSource::default,
);
assert_has_any_populated_kind_matches_populated_kind_count::<
crate::export::VectorChannel,
_,
_,
>(
single_slot_vector_channel_probe,
crate::export::VectorChannel::default,
);
}
/// Every one of the four production `.variant()` sites on
/// `ProcessSpec` binds through the at-least-one-missing-
/// cardinality Boolean primitive coherently — every per-site
/// `single_slot_X(k)` factory produces a `has_any_missing_kind() ==
/// true` parent (there are ≥ 2 missing slots on every real-world
/// tagged union in the workspace, since `ALL.len() ≥ 2`), and
/// `X::default().has_any_missing_kind() == true` on the empty-
/// parent baseline (every slot is missing).
#[test]
fn every_production_tagged_union_binds_through_the_has_any_missing_kind_testkit_primitive() {
assert_has_any_missing_kind_matches_missing_kind_count::<crate::intent::Intent, _, _>(
single_slot_intent_probe,
crate::intent::Intent::default,
);
assert_has_any_missing_kind_matches_missing_kind_count::<
crate::encapsulates::EncapsulationKind,
_,
_,
>(
single_slot_encapsulation_kind_probe,
crate::encapsulates::EncapsulationKind::default,
);
assert_has_any_missing_kind_matches_missing_kind_count::<crate::export::ArtifactSource, _, _>(
single_slot_artifact_source_probe,
crate::export::ArtifactSource::default,
);
assert_has_any_missing_kind_matches_missing_kind_count::<crate::export::VectorChannel, _, _>(
single_slot_vector_channel_probe,
crate::export::VectorChannel::default,
);
}
/// The `assert_has_unique_populated_kind_matches_populated_kind_count`
/// primitive accepts the [`LocalParent`] scaffold coherently.
#[test]
fn assert_has_unique_populated_kind_matches_populated_kind_count_accepts_coherent_local_impl() {
fn make_local(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(11),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(22),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(33),
..Default::default()
},
}
}
assert_has_unique_populated_kind_matches_populated_kind_count::<LocalParent, _, _>(
make_local,
LocalParent::default,
);
}
/// A factory that yields an all-empty parent on the single-slot
/// diagonal (so `has_unique_populated_kind()` returns `false` when
/// the diagonal contract requires `true`) MUST fail-loudly at the
/// caller's site through the primitive's single-slot-diagonal arm.
#[test]
#[should_panic(expected = "must equal true")]
fn assert_has_unique_populated_kind_matches_populated_kind_count_rejects_empty_factory() {
fn empty_factory(_: LocalKind) -> LocalParent {
LocalParent::default()
}
assert_has_unique_populated_kind_matches_populated_kind_count::<LocalParent, _, _>(
empty_factory,
LocalParent::default,
);
}
/// A factory that yields a WELL-FORMED parent from `empty_parent()`
/// (so `has_unique_populated_kind()` returns `true` when the
/// baseline contract requires `false`) MUST fail-loudly at the
/// caller's site through the primitive's baseline arm.
#[test]
#[should_panic(expected = "on empty_parent() must equal false")]
fn assert_has_unique_populated_kind_matches_populated_kind_count_rejects_wellformed_baseline() {
fn make_local(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(11),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(22),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(33),
..Default::default()
},
}
}
fn wellformed_baseline() -> LocalParent {
LocalParent {
alpha: Some(999),
..Default::default()
}
}
assert_has_unique_populated_kind_matches_populated_kind_count::<LocalParent, _, _>(
make_local,
wellformed_baseline,
);
}
/// The `assert_has_unique_missing_kind_matches_missing_kind_count`
/// primitive accepts the [`LocalParent`] scaffold coherently.
/// `LocalKind::ALL.len() == 3` so a well-formed single-slot parent
/// has `3 - 1 == 2` missing slots, meaning
/// `has_unique_missing_kind() == false` on the diagonal.
#[test]
fn assert_has_unique_missing_kind_matches_missing_kind_count_accepts_coherent_local_impl() {
fn make_local(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(11),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(22),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(33),
..Default::default()
},
}
}
assert_has_unique_missing_kind_matches_missing_kind_count::<LocalParent, _, _>(
make_local,
LocalParent::default,
);
}
/// A factory that yields a NEAR-SATURATED (two-slot) parent on the
/// single-slot diagonal — so `has_unique_missing_kind()` returns
/// `true` (exactly one missing on an `ALL.len() == 3` closed set)
/// when the diagonal contract on this scaffold requires `false`
/// (a well-formed one-slot parent has two missing, not one) — MUST
/// fail-loudly at the caller's site through the primitive's
/// single-slot-diagonal arm.
#[test]
#[should_panic(expected = "must equal false")]
fn assert_has_unique_missing_kind_matches_missing_kind_count_rejects_near_saturated_factory() {
fn near_saturated(k: LocalKind) -> LocalParent {
// Populate two slots regardless of `k`, leaving exactly one
// missing — mimics a factory that "helpfully" pre-populates
// extras and drifts off the well-formed diagonal.
let mut p = LocalParent {
alpha: Some(1),
beta: Some(2),
..Default::default()
};
if let LocalKind::Gamma = k {
p.gamma = Some(3);
// Now saturated — drop back to two-slot by clearing
// alpha, so exactly one missing again.
p.alpha = None;
}
p
}
assert_has_unique_missing_kind_matches_missing_kind_count::<LocalParent, _, _>(
near_saturated,
LocalParent::default,
);
}
/// A factory that yields a NEAR-SATURATED parent from
/// `empty_parent()` (so `has_unique_missing_kind()` returns `true`
/// when the baseline contract requires `false`) MUST fail-loudly
/// at the caller's site through the primitive's baseline arm.
#[test]
#[should_panic(expected = "on empty_parent() must equal false")]
fn assert_has_unique_missing_kind_matches_missing_kind_count_rejects_near_saturated_baseline() {
fn make_local(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(11),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(22),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(33),
..Default::default()
},
}
}
fn near_saturated_baseline() -> LocalParent {
LocalParent {
alpha: Some(1),
beta: Some(2),
..Default::default()
}
}
assert_has_unique_missing_kind_matches_missing_kind_count::<LocalParent, _, _>(
make_local,
near_saturated_baseline,
);
}
/// Every one of the four production `.variant()` sites on
/// `ProcessSpec` binds through the one-populated-cardinality
/// Boolean primitive coherently — every per-site `single_slot_X(k)`
/// factory produces a `has_unique_populated_kind() == true` parent,
/// and `X::default().has_unique_populated_kind() == false` on the
/// empty-parent baseline.
#[test]
fn every_production_tagged_union_binds_through_the_has_unique_populated_kind_testkit_primitive()
{
assert_has_unique_populated_kind_matches_populated_kind_count::<crate::intent::Intent, _, _>(
single_slot_intent_probe,
crate::intent::Intent::default,
);
assert_has_unique_populated_kind_matches_populated_kind_count::<
crate::encapsulates::EncapsulationKind,
_,
_,
>(
single_slot_encapsulation_kind_probe,
crate::encapsulates::EncapsulationKind::default,
);
assert_has_unique_populated_kind_matches_populated_kind_count::<
crate::export::ArtifactSource,
_,
_,
>(
single_slot_artifact_source_probe,
crate::export::ArtifactSource::default,
);
assert_has_unique_populated_kind_matches_populated_kind_count::<
crate::export::VectorChannel,
_,
_,
>(
single_slot_vector_channel_probe,
crate::export::VectorChannel::default,
);
}
/// Every one of the four production `.variant()` sites on
/// `ProcessSpec` binds through the one-missing-cardinality Boolean
/// primitive coherently — every per-site `single_slot_X(k)` factory
/// produces a `has_unique_missing_kind() == false` parent (there
/// are ≥ 2 missing slots on every real-world tagged union in the
/// workspace: `Intent` `ALL.len() == 6`, `EncapsulationKind` `>= 3`,
/// `ArtifactSource` `>= 3`, `VectorChannel` `>= 3`), and
/// `X::default().has_unique_missing_kind() == false` on the empty-
/// parent baseline (every slot missing, not exactly one).
#[test]
fn every_production_tagged_union_binds_through_the_has_unique_missing_kind_testkit_primitive() {
assert_has_unique_missing_kind_matches_missing_kind_count::<crate::intent::Intent, _, _>(
single_slot_intent_probe,
crate::intent::Intent::default,
);
assert_has_unique_missing_kind_matches_missing_kind_count::<
crate::encapsulates::EncapsulationKind,
_,
_,
>(
single_slot_encapsulation_kind_probe,
crate::encapsulates::EncapsulationKind::default,
);
assert_has_unique_missing_kind_matches_missing_kind_count::<
crate::export::ArtifactSource,
_,
_,
>(
single_slot_artifact_source_probe,
crate::export::ArtifactSource::default,
);
assert_has_unique_missing_kind_matches_missing_kind_count::<
crate::export::VectorChannel,
_,
_,
>(
single_slot_vector_channel_probe,
crate::export::VectorChannel::default,
);
}
// -------------------------------------------------------------------
// `assert_has_multiple_(populated|missing)_kinds_matches_(populated|
// missing)_kind_count` — the ≥2-cardinality Boolean testkit
// primitives. Pin acceptance on the coherent LocalParent scaffold +
// rejection on the two obvious factory drifts + a production sweep
// binding all four `.variant()` sites through the trichotomy law
// (is_empty + has_unique_populated_kind + has_multiple_populated_kinds
// == 1 on every arm, and the missing-axis peer).
// -------------------------------------------------------------------
/// The `assert_has_multiple_populated_kinds_matches_populated_kind_count`
/// primitive accepts the [`LocalParent`] scaffold coherently — the
/// coherent-impl side has no false-positive drift on the empty
/// baseline, the single-slot diagonal, or the two-slot sweep.
#[test]
fn assert_has_multiple_populated_kinds_matches_populated_kind_count_accepts_coherent_local_impl(
) {
fn single_slot(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(1),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(2),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(3),
..Default::default()
},
}
}
fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
let mut p = LocalParent::default();
for k in [a, b] {
match k {
LocalKind::Alpha => p.alpha = Some(1),
LocalKind::Beta => p.beta = Some(2),
LocalKind::Gamma => p.gamma = Some(3),
}
}
p
}
assert_has_multiple_populated_kinds_matches_populated_kind_count::<LocalParent, _, _, _>(
single_slot,
two_slot,
LocalParent::default,
);
}
/// The primitive rejects an `empty_parent` factory that yields a
/// two-slot parent (baseline expects zero-populated on empty).
#[test]
#[should_panic(
expected = "TaggedUnion::has_multiple_populated_kinds() on empty_parent() must equal false"
)]
fn assert_has_multiple_populated_kinds_matches_populated_kind_count_rejects_two_slot_baseline()
{
fn single_slot(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(1),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(2),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(3),
..Default::default()
},
}
}
fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
let mut p = LocalParent::default();
for k in [a, b] {
match k {
LocalKind::Alpha => p.alpha = Some(1),
LocalKind::Beta => p.beta = Some(2),
LocalKind::Gamma => p.gamma = Some(3),
}
}
p
}
fn two_slot_baseline() -> LocalParent {
LocalParent {
alpha: Some(1),
beta: Some(2),
..Default::default()
}
}
assert_has_multiple_populated_kinds_matches_populated_kind_count::<LocalParent, _, _, _>(
single_slot,
two_slot,
two_slot_baseline,
);
}
/// The primitive rejects a `two_slot` factory that yields a
/// single-slot parent (two-slot sweep expects has_multiple ==
/// true).
#[test]
#[should_panic(expected = "TaggedUnion::has_multiple_populated_kinds() on two_slot(")]
fn assert_has_multiple_populated_kinds_matches_populated_kind_count_rejects_single_slot_two_slot_factory(
) {
fn single_slot(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(1),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(2),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(3),
..Default::default()
},
}
}
fn drifted_two_slot(a: LocalKind, _: LocalKind) -> LocalParent {
// Only populates the first slot — the two-slot invariant
// is violated.
single_slot(a)
}
assert_has_multiple_populated_kinds_matches_populated_kind_count::<LocalParent, _, _, _>(
single_slot,
drifted_two_slot,
LocalParent::default,
);
}
/// The `assert_has_multiple_missing_kinds_matches_missing_kind_count`
/// primitive accepts the [`LocalParent`] scaffold coherently.
#[test]
fn assert_has_multiple_missing_kinds_matches_missing_kind_count_accepts_coherent_local_impl() {
fn single_slot(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(1),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(2),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(3),
..Default::default()
},
}
}
fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
let mut p = LocalParent::default();
for k in [a, b] {
match k {
LocalKind::Alpha => p.alpha = Some(1),
LocalKind::Beta => p.beta = Some(2),
LocalKind::Gamma => p.gamma = Some(3),
}
}
p
}
assert_has_multiple_missing_kinds_matches_missing_kind_count::<LocalParent, _, _, _>(
single_slot,
two_slot,
LocalParent::default,
);
}
/// The primitive rejects a `two_slot` factory that yields an
/// empty parent (two-slot expects `ALL.len() - 2 == 1` missing
/// on `LocalParent`, whose composition law asserts
/// `has_multiple_missing_kinds() == false`; an empty factory
/// yields `ALL.len() == 3` missing where the primitive returns
/// `true` — the composition law and the trichotomy both drift).
#[test]
#[should_panic]
fn assert_has_multiple_missing_kinds_matches_missing_kind_count_rejects_empty_two_slot_factory()
{
fn single_slot(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(1),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(2),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(3),
..Default::default()
},
}
}
fn empty_two_slot(_: LocalKind, _: LocalKind) -> LocalParent {
// Always yields an empty parent — zero populated, three
// missing. The two-slot invariant is violated.
LocalParent::default()
}
assert_has_multiple_missing_kinds_matches_missing_kind_count::<LocalParent, _, _, _>(
single_slot,
empty_two_slot,
LocalParent::default,
);
}
/// The primitive rejects a `empty_parent` factory that yields a
/// saturated parent (empty baseline expects has_multiple_missing
/// == true on ALL.len() == 3 since 3 missing >= 2).
#[test]
#[should_panic]
fn assert_has_multiple_missing_kinds_matches_missing_kind_count_rejects_saturated_empty_baseline(
) {
fn single_slot(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(1),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(2),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(3),
..Default::default()
},
}
}
fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
let mut p = LocalParent::default();
for k in [a, b] {
match k {
LocalKind::Alpha => p.alpha = Some(1),
LocalKind::Beta => p.beta = Some(2),
LocalKind::Gamma => p.gamma = Some(3),
}
}
p
}
fn saturated_baseline() -> LocalParent {
LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: Some(3),
}
}
assert_has_multiple_missing_kinds_matches_missing_kind_count::<LocalParent, _, _, _>(
single_slot,
two_slot,
saturated_baseline,
);
}
/// Every one of the four production `.variant()` sites on
/// `ProcessSpec` binds through the many-cardinality Boolean
/// primitive on the populated axis coherently — every per-site
/// `single_slot_X(k)` factory produces `has_multiple_populated_kinds()
/// == false`, every `two_slot_X(a, b)` produces `== true`, and
/// `X::default().has_multiple_populated_kinds() == false`. The
/// trichotomy partition law (`is_empty` plus `has_unique_populated_kind`
/// plus `has_multiple_populated_kinds` sums to `1`) is pinned inside
/// the testkit on every arm.
#[test]
fn every_production_tagged_union_binds_through_the_has_multiple_populated_kinds_testkit_primitive(
) {
assert_has_multiple_populated_kinds_matches_populated_kind_count::<
crate::intent::Intent,
_,
_,
_,
>(
single_slot_intent_probe,
two_slot_intent_probe,
crate::intent::Intent::default,
);
assert_has_multiple_populated_kinds_matches_populated_kind_count::<
crate::encapsulates::EncapsulationKind,
_,
_,
_,
>(
single_slot_encapsulation_kind_probe,
two_slot_encapsulation_kind_probe,
crate::encapsulates::EncapsulationKind::default,
);
assert_has_multiple_populated_kinds_matches_populated_kind_count::<
crate::export::ArtifactSource,
_,
_,
_,
>(
single_slot_artifact_source_probe,
two_slot_artifact_source_probe,
crate::export::ArtifactSource::default,
);
assert_has_multiple_populated_kinds_matches_populated_kind_count::<
crate::export::VectorChannel,
_,
_,
_,
>(
single_slot_vector_channel_probe,
two_slot_vector_channel_probe,
crate::export::VectorChannel::default,
);
}
/// Every one of the four production `.variant()` sites on
/// `ProcessSpec` binds through the many-cardinality Boolean
/// primitive on the missing axis coherently. On `Intent`
/// (`ALL.len() == 6`), `EncapsulationKind` (`>= 3`),
/// `ArtifactSource` (`>= 3`), `VectorChannel` (`>= 3`), the
/// single-slot diagonal returns `true` (`ALL.len() - 1 >= 2`);
/// on `Intent` (`ALL.len() == 6 >= 4`) the two-slot sweep also
/// returns `true`. The trichotomy partition law on the missing
/// axis (`is_saturated + has_unique_missing_kind +
/// has_multiple_missing_kinds == 1`) is pinned inside the testkit
/// on every arm.
#[test]
fn every_production_tagged_union_binds_through_the_has_multiple_missing_kinds_testkit_primitive(
) {
assert_has_multiple_missing_kinds_matches_missing_kind_count::<
crate::intent::Intent,
_,
_,
_,
>(
single_slot_intent_probe,
two_slot_intent_probe,
crate::intent::Intent::default,
);
assert_has_multiple_missing_kinds_matches_missing_kind_count::<
crate::encapsulates::EncapsulationKind,
_,
_,
_,
>(
single_slot_encapsulation_kind_probe,
two_slot_encapsulation_kind_probe,
crate::encapsulates::EncapsulationKind::default,
);
assert_has_multiple_missing_kinds_matches_missing_kind_count::<
crate::export::ArtifactSource,
_,
_,
_,
>(
single_slot_artifact_source_probe,
two_slot_artifact_source_probe,
crate::export::ArtifactSource::default,
);
assert_has_multiple_missing_kinds_matches_missing_kind_count::<
crate::export::VectorChannel,
_,
_,
_,
>(
single_slot_vector_channel_probe,
two_slot_vector_channel_probe,
crate::export::VectorChannel::default,
);
}
// -------------------------------------------------------------------
// `assert_has_at_most_one_(populated|missing)_kind_matches_(populated|
// missing)_kind_count` — the ≤1-cardinality Boolean testkit
// primitives. Boolean-negation peer of the ≥2 testkits above;
// pin acceptance on the coherent LocalParent scaffold + a
// production sweep binding all four `.variant()` sites through
// the three composition laws (definitional Boolean-negation,
// scalar cardinality, and trichotomy union).
// -------------------------------------------------------------------
/// The `assert_has_at_most_one_populated_kind_matches_populated_kind_count`
/// primitive accepts the [`LocalParent`] scaffold coherently — the
/// coherent-impl side reads `true` on the empty baseline (0 ≤ 1)
/// and every single-slot arrangement (1 ≤ 1), and `false` on every
/// off-diagonal two-slot arrangement (2 > 1). All three composition
/// laws hold on every arm.
#[test]
fn assert_has_at_most_one_populated_kind_matches_populated_kind_count_accepts_coherent_local_impl(
) {
fn single_slot(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(1),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(2),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(3),
..Default::default()
},
}
}
fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
let mut p = LocalParent::default();
for k in [a, b] {
match k {
LocalKind::Alpha => p.alpha = Some(1),
LocalKind::Beta => p.beta = Some(2),
LocalKind::Gamma => p.gamma = Some(3),
}
}
p
}
assert_has_at_most_one_populated_kind_matches_populated_kind_count::<LocalParent, _, _, _>(
single_slot,
two_slot,
LocalParent::default,
);
}
/// The primitive rejects a `two_slot` factory that yields a
/// well-formed single-populated parent — the two-slot sweep expects
/// `has_at_most_one_populated_kind() == false` (2 > 1), but a
/// single-slot yields `true` (1 ≤ 1).
#[test]
#[should_panic(expected = "TaggedUnion::has_at_most_one_populated_kind() on two_slot(")]
fn assert_has_at_most_one_populated_kind_matches_populated_kind_count_rejects_single_slot_two_slot_factory(
) {
fn single_slot(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(1),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(2),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(3),
..Default::default()
},
}
}
fn single_slot_two_slot(a: LocalKind, _b: LocalKind) -> LocalParent {
match a {
LocalKind::Alpha => LocalParent {
alpha: Some(1),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(2),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(3),
..Default::default()
},
}
}
assert_has_at_most_one_populated_kind_matches_populated_kind_count::<LocalParent, _, _, _>(
single_slot,
single_slot_two_slot,
LocalParent::default,
);
}
/// The `assert_has_at_most_one_missing_kind_matches_missing_kind_count`
/// primitive accepts the [`LocalParent`] scaffold coherently. On
/// `ALL.len() == 3` the missing counts are: empty=3, single_slot=2,
/// two_slot=1, saturated=0. So `has_at_most_one_missing_kind()`
/// reads `false` on empty (3 > 1), `false` on single_slot (2 > 1),
/// `true` on two_slot (1 ≤ 1). All three composition laws hold on
/// every arm.
#[test]
fn assert_has_at_most_one_missing_kind_matches_missing_kind_count_accepts_coherent_local_impl()
{
fn single_slot(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(1),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(2),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(3),
..Default::default()
},
}
}
fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
let mut p = LocalParent::default();
for k in [a, b] {
match k {
LocalKind::Alpha => p.alpha = Some(1),
LocalKind::Beta => p.beta = Some(2),
LocalKind::Gamma => p.gamma = Some(3),
}
}
p
}
assert_has_at_most_one_missing_kind_matches_missing_kind_count::<LocalParent, _, _, _>(
single_slot,
two_slot,
LocalParent::default,
);
}
/// The primitive rejects a saturated `empty_parent` factory — on
/// `ALL.len() == 3` the baseline expects `has_at_most_one_missing_kind()
/// == false` (all 3 missing on the genuine empty arm), but a
/// saturated factory yields 0 missing → `true`.
#[test]
#[should_panic(
expected = "TaggedUnion::has_at_most_one_missing_kind() on empty_parent() must equal false"
)]
fn assert_has_at_most_one_missing_kind_matches_missing_kind_count_rejects_saturated_empty_baseline(
) {
fn single_slot(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(1),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(2),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(3),
..Default::default()
},
}
}
fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
let mut p = LocalParent::default();
for k in [a, b] {
match k {
LocalKind::Alpha => p.alpha = Some(1),
LocalKind::Beta => p.beta = Some(2),
LocalKind::Gamma => p.gamma = Some(3),
}
}
p
}
fn saturated_baseline() -> LocalParent {
LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: Some(3),
}
}
assert_has_at_most_one_missing_kind_matches_missing_kind_count::<LocalParent, _, _, _>(
single_slot,
two_slot,
saturated_baseline,
);
}
/// Every one of the four production `.variant()` sites on
/// `ProcessSpec` binds through the ≤1-populated-cardinality Boolean
/// primitive coherently — every per-site `single_slot_X(k)` factory
/// produces `has_at_most_one_populated_kind() == true` (1 ≤ 1),
/// every `two_slot_X(a, b)` produces `== false` (2 > 1), and
/// `X::default().has_at_most_one_populated_kind() == true` on the
/// empty-parent baseline (0 ≤ 1). All three composition laws
/// (definitional negation, scalar cardinality, trichotomy union)
/// are pinned inside the testkit on every arm.
#[test]
fn every_production_tagged_union_binds_through_the_has_at_most_one_populated_kind_testkit_primitive(
) {
assert_has_at_most_one_populated_kind_matches_populated_kind_count::<
crate::intent::Intent,
_,
_,
_,
>(
single_slot_intent_probe,
two_slot_intent_probe,
crate::intent::Intent::default,
);
assert_has_at_most_one_populated_kind_matches_populated_kind_count::<
crate::encapsulates::EncapsulationKind,
_,
_,
_,
>(
single_slot_encapsulation_kind_probe,
two_slot_encapsulation_kind_probe,
crate::encapsulates::EncapsulationKind::default,
);
assert_has_at_most_one_populated_kind_matches_populated_kind_count::<
crate::export::ArtifactSource,
_,
_,
_,
>(
single_slot_artifact_source_probe,
two_slot_artifact_source_probe,
crate::export::ArtifactSource::default,
);
assert_has_at_most_one_populated_kind_matches_populated_kind_count::<
crate::export::VectorChannel,
_,
_,
_,
>(
single_slot_vector_channel_probe,
two_slot_vector_channel_probe,
crate::export::VectorChannel::default,
);
}
/// Every one of the four production `.variant()` sites on
/// `ProcessSpec` binds through the ≤1-missing-cardinality Boolean
/// primitive coherently. On `Intent` (`ALL.len() == 6`),
/// `EncapsulationKind` (`>= 3`), `ArtifactSource` (`>= 3`),
/// `VectorChannel` (`>= 3`), the single-slot diagonal returns
/// `false` (`ALL.len() - 1 >= 2`), the two-slot sweep returns
/// `false` on any `ALL.len() >= 4` (Intent) and `true` on
/// `ALL.len() == 3` (the smaller unions have `1 <= 1` missing on
/// the two-slot arm), and the empty baseline returns `false`
/// (`ALL.len() >= 2`).
#[test]
fn every_production_tagged_union_binds_through_the_has_at_most_one_missing_kind_testkit_primitive(
) {
assert_has_at_most_one_missing_kind_matches_missing_kind_count::<
crate::intent::Intent,
_,
_,
_,
>(
single_slot_intent_probe,
two_slot_intent_probe,
crate::intent::Intent::default,
);
assert_has_at_most_one_missing_kind_matches_missing_kind_count::<
crate::encapsulates::EncapsulationKind,
_,
_,
_,
>(
single_slot_encapsulation_kind_probe,
two_slot_encapsulation_kind_probe,
crate::encapsulates::EncapsulationKind::default,
);
assert_has_at_most_one_missing_kind_matches_missing_kind_count::<
crate::export::ArtifactSource,
_,
_,
_,
>(
single_slot_artifact_source_probe,
two_slot_artifact_source_probe,
crate::export::ArtifactSource::default,
);
assert_has_at_most_one_missing_kind_matches_missing_kind_count::<
crate::export::VectorChannel,
_,
_,
_,
>(
single_slot_vector_channel_probe,
two_slot_vector_channel_probe,
crate::export::VectorChannel::default,
);
}
/// The `assert_is_partially_populated_matches_cardinality` primitive
/// accepts the [`LocalParent`] scaffold coherently — the middle-arm
/// Boolean projection reads `true` on every single-slot and two-slot
/// arrangement (0 < populated < 3) and `false` on the empty
/// baseline (0 populated), and the parent-state trichotomy partition
/// (`is_empty + is_partially_populated + is_saturated == 1`) holds
/// on every arm.
#[test]
fn assert_is_partially_populated_matches_cardinality_accepts_coherent_local_impl() {
fn single_slot(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(1),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(2),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(3),
..Default::default()
},
}
}
fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
let mut p = LocalParent::default();
for k in [a, b] {
match k {
LocalKind::Alpha => p.alpha = Some(1),
LocalKind::Beta => p.beta = Some(2),
LocalKind::Gamma => p.gamma = Some(3),
}
}
p
}
assert_is_partially_populated_matches_cardinality::<LocalParent, _, _, _>(
single_slot,
two_slot,
LocalParent::default,
);
}
/// The primitive rejects a `single_slot` factory that yields an
/// empty parent (single-slot expects `is_partially_populated() ==
/// true` because on `ALL.len() == 3` a well-formed parent has
/// `1 populated + 2 missing` — but an empty factory yields 0
/// populated, so the middle-arm assertion drifts).
#[test]
#[should_panic(expected = "must equal true")]
fn assert_is_partially_populated_matches_cardinality_rejects_empty_single_slot_factory() {
fn empty_single_slot(_: LocalKind) -> LocalParent {
LocalParent::default()
}
fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
let mut p = LocalParent::default();
for k in [a, b] {
match k {
LocalKind::Alpha => p.alpha = Some(1),
LocalKind::Beta => p.beta = Some(2),
LocalKind::Gamma => p.gamma = Some(3),
}
}
p
}
assert_is_partially_populated_matches_cardinality::<LocalParent, _, _, _>(
empty_single_slot,
two_slot,
LocalParent::default,
);
}
/// The primitive rejects an `empty_parent` factory that yields a
/// saturated parent (empty baseline expects
/// `is_partially_populated() == false` because 0 populated is the
/// empty arm — a saturated factory has `ALL.len()` populated + 0
/// missing, which is ALSO the `false` arm of the middle Boolean
/// but drifts on the trichotomy partition since
/// `is_saturated == true` while the primitive expected
/// `is_empty == true` on the baseline).
#[test]
#[should_panic]
fn assert_is_partially_populated_matches_cardinality_rejects_saturated_empty_baseline() {
fn single_slot(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(1),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(2),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(3),
..Default::default()
},
}
}
fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
let mut p = LocalParent::default();
for k in [a, b] {
match k {
LocalKind::Alpha => p.alpha = Some(1),
LocalKind::Beta => p.beta = Some(2),
LocalKind::Gamma => p.gamma = Some(3),
}
}
p
}
fn saturated_baseline() -> LocalParent {
LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: Some(3),
}
}
assert_is_partially_populated_matches_cardinality::<LocalParent, _, _, _>(
single_slot,
two_slot,
saturated_baseline,
);
}
/// Every one of the four production `.variant()` sites on
/// `ProcessSpec` binds through the parent-state-middle-arm Boolean
/// primitive coherently — every per-site `single_slot_X(k)` factory
/// produces `is_partially_populated() == true` (well-formed has
/// `1 populated + ALL.len() - 1 ≥ 1 missing`), every
/// `two_slot_X(a, b)` produces `== true` (`ALL.len() ≥ 3` on every
/// production union so two_slot has `2 populated + ALL.len() - 2
/// ≥ 1 missing`), and `X::default().is_partially_populated() ==
/// false` on the empty-parent baseline. The parent-state
/// trichotomy partition law (`is_empty + is_partially_populated
/// + is_saturated == 1`) is pinned inside the testkit on every arm.
#[test]
fn every_production_tagged_union_binds_through_the_is_partially_populated_testkit_primitive() {
assert_is_partially_populated_matches_cardinality::<crate::intent::Intent, _, _, _>(
single_slot_intent_probe,
two_slot_intent_probe,
crate::intent::Intent::default,
);
assert_is_partially_populated_matches_cardinality::<
crate::encapsulates::EncapsulationKind,
_,
_,
_,
>(
single_slot_encapsulation_kind_probe,
two_slot_encapsulation_kind_probe,
crate::encapsulates::EncapsulationKind::default,
);
assert_is_partially_populated_matches_cardinality::<crate::export::ArtifactSource, _, _, _>(
single_slot_artifact_source_probe,
two_slot_artifact_source_probe,
crate::export::ArtifactSource::default,
);
assert_is_partially_populated_matches_cardinality::<crate::export::VectorChannel, _, _, _>(
single_slot_vector_channel_probe,
two_slot_vector_channel_probe,
crate::export::VectorChannel::default,
);
}
/// The `assert_has_only_matches_unique_populated_kind` primitive
/// accepts the [`LocalParent`] scaffold coherently — the kind-scoped
/// strict-refinement predicate reads `true` iff the probed kind
/// equals the populated kind on every single-slot arrangement (the
/// diagonal), `false` on every off-diagonal pair regardless of
/// probed kind, and `false` on the empty baseline for every kind.
/// The five composition laws (widened uniqueness, cardinality-
/// refinement, kind-scoped implication, kind-domain exhaustivity,
/// well-formed diagonal) hold on every arm.
#[test]
fn assert_has_only_matches_unique_populated_kind_accepts_coherent_local_impl() {
fn single_slot(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(1),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(2),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(3),
..Default::default()
},
}
}
fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
let mut p = LocalParent::default();
for k in [a, b] {
match k {
LocalKind::Alpha => p.alpha = Some(1),
LocalKind::Beta => p.beta = Some(2),
LocalKind::Gamma => p.gamma = Some(3),
}
}
p
}
assert_has_only_matches_unique_populated_kind::<LocalParent, _, _, _>(
single_slot,
two_slot,
LocalParent::default,
);
}
/// The primitive rejects a `single_slot` factory that populates
/// the WRONG kind (always `Beta` regardless of what kind is asked
/// for) — the well-formed diagonal law
/// `single_slot(k).has_only(k) == true` fails on
/// `k ∈ {Alpha, Gamma}` where the factory populated `Beta` instead.
#[test]
#[should_panic(expected = "must equal true")]
fn assert_has_only_matches_unique_populated_kind_rejects_wrong_slot_factory() {
fn always_beta(_: LocalKind) -> LocalParent {
LocalParent {
beta: Some(2),
..Default::default()
}
}
fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
let mut p = LocalParent::default();
for k in [a, b] {
match k {
LocalKind::Alpha => p.alpha = Some(1),
LocalKind::Beta => p.beta = Some(2),
LocalKind::Gamma => p.gamma = Some(3),
}
}
p
}
assert_has_only_matches_unique_populated_kind::<LocalParent, _, _, _>(
always_beta,
two_slot,
LocalParent::default,
);
}
/// The primitive rejects an `empty_parent` factory that yields a
/// saturated parent — the empty-baseline exhaustivity assertion
/// `empty_parent().is_empty() == true` fails on the saturated
/// baseline, catching a factory that mis-represents the empty arm.
#[test]
#[should_panic(expected = "must satisfy is_empty() == true")]
fn assert_has_only_matches_unique_populated_kind_rejects_saturated_empty_baseline() {
fn single_slot(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(1),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(2),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(3),
..Default::default()
},
}
}
fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
let mut p = LocalParent::default();
for k in [a, b] {
match k {
LocalKind::Alpha => p.alpha = Some(1),
LocalKind::Beta => p.beta = Some(2),
LocalKind::Gamma => p.gamma = Some(3),
}
}
p
}
fn saturated_baseline() -> LocalParent {
LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: Some(3),
}
}
assert_has_only_matches_unique_populated_kind::<LocalParent, _, _, _>(
single_slot,
two_slot,
saturated_baseline,
);
}
/// Every one of the four production `.variant()` sites on
/// `ProcessSpec` binds through the kind-scoped strict-refinement
/// Boolean primitive coherently — every per-site `single_slot_X(k)`
/// factory produces `has_only(k) == true` (well-formed truth table
/// on the diagonal), every off-diagonal probe returns `false`
/// (well-formed truth table off the diagonal), every
/// `two_slot_X(a, b)` produces `has_only(k) == false` for every
/// `k` (multi-populated arm), and `X::default().has_only(k) ==
/// false` on the empty baseline for every `k`. The kind-domain
/// exhaustivity law (`count k where has_only(k) ≤ 1` per parent,
/// with equality iff well-formed) is pinned inside the testkit on
/// every arm.
#[test]
fn every_production_tagged_union_binds_through_the_has_only_testkit_primitive() {
assert_has_only_matches_unique_populated_kind::<crate::intent::Intent, _, _, _>(
single_slot_intent_probe,
two_slot_intent_probe,
crate::intent::Intent::default,
);
assert_has_only_matches_unique_populated_kind::<
crate::encapsulates::EncapsulationKind,
_,
_,
_,
>(
single_slot_encapsulation_kind_probe,
two_slot_encapsulation_kind_probe,
crate::encapsulates::EncapsulationKind::default,
);
assert_has_only_matches_unique_populated_kind::<crate::export::ArtifactSource, _, _, _>(
single_slot_artifact_source_probe,
two_slot_artifact_source_probe,
crate::export::ArtifactSource::default,
);
assert_has_only_matches_unique_populated_kind::<crate::export::VectorChannel, _, _, _>(
single_slot_vector_channel_probe,
two_slot_vector_channel_probe,
crate::export::VectorChannel::default,
);
}
// -------------------------------------------------------------------
// `assert_lacks_only_matches_unique_missing_kind` — the closed-set-
// complement mirror of `assert_has_only_matches_unique_populated_kind`
// on the MISSING axis. Pin the composition-law truth table
// (`lacks_only(kind) == (unique_missing_kind() == Some(kind))`,
// cardinality-refinement under complement, kind-scoped implication
// under complement, kind-domain exhaustivity ≤ 1) directly on the
// sibling-shaped `LocalParent` scaffold + on every one of the four
// production `.variant()` parents — a regression on either the fused
// walk's negated presence probe, the argument-scoped short-circuit,
// or the exhaustivity partition fails here before any per-parent
// consumer surfaces the drift.
// -------------------------------------------------------------------
/// The `assert_lacks_only_matches_unique_missing_kind` primitive
/// accepts the [`LocalParent`] scaffold coherently — the closed-set-
/// complement mirror of the populated-axis kind-scoped strict-
/// refinement predicate reads `true` iff the probed kind names the
/// SOLE missing slot. On `LocalParent`'s `ALL.len() == 3` closed
/// set: the empty baseline has 3 missing (so `lacks_only(k) ==
/// false` for every `k`), every single-slot arm has 2 missing (so
/// `lacks_only(k) == false` for every `k`), and every off-diagonal
/// two-slot arm has 1 missing — the third kind, where `lacks_only`
/// returns `true` for that one probe and `false` for the two
/// populated probes. The four composition laws (widened
/// uniqueness, cardinality-refinement under complement, kind-
/// scoped implication under complement, kind-domain exhaustivity)
/// hold on every arm.
#[test]
fn assert_lacks_only_matches_unique_missing_kind_accepts_coherent_local_impl() {
fn single_slot(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(1),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(2),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(3),
..Default::default()
},
}
}
fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
let mut p = LocalParent::default();
for k in [a, b] {
match k {
LocalKind::Alpha => p.alpha = Some(1),
LocalKind::Beta => p.beta = Some(2),
LocalKind::Gamma => p.gamma = Some(3),
}
}
p
}
assert_lacks_only_matches_unique_missing_kind::<LocalParent, _, _, _>(
single_slot,
two_slot,
LocalParent::default,
);
}
/// The primitive rejects a `two_slot` factory that yields a
/// saturated parent (all three slots populated, zero missing) —
/// the factory-precondition truth table on the two-slot arm reads
/// `expected == (k != a && k != b)` for the third kind on
/// `ALL.len() == 3`, but the saturated factory has zero missing so
/// `lacks_only(third) == false` where `expected == true`. Caught
/// by the hard-coded arm expectation BEFORE any composition law
/// reconciles two internally-drifted trait bodies.
#[test]
#[should_panic(expected = "must equal true on ALL.len() == 3")]
fn assert_lacks_only_matches_unique_missing_kind_rejects_saturated_two_slot_factory() {
fn single_slot(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(1),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(2),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(3),
..Default::default()
},
}
}
fn saturated_two_slot(_: LocalKind, _: LocalKind) -> LocalParent {
// Always yields a saturated parent — zero missing.
LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: Some(3),
}
}
assert_lacks_only_matches_unique_missing_kind::<LocalParent, _, _, _>(
single_slot,
saturated_two_slot,
LocalParent::default,
);
}
/// The primitive rejects a `empty_parent` factory that yields a
/// saturated parent — the empty-baseline exhaustivity assertion
/// `empty_parent().is_empty() == true` fails on the saturated
/// baseline, catching a factory that mis-represents the empty arm.
#[test]
#[should_panic(expected = "must satisfy is_empty() == true")]
fn assert_lacks_only_matches_unique_missing_kind_rejects_saturated_empty_baseline() {
fn single_slot(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(1),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(2),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(3),
..Default::default()
},
}
}
fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
let mut p = LocalParent::default();
for k in [a, b] {
match k {
LocalKind::Alpha => p.alpha = Some(1),
LocalKind::Beta => p.beta = Some(2),
LocalKind::Gamma => p.gamma = Some(3),
}
}
p
}
fn saturated_baseline() -> LocalParent {
LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: Some(3),
}
}
assert_lacks_only_matches_unique_missing_kind::<LocalParent, _, _, _>(
single_slot,
two_slot,
saturated_baseline,
);
}
/// Every one of the four production `.variant()` sites on
/// `ProcessSpec` binds through the kind-scoped strict-refinement
/// Boolean primitive on the MISSING axis coherently — on the
/// three `ALL.len() == 3` sites (`EncapsulationKind`,
/// `ArtifactSource`, `VectorChannel`) every off-diagonal
/// `two_slot_X(a, b)` produces `lacks_only(third) == true` for
/// exactly the third kind and `lacks_only(k) == false` for the
/// two populated kinds; on the `ALL.len() == 6` site (`Intent`)
/// every off-diagonal two-slot arm has 4 missing so `lacks_only(k)
/// == false` for every `k`. Every single-slot arm on every site
/// has `ALL.len() - 1 >= 2` missing, so `lacks_only(k) == false`
/// for every `k`. The `X::default()` empty baseline on every site
/// has `ALL.len() >= 3` missing, so `lacks_only(k) == false` for
/// every `k`. The composition-law shape binds every regime
/// through the same substrate site. The kind-domain exhaustivity
/// law (`count k where lacks_only(k) ≤ 1` per parent, with
/// equality iff exactly one slot is missing) is pinned inside the
/// testkit on every arm.
#[test]
fn every_production_tagged_union_binds_through_the_lacks_only_testkit_primitive() {
assert_lacks_only_matches_unique_missing_kind::<crate::intent::Intent, _, _, _>(
single_slot_intent_probe,
two_slot_intent_probe,
crate::intent::Intent::default,
);
assert_lacks_only_matches_unique_missing_kind::<
crate::encapsulates::EncapsulationKind,
_,
_,
_,
>(
single_slot_encapsulation_kind_probe,
two_slot_encapsulation_kind_probe,
crate::encapsulates::EncapsulationKind::default,
);
assert_lacks_only_matches_unique_missing_kind::<crate::export::ArtifactSource, _, _, _>(
single_slot_artifact_source_probe,
two_slot_artifact_source_probe,
crate::export::ArtifactSource::default,
);
assert_lacks_only_matches_unique_missing_kind::<crate::export::VectorChannel, _, _, _>(
single_slot_vector_channel_probe,
two_slot_vector_channel_probe,
crate::export::VectorChannel::default,
);
}
// -------------------------------------------------------------------
// `assert_lacks_matches_has_complement` — the missing-axis SUBSET
// primitive testkit. Pin the composition-law truth table
// (definitional complement, missing-set membership, kind-scoped
// implication from lacks_only, cardinality partition against
// missing_kind_count, factory-precondition arm expectation) directly
// on the sibling-shaped `LocalParent` scaffold + on every one of the
// four production `.variant()` parents — a regression on either the
// definitional negation, the missing-set membership projection, or
// the cardinality partition fails here before any per-parent
// consumer surfaces the drift.
// -------------------------------------------------------------------
/// The `assert_lacks_matches_has_complement` primitive accepts the
/// [`LocalParent`] scaffold coherently — the closed-set-complement
/// peer of the kind-scoped SUBSET populated-axis predicate reads
/// `true` iff the probed kind is missing. On `LocalParent`'s
/// `ALL.len() == 3` closed set: the empty baseline has 3 missing
/// (so `lacks(k) == true` for every `k`), every single-slot arm
/// has 2 missing (so `lacks(k) == true` for every `k != populated`
/// and `false` for `k == populated`), and every off-diagonal
/// two-slot arm has 1 missing (so `lacks(k) == true` for the third
/// kind and `false` for the two populated kinds). The five
/// composition laws (definitional complement, missing-set
/// membership, kind-scoped implication from lacks_only,
/// cardinality partition against missing_kind_count, factory-
/// precondition arm expectation) hold on every arm.
#[test]
fn assert_lacks_matches_has_complement_accepts_coherent_local_impl() {
fn single_slot(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(1),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(2),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(3),
..Default::default()
},
}
}
fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
let mut p = LocalParent::default();
for k in [a, b] {
match k {
LocalKind::Alpha => p.alpha = Some(1),
LocalKind::Beta => p.beta = Some(2),
LocalKind::Gamma => p.gamma = Some(3),
}
}
p
}
assert_lacks_matches_has_complement::<LocalParent, _, _, _>(
single_slot,
two_slot,
LocalParent::default,
);
}
/// The primitive rejects a `single_slot` factory that yields a
/// saturated parent (all three slots populated, zero missing) —
/// the factory-precondition truth table on the well-formed
/// single-slot arm reads `expected == (probed != populated)`, but
/// the saturated factory has zero missing so `lacks(probed) ==
/// false` for EVERY probe, mismatching the `true` expectation
/// on every off-diagonal probe. Caught by the hard-coded arm
/// expectation BEFORE the definitional complement law reconciles
/// two internally-drifted trait bodies.
#[test]
#[should_panic(expected = "must equal true")]
fn assert_lacks_matches_has_complement_rejects_saturated_single_slot_factory() {
fn saturated_single_slot(_: LocalKind) -> LocalParent {
LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: Some(3),
}
}
fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
let mut p = LocalParent::default();
for k in [a, b] {
match k {
LocalKind::Alpha => p.alpha = Some(1),
LocalKind::Beta => p.beta = Some(2),
LocalKind::Gamma => p.gamma = Some(3),
}
}
p
}
assert_lacks_matches_has_complement::<LocalParent, _, _, _>(
saturated_single_slot,
two_slot,
LocalParent::default,
);
}
/// The primitive rejects an `empty_parent` factory that yields a
/// saturated parent — the empty-baseline exhaustivity assertion
/// `empty_parent().is_empty() == true` fails on the saturated
/// baseline, catching a factory that mis-represents the empty arm
/// BEFORE any composition law reconciles two internally-drifted
/// trait bodies.
#[test]
#[should_panic(expected = "must satisfy is_empty() == true")]
fn assert_lacks_matches_has_complement_rejects_saturated_empty_baseline() {
fn single_slot(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(1),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(2),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(3),
..Default::default()
},
}
}
fn two_slot(a: LocalKind, b: LocalKind) -> LocalParent {
let mut p = LocalParent::default();
for k in [a, b] {
match k {
LocalKind::Alpha => p.alpha = Some(1),
LocalKind::Beta => p.beta = Some(2),
LocalKind::Gamma => p.gamma = Some(3),
}
}
p
}
fn saturated_baseline() -> LocalParent {
LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: Some(3),
}
}
assert_lacks_matches_has_complement::<LocalParent, _, _, _>(
single_slot,
two_slot,
saturated_baseline,
);
}
/// Every one of the four production `.variant()` sites on
/// `ProcessSpec` binds through the closed-set-complement peer of
/// `has` on the kind-scoped SUBSET axis coherently — every
/// `single_slot_X(k)` factory produces `lacks(k) == false` on the
/// diagonal and `lacks(other) == true` off-diagonal, every
/// `two_slot_X(a, b)` produces `lacks(k) == true` iff `k != a && k
/// != b`, and `X::default().lacks(k) == true` on the empty
/// baseline for every `k`. The cardinality-partition law (`count k
/// where lacks(k) == missing_kind_count()` per parent) is pinned
/// inside the testkit on every arm.
#[test]
fn every_production_tagged_union_binds_through_the_lacks_testkit_primitive() {
assert_lacks_matches_has_complement::<crate::intent::Intent, _, _, _>(
single_slot_intent_probe,
two_slot_intent_probe,
crate::intent::Intent::default,
);
assert_lacks_matches_has_complement::<crate::encapsulates::EncapsulationKind, _, _, _>(
single_slot_encapsulation_kind_probe,
two_slot_encapsulation_kind_probe,
crate::encapsulates::EncapsulationKind::default,
);
assert_lacks_matches_has_complement::<crate::export::ArtifactSource, _, _, _>(
single_slot_artifact_source_probe,
two_slot_artifact_source_probe,
crate::export::ArtifactSource::default,
);
assert_lacks_matches_has_complement::<crate::export::VectorChannel, _, _, _>(
single_slot_vector_channel_probe,
two_slot_vector_channel_probe,
crate::export::VectorChannel::default,
);
}
// -------------------------------------------------------------------
// `assert_two_slots_ambiguous` — the ALL×ALL ambiguity sweep as ONE
// substrate primitive. Pin the truth table (every off-diagonal pair
// resolves to `TaggedUnionError::ambiguous`, diagonal pairs are
// skipped, a factory that yields a non-Ambiguous parent fails-loudly
// at the caller's site) directly on the sibling-shaped `LocalParent`
// scaffold — a regression on either the pair-iteration order or the
// expected-carrier composition fails here before any per-parent test
// surfaces the drift.
// -------------------------------------------------------------------
/// Every off-diagonal pair across [`LocalKind::ALL`] × `ALL`
/// resolves through the substrate primitive to
/// [`LocalParentError::Ambiguous`] on the sibling-shaped local
/// scaffold. Pins the primitive's Ok arm (no false positives on the
/// coherent-impl side) at ONE boundary — a regression that drops
/// the diagonal skip, mis-iterates `ClosedSet::ALL`, or composes a
/// divergent expected carrier fails here before any per-parent
/// inherent test surfaces the drift.
#[test]
fn assert_two_slots_ambiguous_accepts_coherent_local_impl() {
fn two_local(a: LocalKind, b: LocalKind) -> LocalParent {
let mut p = LocalParent::default();
for k in [a, b] {
match k {
LocalKind::Alpha => p.alpha = Some(11),
LocalKind::Beta => p.beta = Some(22),
LocalKind::Gamma => p.gamma = Some(33),
}
}
p
}
assert_two_slots_ambiguous::<LocalParent, _>(two_local);
}
/// A factory that yields a single-slot parent for the FIRST kind
/// (ignoring the second) — every off-diagonal pair resolves to
/// exactly-one Ok(Variant), NOT Ambiguous — MUST fail-loudly at
/// the caller's site through the primitive's "two-slot parent
/// must not resolve to a variant" arm. Pin the Ok-side failure
/// mode so a regression that mis-routes the substrate primitive's
/// resolved-Ok arm past the assertion (silently succeeding on a
/// single-slot factory) is caught here.
#[test]
#[should_panic(expected = "two-slot parent must not resolve to a variant")]
fn assert_two_slots_ambiguous_rejects_factory_that_populates_only_one_slot() {
fn single_only(a: LocalKind, _: LocalKind) -> LocalParent {
let mut p = LocalParent::default();
match a {
LocalKind::Alpha => p.alpha = Some(11),
LocalKind::Beta => p.beta = Some(22),
LocalKind::Gamma => p.gamma = Some(33),
}
p
}
assert_two_slots_ambiguous::<LocalParent, _>(single_only);
}
/// A factory that yields an all-empty parent (so `.variant()`
/// resolves to the `Empty` carrier, NOT `Ambiguous`) MUST
/// fail-loudly at the caller's site through the primitive's
/// `assert_eq!` arm — the composed expected carrier
/// [`TaggedUnionError::ambiguous`] mismatches the resolved
/// [`TaggedUnionError::empty`] carrier. Pin the Empty-arm failure
/// mode so a regression that mis-projects the None arm of
/// [`ResolveError`] onto Ambiguous (silently succeeding on an
/// empty factory) is caught here.
#[test]
#[should_panic(expected = "should resolve Ambiguous")]
fn assert_two_slots_ambiguous_rejects_factory_that_populates_no_slots() {
fn empty_factory(_: LocalKind, _: LocalKind) -> LocalParent {
LocalParent::default()
}
assert_two_slots_ambiguous::<LocalParent, _>(empty_factory);
}
// -------------------------------------------------------------------
// `assert_single_slot_key_matches_label` — the wire-key / kind-label
// alignment sweep as ONE substrate primitive. Pin the truth table
// (every populated slot serializes to exactly one JSON key whose
// name equals the addressing kind's ClosedSet label; a factory that
// populates the wrong slot / no slot / multiple slots fails-loudly
// at the caller's site) directly on the sibling-shaped `LocalParent`
// scaffold — a regression on either the exactly-one arm or the
// name-equality arm fails here before any per-parent inherent test
// surfaces the drift.
// -------------------------------------------------------------------
/// Every kind across [`LocalKind::ALL`] serializes through the
/// substrate primitive to a JSON object with EXACTLY ONE key whose
/// name equals `<LocalKind as ClosedSet>::label` on the addressed
/// kind. Pins the primitive's Ok arm (no false positives on the
/// coherent-impl side) at ONE boundary — a regression that inspects
/// the wrong serde value (e.g. `to_string` instead of `to_value`),
/// counts fields off-by-one, or projects the wrong `ClosedSet`
/// method (`labels_joined` instead of `label`) fails here before any
/// per-parent inherent test surfaces the drift.
#[test]
fn assert_single_slot_key_matches_label_accepts_coherent_local_impl() {
fn make_local(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(11),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(22),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(33),
..Default::default()
},
}
}
assert_single_slot_key_matches_label::<LocalParent, _>(make_local);
}
/// A factory that returns a single-slot parent for the WRONG kind
/// (populates `beta` regardless of what kind is asked for) MUST
/// fail-loudly at the caller's site through the primitive's
/// name-equality arm — the emitted key does not match the addressed
/// kind's label. Pins the drift-detection failure mode so a
/// regression that drops the `assert_eq!(keys[0], label)` arm
/// (silently succeeding on any-key-at-all) is caught here. The
/// caller's site is the `#[should_panic]` boundary through the
/// primitive's `#[track_caller]` compound-lift.
#[test]
#[should_panic(expected = "wire-key drift")]
fn assert_single_slot_key_matches_label_rejects_factory_that_populates_wrong_slot() {
fn always_beta(_: LocalKind) -> LocalParent {
LocalParent {
beta: Some(22),
..Default::default()
}
}
assert_single_slot_key_matches_label::<LocalParent, _>(always_beta);
}
/// A factory that returns an all-empty parent (so serializing
/// yields ZERO keys, not exactly-one) MUST fail-loudly at the
/// caller's site through the primitive's exactly-one arm. Pins the
/// zero-key failure mode so a regression that projects
/// `obj.keys().count() >= 1` (rather than `== 1`) is caught here.
#[test]
#[should_panic(expected = "exactly one populated field")]
fn assert_single_slot_key_matches_label_rejects_factory_that_populates_no_slots() {
fn empty_factory(_: LocalKind) -> LocalParent {
LocalParent::default()
}
assert_single_slot_key_matches_label::<LocalParent, _>(empty_factory);
}
/// A factory that returns a parent with TWO populated slots (so
/// serializing yields two keys, not exactly-one) MUST fail-loudly
/// at the caller's site through the primitive's exactly-one arm.
/// Pins the many-keys failure mode so a regression that projects
/// `obj.keys().count() <= 1` (rather than `== 1`) is caught here.
/// Cross-pins the substrate promise that a single-slot factory
/// truly populates ONE slot — a future factory bug that leaks
/// residual populated slots between calls (e.g. via shared mutable
/// state) is caught HERE at the primitive boundary.
#[test]
#[should_panic(expected = "exactly one populated field")]
fn assert_single_slot_key_matches_label_rejects_factory_that_populates_two_slots() {
fn two_slot_factory(_: LocalKind) -> LocalParent {
LocalParent {
alpha: Some(1),
beta: Some(2),
gamma: None,
}
}
assert_single_slot_key_matches_label::<LocalParent, _>(two_slot_factory);
}
/// The macro-emitted [`MacroLocalParent`] scaffold impls
/// [`TaggedUnion`] through the [`declare_tagged_union_impls!`]
/// three-block macro AND additionally derives `serde::Serialize` +
/// `#[serde(skip_serializing_if = "Option::is_none")]` on every
/// slot — so the wire-key primitive dispatches on the MACRO-emitted
/// impl path byte-identically with the hand-rolled [`LocalParent`]
/// path above. Pins the substrate-wide guarantee that a fifth
/// sibling landing through the macro picks up the wire-alignment
/// check for free, without a hand-rolled `TaggedUnion` block, so
/// long as its serde derives match the substrate-wide
/// `skip_serializing_if = "Option::is_none"` shape every production
/// site already carries. A regression that mis-routes the
/// primitive's serialize call through the WRONG entry point (e.g.
/// calling a bespoke `to_json` that bypasses serde) is caught here.
#[test]
fn assert_single_slot_key_matches_label_accepts_macro_emitted_impl() {
fn make_macro_local(k: MacroLocalKind) -> MacroLocalParent {
match k {
MacroLocalKind::Foo => MacroLocalParent {
foo: Some(7),
bar: None,
},
MacroLocalKind::Bar => MacroLocalParent {
foo: None,
bar: Some(8),
},
}
}
assert_single_slot_key_matches_label::<MacroLocalParent, _>(make_macro_local);
}
// -------------------------------------------------------------------
// `assert_wire_key_matches_label` — bound-relaxed peer of the
// `assert_single_slot_key_matches_label` primitive. Pin the truth
// table (every populated slot serializes to exactly one JSON key
// whose name equals the addressing kind's ClosedSet label; a
// factory that populates the wrong slot / no slot / multiple slots
// fails-loudly at the caller's site) on a NON-TaggedUnion parent
// scaffold — the delegation-only path from the trait-projected
// primitive would silently pass this test if the bound-relaxed
// primitive's body regressed, so the direct-dispatch probes here
// pin the bound-relaxed pathway independently.
// -------------------------------------------------------------------
/// Local parent that carries the wire-format shape (`Option<T>`
/// slots + `#[serde(skip_serializing_if = "Option::is_none")]`
/// annotations) but DELIBERATELY does NOT impl [`TaggedUnion`] —
/// pins the bound-relaxed sweep on the exact shape [`crate::lifetime::Lifetime`]
/// carries in production (empty resolves to a default variant,
/// not to a typed error, so the trait's `T::Error` bound doesn't
/// hold and the trait-projected surface excludes it).
#[derive(Default, serde::Serialize)]
struct BareParent {
#[serde(skip_serializing_if = "Option::is_none")]
alpha: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
beta: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
gamma: Option<u32>,
}
/// The bound-relaxed primitive dispatches Ok on a coherent
/// non-TaggedUnion impl — pin the happy path directly on the
/// [`BareParent`] scaffold so a regression that gates the sweep
/// body on the `T: TaggedUnion` bound (accidentally re-adding it,
/// or projecting through `T::Kind` instead of the caller-supplied
/// `K` generic) fails HERE at the primitive-independent boundary
/// rather than at the [`crate::lifetime::Lifetime`] production
/// site alone. The Ok arm is the "no drift" outcome; a divergence
/// surfaces as a labeled assertion failure at the caller site
/// (this test's own line) via the primitive's `#[track_caller]`.
#[test]
fn assert_wire_key_matches_label_accepts_coherent_bare_parent_impl() {
fn make_bare(k: LocalKind) -> BareParent {
match k {
LocalKind::Alpha => BareParent {
alpha: Some(11),
..Default::default()
},
LocalKind::Beta => BareParent {
beta: Some(22),
..Default::default()
},
LocalKind::Gamma => BareParent {
gamma: Some(33),
..Default::default()
},
}
}
assert_wire_key_matches_label::<BareParent, LocalKind, _>(make_bare);
}
/// A factory that returns a bare-parent for the WRONG kind
/// (populates `beta` regardless of what kind is asked for) MUST
/// fail-loudly at the caller's site through the bound-relaxed
/// primitive's name-equality arm — the emitted key does not match
/// the addressed kind's label. Pins the drift-detection failure
/// mode on the non-TaggedUnion pathway so a regression that drops
/// the `assert_eq!(keys[0], label)` arm (silently succeeding on
/// any-key-at-all) is caught here — mechanical peer of the
/// sibling `assert_single_slot_key_matches_label_rejects_factory_that_populates_wrong_slot`
/// on the TaggedUnion pathway.
#[test]
#[should_panic(expected = "wire-key drift")]
fn assert_wire_key_matches_label_rejects_factory_that_populates_wrong_slot() {
fn always_beta(_: LocalKind) -> BareParent {
BareParent {
beta: Some(22),
..Default::default()
}
}
assert_wire_key_matches_label::<BareParent, LocalKind, _>(always_beta);
}
/// A factory that returns an all-empty bare-parent (so serializing
/// yields ZERO keys, not exactly-one) MUST fail-loudly at the
/// caller's site through the bound-relaxed primitive's
/// exactly-one arm. Pins the zero-key failure mode on the
/// non-TaggedUnion pathway.
#[test]
#[should_panic(expected = "exactly one populated field")]
fn assert_wire_key_matches_label_rejects_factory_that_populates_no_slots() {
fn empty_factory(_: LocalKind) -> BareParent {
BareParent::default()
}
assert_wire_key_matches_label::<BareParent, LocalKind, _>(empty_factory);
}
/// The trait-projected [`assert_single_slot_key_matches_label`]
/// is a one-line delegation to the bound-relaxed
/// [`assert_wire_key_matches_label`] peer — pin the delegation
/// shape at ONE boundary so a regression that inlines a
/// divergent sweep body into the trait-projected surface (rather
/// than the one-line dispatch) is caught here. Ok on a coherent
/// impl means BOTH primitives dispatch through the SAME body on
/// the same fixture — [`LocalParent`] impls [`TaggedUnion`], so
/// both the trait-projected surface and the bound-relaxed peer
/// reach it, and a divergence between the two dispatches would
/// surface here as one succeeding + the other failing.
#[test]
fn assert_single_slot_key_matches_label_delegates_to_wire_key_matches_label() {
fn make_local(k: LocalKind) -> LocalParent {
match k {
LocalKind::Alpha => LocalParent {
alpha: Some(11),
..Default::default()
},
LocalKind::Beta => LocalParent {
beta: Some(22),
..Default::default()
},
LocalKind::Gamma => LocalParent {
gamma: Some(33),
..Default::default()
},
}
}
// Both surfaces reach the same body — dispatched here through
// BOTH entry points so a divergence between them fails one
// arm while the other passes.
assert_single_slot_key_matches_label::<LocalParent, _>(make_local);
assert_wire_key_matches_label::<LocalParent, LocalKind, _>(make_local);
}
/// Every one of the five production borrowed-view enums impls
/// [`VariantKind`] byte-identically with its inherent `.kind()`
/// (or `.target()` on `EncapsulationKindVariant`) — pin the
/// delegation shape at ONE substrate boundary so a regression that
/// inlines a divergent match body into the trait impl (rather than
/// the one-line delegation) is caught here. `Lifetime`'s
/// borrowed-view is included even though `Lifetime` isn't a
/// [`TaggedUnion`] impl — the reverse projection applies uniformly.
#[test]
fn every_production_variant_kind_impl_matches_inherent_projection() {
use crate::encapsulates::{EncapsulationKindVariant, ExistingHelmRelease};
use crate::export::{ArtifactVariant, ChannelVariant, HttpEventChannel, ReceiptsSource};
use crate::intent::{IntentVariant, NixIntent};
use crate::lifetime::{LifetimeVariant, PermanentLifetime};
let nix = NixIntent {
flake_ref: "github:a/b".into(),
attribute: "x".into(),
system: None,
attic_cache: None,
extra_args: vec![],
delegate_to_nix_build: false,
};
let iv = IntentVariant::Nix(&nix);
assert_eq!(iv.kind(), iv.variant_kind());
let perm = PermanentLifetime::default();
let lv = LifetimeVariant::Permanent(&perm);
assert_eq!(lv.kind(), lv.variant_kind());
let hr = ExistingHelmRelease {
namespace: "ns".into(),
name: "n".into(),
release_name: "r".into(),
};
let ev = EncapsulationKindVariant::ExistingHelmRelease(&hr);
assert_eq!(ev.target(), ev.variant_kind());
let rs = ReceiptsSource {};
let av = ArtifactVariant::Receipts(&rs);
assert_eq!(av.kind(), av.variant_kind());
let ch = HttpEventChannel::signal("s");
let cv = ChannelVariant::HttpEvent(&ch);
assert_eq!(cv.kind(), cv.variant_kind());
}
}