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
// @generated by uor-crate from uor-ontology — do not edit manually
//! UOR Foundation SDK — procedural-macro ergonomics for `uor-foundation`.
//!
//! Emitted by `codegen/src/sdk_macros.rs` from the ontology. Consumers of
//! this crate must also depend on `uor-foundation`; the macros emit
//! absolute-path references (`::uor_foundation::…`) that resolve in the
//! *consumer's* dependency graph.
//!
//! # Macros
//!
//! - [`product_shape!`] — emits a `ConstrainedTypeShape` impl and a
//! `mint_product_witness` helper for the UOR product type `A × B`
//! (PT_1 / PT_2a / PT_3 / PT_4).
//! - [`coproduct_shape!`] — emits a `ConstrainedTypeShape` impl and a
//! `mint_coproduct_witness` helper for the UOR sum type `A + B`
//! (ST_1 / ST_2 / ST_6 / ST_7 / ST_8 / ST_9 / ST_10).
//! - [`cartesian_product_shape!`] — emits a `ConstrainedTypeShape` impl,
//! a `CartesianProductShape` marker impl, and a `mint_cartesian_witness`
//! helper for the UOR Cartesian-partition product `A ⊠ B`
//! (CPT_1 / CPT_2a / CPT_3 / CPT_4 / CPT_5).
//! - [`prism_model!`] — emits the seal impls (`__sdk_seal::Sealed` for
//! the model and the route witness), the `FoundationClosed` impl on
//! the route witness, and the `PrismModel<H, B, A>` impl whose
//! `forward` body delegates to `pipeline::run_route` (wiki ADR-020 +
//! ADR-022 D1, D3, D4, D5).
//!
//! # Operand support
//!
//! Operand `CONSTRAINTS` arrays may contain every `ConstraintRef`
//! variant: `Residue`, `Hamming`, `Depth`, `Carry`, `Site`, `Affine`,
//! `SatClauses`, `Bound`, and `Conjunction`. Phase 17 stores
//! `Affine.coefficients` as a fixed-size
//! `[i64; AFFINE_MAX_COEFFS]` array (capacity 8) and limits
//! `Conjunction.conjuncts` to a `[LeafConstraintRef; CONJUNCTION_MAX_TERMS]`
//! depth-1 array; both are stable-Rust const-buildable, so the SDK
//! macros support the full operand catalogue. Inputs exceeding the
//! caps fail `validate_const()` with a typed `ShapeViolation`.
#![deny(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
missing_docs,
clippy::missing_errors_doc
)]
use proc_macro::TokenStream;
use quote::quote;
use syn::ext::IdentExt;
use syn::parse::{Parse, ParseStream};
use syn::{parse_macro_input, Ident, Result, Token};
/// Callsite input for `product_shape!(Name, A, B)` — three identifier
/// tokens separated by commas.
struct ShapeArgs {
name: Ident,
left: Ident,
right: Ident,
}
impl Parse for ShapeArgs {
fn parse(input: ParseStream) -> Result<Self> {
let name: Ident = input.parse()?;
input.parse::<Token![,]>()?;
let left: Ident = input.parse()?;
input.parse::<Token![,]>()?;
let right: Ident = input.parse()?;
// Trailing comma permitted for consistency with Rust style.
let _ = input.parse::<Token![,]>();
Ok(Self { name, left, right })
}
}
/// Product-type shape constructor. See crate-level docs.
///
/// # Example
///
/// ```
/// use uor_foundation::pipeline::{ConstrainedTypeShape, ConstraintRef};
/// use uor_foundation_sdk::product_shape;
///
/// pub struct A;
/// impl ConstrainedTypeShape for A {
/// const IRI: &'static str = "https://example.org/A";
/// const SITE_COUNT: usize = 1;
/// const CONSTRAINTS: &'static [ConstraintRef] = &[
/// ConstraintRef::Residue { modulus: 7, residue: 3 },
/// ];
/// const CYCLE_SIZE: u64 = 7;
/// }
///
/// pub struct B;
/// impl ConstrainedTypeShape for B {
/// const IRI: &'static str = "https://example.org/B";
/// const SITE_COUNT: usize = 1;
/// const CONSTRAINTS: &'static [ConstraintRef] = &[
/// ConstraintRef::Hamming { bound: 1 },
/// ];
/// const CYCLE_SIZE: u64 = 2;
/// }
///
/// product_shape!(MyProduct, A, B);
///
/// assert!(<MyProduct as ConstrainedTypeShape>::IRI.starts_with("urn:uor:product:"));
/// assert_eq!(<MyProduct as ConstrainedTypeShape>::SITE_COUNT, 2);
/// ```
#[proc_macro]
pub fn product_shape(input: TokenStream) -> TokenStream {
let ShapeArgs { name, left, right } = parse_macro_input!(input as ShapeArgs);
let iri = format!(
"urn:uor:product:{}:{}",
lexically_earlier(&left, &right),
lexically_later(&left, &right)
);
// Canonicalize operand ordering by stable token spelling so
// `product_shape!(X, A, B)` and `product_shape!(X, B, A)` emit
// identical source. Documented as the §4e canonicalization rule the
// SDK enforces — the runtime content-fingerprint match §4e describes
// is then checked by consumer tests.
let (l, r) = canonical_operand_pair(&left, &right);
let raw_const = format_ident_suffix(&name, "__CONSTRAINTS_RAW");
let len_const = format_ident_suffix(&name, "__CONSTRAINTS_LEN");
let expansion = quote! {
/// UOR ProductType shape, emitted by `product_shape!`.
pub struct #name;
const #raw_const:
[::uor_foundation::pipeline::ConstraintRef;
2 * ::uor_foundation::enforcement::NERVE_CONSTRAINTS_CAP]
= ::uor_foundation::pipeline::sdk_concat_product_constraints::<#l, #r>();
const #len_const: usize =
::uor_foundation::pipeline::sdk_product_constraints_len::<#l, #r>();
impl ::uor_foundation::pipeline::ConstrainedTypeShape for #name {
const IRI: &'static str = #iri;
const SITE_BUDGET: usize =
<#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_BUDGET
+ <#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_BUDGET;
const SITE_COUNT: usize =
<#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT
+ <#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT;
const CONSTRAINTS: &'static [::uor_foundation::pipeline::ConstraintRef] = {
let buf: &'static [::uor_foundation::pipeline::ConstraintRef] = &#raw_const;
match buf.split_at_checked(#len_const) {
Some((head, _tail)) => head,
None => &[],
}
};
// ADR-032: product cardinality = saturating product of factors.
const CYCLE_SIZE: u64 = ::uor_foundation::pipeline::cycle_size_product(
<#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::CYCLE_SIZE,
<#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::CYCLE_SIZE,
);
}
// Wiki ADR-023 + ADR-027: shape-derived shapes receive the four
// sealed-trait impls (`__sdk_seal::Sealed`, `IntoBindingValue`,
// `GroundedShape`, plus the `ConstrainedTypeShape` impl above).
// The shape struct is a zero-sized type-level marker, so the
// canonical byte sequence is empty (MAX_BYTES = 0); applications
// that need to carry runtime input data declare a custom
// `ConstrainedTypeShape` via the `output_shape!` macro and write a
// bespoke `IntoBindingValue` impl.
impl ::uor_foundation::pipeline::__sdk_seal::Sealed for #name {}
impl<'a> ::uor_foundation::pipeline::IntoBindingValue<'a> for #name {
fn as_binding_value<const INLINE_BYTES: usize>(
&self,
) -> ::uor_foundation::pipeline::TermValue<'a, INLINE_BYTES> {
::uor_foundation::pipeline::TermValue::empty()
}
}
impl ::uor_foundation::enforcement::GroundedShape for #name {}
// ADR-033 G20: positional-only field directory. Field byte
// boundaries are derived from each factor's `SITE_COUNT` (the
// foundation convention: one byte per site in the canonical
// binding-table serialization). Composite operands inherit
// their cumulative SITE_COUNT through the product/coproduct
// composition rules.
impl ::uor_foundation::pipeline::PartitionProductFields for #name {
const FIELDS: &'static [(u32, u32)] = &[
(0u32, <#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT as u32),
(<#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT as u32,
<#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT as u32),
];
const FIELD_NAMES: &'static [&'static str] = &["", ""];
}
// ADR-033 G4: per-factor static-type carriers — chained access
// resolution by the `prism_model!` proc-macro names each
// intermediate shape via `<PrevTy as PartitionProductFactor<I>>::Factor`.
impl ::uor_foundation::pipeline::PartitionProductFactor<0> for #name {
type Factor = #l;
}
impl ::uor_foundation::pipeline::PartitionProductFactor<1> for #name {
type Factor = #r;
}
impl #name {
/// Mint a verified [`PartitionProductWitness`] for this shape's
/// operand pair. The numeric invariants (Euler characteristics,
/// entropy, fingerprints) are caller-supplied because they depend
/// on the resolved constraint configuration; shape-derivable
/// fields (site budgets / site counts) are read from the
/// operand `ConstrainedTypeShape` impls.
///
/// # Errors
///
/// Returns a `GenericImpossibilityWitness` citing the specific
/// failed identity when PT_1, PT_3, PT_4, or the foundation
/// layout-width invariant fails.
#[allow(clippy::too_many_arguments)]
pub fn mint_product_witness(
witt_bits: u16,
left_fingerprint: ::uor_foundation::ContentFingerprint,
right_fingerprint: ::uor_foundation::ContentFingerprint,
left_euler: i32,
right_euler: i32,
left_entropy_nats_bits: u64,
right_entropy_nats_bits: u64,
combined_euler: i32,
combined_entropy_nats_bits: u64,
combined_fingerprint: ::uor_foundation::ContentFingerprint,
) -> ::core::result::Result<
::uor_foundation::PartitionProductWitness,
::uor_foundation::enforcement::GenericImpossibilityWitness,
> {
use ::uor_foundation::pipeline::ConstrainedTypeShape;
let inputs = ::uor_foundation::PartitionProductMintInputs {
witt_bits,
left_fingerprint,
right_fingerprint,
left_site_budget: <#l as ConstrainedTypeShape>::SITE_BUDGET as u16,
right_site_budget: <#r as ConstrainedTypeShape>::SITE_BUDGET as u16,
left_total_site_count: <#l as ConstrainedTypeShape>::SITE_COUNT as u16,
right_total_site_count: <#r as ConstrainedTypeShape>::SITE_COUNT as u16,
left_euler,
right_euler,
left_entropy_nats_bits,
right_entropy_nats_bits,
combined_site_budget: <#name as ConstrainedTypeShape>::SITE_BUDGET as u16,
combined_site_count: <#name as ConstrainedTypeShape>::SITE_COUNT as u16,
combined_euler,
combined_entropy_nats_bits,
combined_fingerprint,
};
<::uor_foundation::PartitionProductWitness
as ::uor_foundation::VerifiedMint>::mint_verified(inputs)
}
}
};
expansion.into()
}
/// Coproduct shape constructor. See crate-level docs.
///
/// # Example
///
/// Demonstrates the post-Phase-17 fixed-array `Affine` operand variant.
///
/// ```
/// use uor_foundation::pipeline::{
/// AFFINE_MAX_COEFFS, ConstrainedTypeShape, ConstraintRef,
/// };
/// use uor_foundation_sdk::coproduct_shape;
///
/// const A_COEFFS: [i64; AFFINE_MAX_COEFFS] = {
/// let mut a = [0i64; AFFINE_MAX_COEFFS];
/// a[0] = 1;
/// a
/// };
///
/// pub struct A;
/// impl ConstrainedTypeShape for A {
/// const IRI: &'static str = "https://example.org/A";
/// const SITE_COUNT: usize = 1;
/// const CONSTRAINTS: &'static [ConstraintRef] = &[
/// ConstraintRef::Affine {
/// coefficients: A_COEFFS,
/// coefficient_count: 1,
/// bias: 0,
/// },
/// ];
/// const CYCLE_SIZE: u64 = 1;
/// }
///
/// pub struct B;
/// impl ConstrainedTypeShape for B {
/// const IRI: &'static str = "https://example.org/B";
/// const SITE_COUNT: usize = 1;
/// const CONSTRAINTS: &'static [ConstraintRef] = &[];
/// const CYCLE_SIZE: u64 = 1;
/// }
///
/// coproduct_shape!(MySum, A, B);
/// assert!(<MySum as ConstrainedTypeShape>::IRI.starts_with("urn:uor:coproduct:"));
/// ```
#[proc_macro]
pub fn coproduct_shape(input: TokenStream) -> TokenStream {
let ShapeArgs { name, left, right } = parse_macro_input!(input as ShapeArgs);
let iri = format!(
"urn:uor:coproduct:{}:{}",
lexically_earlier(&left, &right),
lexically_later(&left, &right)
);
let (l, r) = canonical_operand_pair(&left, &right);
// Per amendment §4b' + §4d: coproduct layout is
// constraints(A) ∪ {tag-pinner bias=0} ∪ constraints(B) ∪ {tag-pinner bias=-1}
// with tag_site = max(SITE_COUNT(A), SITE_COUNT(B)). The foundation
// `sdk_concat_product_constraints` helper handles the A / B splice
// but the two Affine tag-pinners require construction at macro time,
// because the tag_site index is a call-site-specific const expression.
//
// For a coproduct, the Affine coefficient slices are `&[i64]` with
// all-zero entries except position tag_site = 1. Since the macro
// cannot allocate `&'static [i64]` slices of arbitrary length, the
// emission uses a fixed-size coefficient array that matches
// `NERVE_CONSTRAINTS_CAP` (the bound on site indices in SDK shapes).
let raw_const = format_ident_suffix(&name, "__CONSTRAINTS_RAW");
let len_const = format_ident_suffix(&name, "__CONSTRAINTS_LEN");
let tag_coeffs_l = format_ident_suffix(&name, "__TAG_COEFFS_L");
let tag_coeffs_r = format_ident_suffix(&name, "__TAG_COEFFS_R");
let tag_coeff_count = format_ident_suffix(&name, "__TAG_COEFF_COUNT");
let expansion = quote! {
/// UOR SumType shape, emitted by `coproduct_shape!`.
pub struct #name;
// Two tag-pinning Affine coefficient arrays, one per variant,
// each of length 2 * NERVE_CONSTRAINTS_CAP so the single `1` at
// the tag_site position fits regardless of how wide the
// operands' SITE_COUNTs are (bounded by NERVE_CONSTRAINTS_CAP
// each, so tag_site = max(L::SITE_COUNT, R::SITE_COUNT) <
// Phase 17: tag-pinner coefficient buffer is now a fixed-size
// `[i64; AFFINE_MAX_COEFFS]` array stored inline in the
// ConstraintRef::Affine variant. The active prefix runs to
// `tag_site + 1`. For coproduct shapes whose
// `max(L::SITE_COUNT, R::SITE_COUNT) + 1` exceeds
// AFFINE_MAX_COEFFS = 8, the const-eval clamps the tag-pinner
// to a no-op (count = 0), and `validate_const` rejects the
// shape at admission time as Affine-unsatisfiable.
const #tag_coeffs_l: [i64; ::uor_foundation::pipeline::AFFINE_MAX_COEFFS] = {
let mut out = [0i64; ::uor_foundation::pipeline::AFFINE_MAX_COEFFS];
let tag_site = {
let a = <#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT;
let b = <#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT;
if a > b { a } else { b }
};
if tag_site < ::uor_foundation::pipeline::AFFINE_MAX_COEFFS {
out[tag_site] = 1;
}
out
};
const #tag_coeffs_r: [i64; ::uor_foundation::pipeline::AFFINE_MAX_COEFFS] = #tag_coeffs_l;
const #tag_coeff_count: u32 = {
let a = <#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT;
let b = <#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT;
let tag_site = if a > b { a } else { b };
(tag_site as u32).saturating_add(1)
};
// Full constraint buffer: L constraints + L tag-pinner (bias=0)
// + R constraints (shifted by L::SITE_COUNT? — per amendment §4d
// sum types share the data-site space so R's site references are
// NOT shifted). The foundation helper
// `sdk_concat_product_constraints` shifts R by A::SITE_COUNT, which
// is correct for products but wrong for coproducts. Coproducts
// instead splice R's constraints verbatim since the tag site is
// the distinguishing bit, not a layout offset.
//
// This makes coproduct construction diverge from the helper's
// assumption, so we emit a per-callsite const fn that does the
// correct coproduct splice.
const #raw_const:
[::uor_foundation::pipeline::ConstraintRef;
2 * ::uor_foundation::enforcement::NERVE_CONSTRAINTS_CAP + 2]
= {
let mut out =
[::uor_foundation::pipeline::ConstraintRef::Site { position: u32::MAX };
2 * ::uor_foundation::enforcement::NERVE_CONSTRAINTS_CAP + 2];
let left_arr = <#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::CONSTRAINTS;
let right_arr = <#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::CONSTRAINTS;
let mut i = 0;
while i < left_arr.len() {
out[i] = left_arr[i];
i += 1;
}
// L's tag-pinner: bias 0.
out[i] = ::uor_foundation::pipeline::ConstraintRef::Affine {
coefficients: #tag_coeffs_l,
coefficient_count: #tag_coeff_count,
bias: 0,
};
let left_boundary = i + 1;
let mut j = 0;
while j < right_arr.len() {
out[left_boundary + j] = right_arr[j];
j += 1;
}
// R's tag-pinner: bias -1.
out[left_boundary + right_arr.len()] = ::uor_foundation::pipeline::ConstraintRef::Affine {
coefficients: #tag_coeffs_r,
coefficient_count: #tag_coeff_count,
bias: -1,
};
out
};
const #len_const: usize =
<#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::CONSTRAINTS.len()
+ <#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::CONSTRAINTS.len()
+ 2;
impl ::uor_foundation::pipeline::ConstrainedTypeShape for #name {
const IRI: &'static str = #iri;
const SITE_BUDGET: usize = {
let a = <#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_BUDGET;
let b = <#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_BUDGET;
if a > b { a } else { b }
};
const SITE_COUNT: usize = {
let a = <#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT;
let b = <#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT;
(if a > b { a } else { b }) + 1
};
const CONSTRAINTS: &'static [::uor_foundation::pipeline::ConstraintRef] = {
let buf: &'static [::uor_foundation::pipeline::ConstraintRef] = &#raw_const;
match buf.split_at_checked(#len_const) {
Some((head, _tail)) => head,
None => &[],
}
};
// ADR-032: coproduct cardinality = saturating sum + 1
// (the `+ 1` is the discriminant tag's contribution).
const CYCLE_SIZE: u64 = ::uor_foundation::pipeline::cycle_size_coproduct(
<#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::CYCLE_SIZE,
<#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::CYCLE_SIZE,
);
}
// Wiki ADR-023 + ADR-027: shape-derived shapes receive the four
// sealed-trait impls so they qualify as both Input
// (`IntoBindingValue`) and Output (`GroundedShape` +
// `IntoBindingValue`) for `PrismModel` (zero-sized marker;
// canonical byte sequence is empty).
impl ::uor_foundation::pipeline::__sdk_seal::Sealed for #name {}
impl<'a> ::uor_foundation::pipeline::IntoBindingValue<'a> for #name {
fn as_binding_value<const INLINE_BYTES: usize>(
&self,
) -> ::uor_foundation::pipeline::TermValue<'a, INLINE_BYTES> {
::uor_foundation::pipeline::TermValue::empty()
}
}
impl ::uor_foundation::enforcement::GroundedShape for #name {}
impl #name {
/// Mint a verified [`PartitionCoproductWitness`] for this shape's
/// operand pair. See `product_shape!`'s `mint_product_witness`
/// doc comment for the caller-vs-derived field split.
///
/// # Errors
///
/// Returns a `GenericImpossibilityWitness` citing the specific
/// failed identity when ST_1, ST_2, ST_6, ST_7, ST_8, ST_9,
/// ST_10, the `CoproductLayoutWidth` layout invariant, or the
/// `CoproductTagEncoding` byte-pattern invariant fails.
#[allow(clippy::too_many_arguments)]
pub fn mint_coproduct_witness(
witt_bits: u16,
left_fingerprint: ::uor_foundation::ContentFingerprint,
right_fingerprint: ::uor_foundation::ContentFingerprint,
left_euler: i32,
right_euler: i32,
left_entropy_nats_bits: u64,
right_entropy_nats_bits: u64,
left_betti: [u32; ::uor_foundation::enforcement::MAX_BETTI_DIMENSION],
right_betti: [u32; ::uor_foundation::enforcement::MAX_BETTI_DIMENSION],
combined_euler: i32,
combined_entropy_nats_bits: u64,
combined_betti: [u32; ::uor_foundation::enforcement::MAX_BETTI_DIMENSION],
combined_fingerprint: ::uor_foundation::ContentFingerprint,
) -> ::core::result::Result<
::uor_foundation::PartitionCoproductWitness,
::uor_foundation::enforcement::GenericImpossibilityWitness,
> {
use ::uor_foundation::pipeline::ConstrainedTypeShape;
let left_total_site_count = <#l as ConstrainedTypeShape>::SITE_COUNT as u16;
let right_total_site_count = <#r as ConstrainedTypeShape>::SITE_COUNT as u16;
let tag_site = if left_total_site_count > right_total_site_count {
left_total_site_count
} else {
right_total_site_count
};
let left_constraint_count =
<#l as ConstrainedTypeShape>::CONSTRAINTS.len() + 1;
let inputs = ::uor_foundation::PartitionCoproductMintInputs {
witt_bits,
left_fingerprint,
right_fingerprint,
left_site_budget: <#l as ConstrainedTypeShape>::SITE_BUDGET as u16,
right_site_budget: <#r as ConstrainedTypeShape>::SITE_BUDGET as u16,
left_total_site_count,
right_total_site_count,
left_euler,
right_euler,
left_entropy_nats_bits,
right_entropy_nats_bits,
left_betti,
right_betti,
combined_site_budget: <#name as ConstrainedTypeShape>::SITE_BUDGET as u16,
combined_site_count: <#name as ConstrainedTypeShape>::SITE_COUNT as u16,
combined_euler,
combined_entropy_nats_bits,
combined_betti,
combined_fingerprint,
combined_constraints: <#name as ConstrainedTypeShape>::CONSTRAINTS,
left_constraint_count,
tag_site,
};
<::uor_foundation::PartitionCoproductWitness
as ::uor_foundation::VerifiedMint>::mint_verified(inputs)
}
}
};
expansion.into()
}
/// Cartesian-product shape constructor. See crate-level docs.
///
/// # Example
///
/// ```
/// use uor_foundation::pipeline::{
/// CartesianProductShape, ConstrainedTypeShape, ConstraintRef,
/// };
/// use uor_foundation_sdk::cartesian_product_shape;
///
/// pub struct A;
/// impl ConstrainedTypeShape for A {
/// const IRI: &'static str = "https://example.org/A";
/// const SITE_COUNT: usize = 1;
/// const CONSTRAINTS: &'static [ConstraintRef] = &[];
/// const CYCLE_SIZE: u64 = 1;
/// }
/// pub struct B;
/// impl ConstrainedTypeShape for B {
/// const IRI: &'static str = "https://example.org/B";
/// const SITE_COUNT: usize = 1;
/// const CONSTRAINTS: &'static [ConstraintRef] = &[];
/// const CYCLE_SIZE: u64 = 1;
/// }
///
/// cartesian_product_shape!(MyCartesian, A, B);
///
/// fn assert_marker<T: CartesianProductShape>() {}
/// assert_marker::<MyCartesian>();
/// ```
#[proc_macro]
pub fn cartesian_product_shape(input: TokenStream) -> TokenStream {
let ShapeArgs { name, left, right } = parse_macro_input!(input as ShapeArgs);
let iri = format!(
"urn:uor:cartesian:{}:{}",
lexically_earlier(&left, &right),
lexically_later(&left, &right)
);
let (l, r) = canonical_operand_pair(&left, &right);
let raw_const = format_ident_suffix(&name, "__CONSTRAINTS_RAW");
let len_const = format_ident_suffix(&name, "__CONSTRAINTS_LEN");
// CartesianProduct emission mirrors product_shape!'s layout but
// additionally implements `CartesianProductShape` so the nerve-Betti
// pipeline uses `primitive_cartesian_nerve_betti` (Künneth) instead of
// the flat simplicial primitive.
let expansion = quote! {
/// UOR CartesianPartitionProduct shape, emitted by
/// `cartesian_product_shape!`.
pub struct #name;
const #raw_const:
[::uor_foundation::pipeline::ConstraintRef;
2 * ::uor_foundation::enforcement::NERVE_CONSTRAINTS_CAP]
= ::uor_foundation::pipeline::sdk_concat_product_constraints::<#l, #r>();
const #len_const: usize =
::uor_foundation::pipeline::sdk_product_constraints_len::<#l, #r>();
impl ::uor_foundation::pipeline::ConstrainedTypeShape for #name {
const IRI: &'static str = #iri;
const SITE_BUDGET: usize =
<#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_BUDGET
+ <#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_BUDGET;
const SITE_COUNT: usize =
<#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT
+ <#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT;
const CONSTRAINTS: &'static [::uor_foundation::pipeline::ConstraintRef] = {
let buf: &'static [::uor_foundation::pipeline::ConstraintRef] = &#raw_const;
match buf.split_at_checked(#len_const) {
Some((head, _tail)) => head,
None => &[],
}
};
// ADR-032: cartesian-product cardinality = saturating product
// (the binary `cartesian_product_shape!` is the two-factor case;
// ≥3 factors compose left-associatively). Equivalent to
// saturating-power for the homogeneous case but expressed via
// the binary product since this macro takes two operands.
const CYCLE_SIZE: u64 = ::uor_foundation::pipeline::cycle_size_product(
<#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::CYCLE_SIZE,
<#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::CYCLE_SIZE,
);
}
impl ::uor_foundation::pipeline::CartesianProductShape for #name {
type Left = #l;
type Right = #r;
}
// Wiki ADR-023 + ADR-027: shape-derived shapes receive the four
// sealed-trait impls so they qualify as both Input
// (`IntoBindingValue`) and Output (`GroundedShape` +
// `IntoBindingValue`) for `PrismModel` (zero-sized marker;
// canonical byte sequence is empty).
impl ::uor_foundation::pipeline::__sdk_seal::Sealed for #name {}
impl<'a> ::uor_foundation::pipeline::IntoBindingValue<'a> for #name {
fn as_binding_value<const INLINE_BYTES: usize>(
&self,
) -> ::uor_foundation::pipeline::TermValue<'a, INLINE_BYTES> {
::uor_foundation::pipeline::TermValue::empty()
}
}
impl ::uor_foundation::enforcement::GroundedShape for #name {}
// ADR-033 G20: positional-only field directory. Field byte
// boundaries are derived from each factor's `SITE_COUNT` (the
// foundation convention: one byte per site in the canonical
// binding-table serialization). Composite operands inherit
// their cumulative SITE_COUNT through the product/coproduct
// composition rules.
impl ::uor_foundation::pipeline::PartitionProductFields for #name {
const FIELDS: &'static [(u32, u32)] = &[
(0u32, <#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT as u32),
(<#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT as u32,
<#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT as u32),
];
const FIELD_NAMES: &'static [&'static str] = &["", ""];
}
// ADR-033 G4: per-factor static-type carriers for chained access.
impl ::uor_foundation::pipeline::PartitionProductFactor<0> for #name {
type Factor = #l;
}
impl ::uor_foundation::pipeline::PartitionProductFactor<1> for #name {
type Factor = #r;
}
impl #name {
/// Mint a verified [`CartesianProductWitness`] for this shape's
/// operand pair.
///
/// # Errors
///
/// Returns a `GenericImpossibilityWitness` citing the specific
/// failed identity when CPT_1, CPT_3, CPT_4, CPT_5, or the
/// `CartesianLayoutWidth` layout invariant fails.
#[allow(clippy::too_many_arguments)]
pub fn mint_cartesian_witness(
witt_bits: u16,
left_fingerprint: ::uor_foundation::ContentFingerprint,
right_fingerprint: ::uor_foundation::ContentFingerprint,
left_euler: i32,
right_euler: i32,
left_betti: [u32; ::uor_foundation::enforcement::MAX_BETTI_DIMENSION],
right_betti: [u32; ::uor_foundation::enforcement::MAX_BETTI_DIMENSION],
left_entropy_nats_bits: u64,
right_entropy_nats_bits: u64,
combined_euler: i32,
combined_betti: [u32; ::uor_foundation::enforcement::MAX_BETTI_DIMENSION],
combined_entropy_nats_bits: u64,
combined_fingerprint: ::uor_foundation::ContentFingerprint,
) -> ::core::result::Result<
::uor_foundation::CartesianProductWitness,
::uor_foundation::enforcement::GenericImpossibilityWitness,
> {
use ::uor_foundation::pipeline::ConstrainedTypeShape;
let inputs = ::uor_foundation::CartesianProductMintInputs {
witt_bits,
left_fingerprint,
right_fingerprint,
left_site_budget: <#l as ConstrainedTypeShape>::SITE_BUDGET as u16,
right_site_budget: <#r as ConstrainedTypeShape>::SITE_BUDGET as u16,
left_total_site_count: <#l as ConstrainedTypeShape>::SITE_COUNT as u16,
right_total_site_count: <#r as ConstrainedTypeShape>::SITE_COUNT as u16,
left_euler,
right_euler,
left_betti,
right_betti,
left_entropy_nats_bits,
right_entropy_nats_bits,
combined_site_budget: <#name as ConstrainedTypeShape>::SITE_BUDGET as u16,
combined_site_count: <#name as ConstrainedTypeShape>::SITE_COUNT as u16,
combined_euler,
combined_betti,
combined_entropy_nats_bits,
combined_fingerprint,
};
<::uor_foundation::CartesianProductWitness
as ::uor_foundation::VerifiedMint>::mint_verified(inputs)
}
}
};
expansion.into()
}
// =====================================================================
// `partition_product!` and `partition_coproduct!` — wiki ADR-026 G17 + G18.
//
// ADR-026 specifies these as type-level operators recognised in
// `type Input` / `type Output` positions as variadic forms
// `partition_product!(<A>, <B>, …)`. On stable Rust 1.83 the in-position
// variadic form requires `generic_const_exprs` (unstable) to compute
// `IRI`/`CONSTRAINTS` from operand type-parameters at the trait level;
// the architecturally-equivalent stable-Rust surface is the same macros
// at item position with a name argument followed by the operand list:
//
// `partition_product!(<Name>, <A>, <B>, [<C>, …]);`
// `partition_coproduct!(<Name>, <A>, <B>, [<C>, …]);`
//
// Three or more operands fold left-associatively: `partition_product!(N, A, B, C)`
// emits the chain `((A × B) × C)` via repeated PT_3 composition. The
// emitted `ConstrainedTypeShape` impl carries the canonically-joined
// `CONSTRAINTS` per ADR-025's PT_3 rule and the IRI per ADR-017's
// content-deterministic naming.
/// Variadic input: `partition_product!(Name, A, B, [C, …])`.
struct VariadicShapeArgs {
name: Ident,
/// Operands as full `syn::Type` since v0.4.11 — admits both bare
/// identifiers (`LeafA`) and generic-parameter-bearing types
/// (`BigIntShape<128>`, `MerkleRoot<H, 32>`). The latter resolves
/// the implementer-reported const-generic leaf depth-2 access
/// gap by letting closure-body field-access expressions thread the
/// full type through `<#ty as PartitionProductFields>::FIELDS[idx]`
/// const-eval lookups.
operands: Vec<syn::Type>,
/// ADR-033 G3: per-operand field names, parallel to `operands`. Each
/// entry is `Some(ident)` for the named-field form
/// `partition_product!(N, lhs: A, rhs: B)` and `None` for positional
/// `partition_product!(N, A, B)`. The two forms must not be mixed in
/// a single invocation.
field_names: Vec<Option<Ident>>,
/// ADR-057 recurse markers, parallel to `operands`. `None` indicates
/// a normal (non-recursive) operand whose constraints inline at the
/// operand's position; `Some(bound)` indicates a `recurse:T` or
/// `recurse(bound):T` operand that lowers to `ConstraintRef::Recurse
/// { shape_iri: <T>::IRI, descent_bound: bound }` at the operand's
/// position. The descent_bound is a `proc_macro2::TokenStream` so the
/// bound expression can be any const-evaluable u32 expression
/// (literal, const reference, `<AppBounds as HostBounds>` associated
/// const, etc.); when the `recurse:T` form omits the bound, the
/// expression defaults to `u32::MAX` (saturated descent).
recurse_bounds: Vec<Option<proc_macro2::TokenStream>>,
}
impl Parse for VariadicShapeArgs {
fn parse(input: ParseStream) -> Result<Self> {
let name: Ident = input.parse()?;
input.parse::<Token![,]>()?;
let mut operands: Vec<syn::Type> = Vec::new();
let mut field_names: Vec<Option<Ident>> = Vec::new();
let mut recurse_bounds: Vec<Option<proc_macro2::TokenStream>> = Vec::new();
// Helper: try to parse one operand, possibly with a `name:` prefix
// and possibly with a `recurse:` or `recurse(<bound>):` prefix.
// The decision tree:
// - `recurse:T` → positional + recurse, bound = u32::MAX
// - `recurse(<bound>):T` → positional + recurse, bound = <bound>
// - `<name>: recurse:T` → named + recurse, bound = u32::MAX
// - `<name>: recurse(<bound>):T` → named + recurse, bound = <bound>
// - `<name>:T` → named, non-recurse (pre-ADR-057 form)
// - `T` → positional, non-recurse (pre-ADR-057 form)
// Returns (field_name, operand_type, recurse_bound).
fn parse_one(
input: ParseStream,
) -> Result<(Option<Ident>, syn::Type, Option<proc_macro2::TokenStream>)> {
// ADR-033 G3 + ADR-057 dispatch:
// `recurse:T` → positional + recurse (saturated)
// `recurse(<b>):T` → positional + recurse (bounded)
// `<name>:recurse:T` → named + recurse (saturated)
// `<name>:recurse(<b>):T` → named + recurse (bounded)
// `<name>:T` → named (non-recurse)
// `T` → positional (non-recurse)
//
// The named-field detection forks past the leading ident +
// `:`. We MUST exclude `recurse` from the named-field
// interpretation: `recurse:T` is a positional recurse marker,
// not a field named "recurse" containing a `T`-typed scalar.
// The wiki's ADR-057 operand grammar reserves `recurse` as a
// marker keyword.
let forked = input.fork();
let mut field_name: Option<Ident> = None;
if let Ok(maybe_name) = forked.parse::<Ident>() {
if maybe_name != "recurse" && forked.peek(Token![:]) {
// Confirmed named-field form (and the name is not the
// reserved `recurse` marker). Consume the ident + colon
// from the real stream; the operand-position parser
// below then handles either a `recurse` marker or a
// plain type.
field_name = Some(input.parse::<Ident>()?);
input.parse::<Token![:]>()?;
}
}
// Check for `recurse` operand marker at operand position.
let recurse_bound = parse_optional_recurse_marker(input)?;
// Parse the operand type.
let ty: syn::Type = input.parse()?;
Ok((field_name, ty, recurse_bound))
}
let (n0, t0, r0) = parse_one(input)?;
field_names.push(n0);
operands.push(t0);
recurse_bounds.push(r0);
while input.peek(Token![,]) {
input.parse::<Token![,]>()?;
if input.is_empty() {
break;
}
let (ni, ti, ri) = parse_one(input)?;
field_names.push(ni);
operands.push(ti);
recurse_bounds.push(ri);
}
if operands.len() < 2 {
return Err(syn::Error::new(
name.span(),
"partition_product!/partition_coproduct! require at least two operands",
));
}
// ADR-033 G3: enforce all-or-nothing — either every operand has
// a name or none does. Mixed forms are a closure violation.
let any_named = field_names.iter().any(|n| n.is_some());
let all_named = field_names.iter().all(|n| n.is_some());
if any_named && !all_named {
return Err(syn::Error::new(
name.span(),
"partition_product!/partition_coproduct!: named-field form must name every operand (or use the positional form for all)",
));
}
Ok(Self {
name,
operands,
field_names,
recurse_bounds,
})
}
}
/// ADR-057: parse an optional `recurse` or `recurse(<bound>)` marker
/// preceding an operand type. Returns `Some(bound_tokens)` when the
/// marker is present (defaulting to `u32::MAX` when no `(<bound>)`
/// group is supplied), `None` when no marker is present.
fn parse_optional_recurse_marker(input: ParseStream) -> Result<Option<proc_macro2::TokenStream>> {
// Speculative parse: peek for an `Ident` whose string is "recurse"
// followed by either `:` (the `recurse:T` form, but we'll consume
// `recurse` here and let the caller's `:` handling in parse_one
// distinguish it from a name-prefix `:`) or `(...)` for the bounded
// form. We use a fork to look ahead without consuming if the marker
// isn't present.
let forked = input.fork();
let Ok(marker_ident) = forked.parse::<Ident>() else {
return Ok(None);
};
if marker_ident != "recurse" {
return Ok(None);
}
// We confirmed `recurse`. Look at what follows:
// `recurse(<bound>):T` — paren group then colon
// `recurse:T` — bare colon
// Anything else is a parse error.
if forked.peek(syn::token::Paren) {
// Bounded form. Consume the ident, the paren group, and the colon.
input.parse::<Ident>()?;
let content;
syn::parenthesized!(content in input);
let bound_expr: syn::Expr = content.parse()?;
input.parse::<Token![:]>()?;
Ok(Some(quote! { (#bound_expr) as u32 }))
} else if forked.peek(Token![:]) {
// Saturated form. Consume the ident and the colon.
input.parse::<Ident>()?;
input.parse::<Token![:]>()?;
Ok(Some(quote! { u32::MAX }))
} else {
// Not a recurse marker after all — the identifier is the
// operand's own type (a struct named `recurse` would shadow
// the marker, but that's an architectural violation —
// `recurse` is a reserved operand-grammar identifier per
// ADR-057). Fall through to treat the ident as a type.
Ok(None)
}
}
/// `partition_product!` — wiki ADR-026 G17 type-level shape constructor.
/// Emits a `ConstrainedTypeShape` impl whose `CONSTRAINTS` carry the
/// canonically-joined PT_3 form (algebraic-product per ADR-025), with
/// `SITE_COUNT = Σ operands' SITE_COUNT`.
#[proc_macro]
pub fn partition_product(input: TokenStream) -> TokenStream {
let parsed = parse_macro_input!(input as VariadicShapeArgs);
expand_partition_product(
parsed.name,
&parsed.operands,
&parsed.field_names,
&parsed.recurse_bounds,
)
}
fn expand_partition_product(
name: Ident,
operands: &[syn::Type],
field_names: &[Option<Ident>],
recurse_bounds: &[Option<proc_macro2::TokenStream>],
) -> TokenStream {
// ADR-057: any operand marked `recurse:T` or `recurse(<bound>):T`
// triggers the recurse-aware emission path. The binary form uses
// `sdk_concat_product_constraints_v2`; CYCLE_SIZE saturates at
// `u64::MAX` per the ADR's "shape with Recurse constraint saturates"
// rule.
let any_recurse = recurse_bounds.iter().any(|b| b.is_some());
if operands.len() == 2 {
// Binary form — delegate to the existing product_shape! semantics
// by emitting the same ConstrainedTypeShape impl pattern with the
// PT_3 canonical-join `CONSTRAINTS`.
let l_orig = &operands[0];
let r_orig = &operands[1];
let l_recurse = &recurse_bounds[0];
let r_recurse = &recurse_bounds[1];
let iri = format!(
"urn:uor:product:{}:{}",
lexically_earlier_ty(l_orig, r_orig),
lexically_later_ty(l_orig, r_orig),
);
// ADR-057: canonical ordering is preserved, but when an operand
// is recurse-marked the marker must travel with the operand. We
// canonicalize the (type, recurse_bound) pair together.
let (l, r, l_recurse, r_recurse) = if type_token_string(l_orig) <= type_token_string(r_orig)
{
(
l_orig.clone(),
r_orig.clone(),
l_recurse.clone(),
r_recurse.clone(),
)
} else {
(
r_orig.clone(),
l_orig.clone(),
r_recurse.clone(),
l_recurse.clone(),
)
};
let _ = canonical_operand_pair_ty; // suppress unused-import lint if generated
let raw_const = format_ident_suffix(&name, "__CONSTRAINTS_RAW");
let len_const = format_ident_suffix(&name, "__CONSTRAINTS_LEN");
// ADR-033 G3: per-factor names — empty string for positional, the
// user-supplied identifier for named.
let l_name_lit = field_names
.first()
.and_then(|n| n.as_ref())
.map(|i| i.to_string())
.unwrap_or_default();
let r_name_lit = field_names
.get(1)
.and_then(|n| n.as_ref())
.map(|i| i.to_string())
.unwrap_or_default();
// ADR-033 G4: per-positional-index `PartitionProductFactor` impls
// emit the static type of each factor so chained field-access
// expressions in `prism_model!` closures can synthesize further
// `<NextSource as PartitionProductFields>::FIELDS` lookups.
//
// ADR-057: when any operand is recurse-marked, switch to the v2
// emission path (`sdk_concat_product_constraints_v2`) and saturate
// CYCLE_SIZE at u64::MAX per the wiki commitment.
let (raw_const_init, len_const_init, cycle_size_init): (
proc_macro2::TokenStream,
proc_macro2::TokenStream,
proc_macro2::TokenStream,
) = if any_recurse {
let l_recurse_expr = match &l_recurse {
Some(bound) => quote! { ::core::option::Option::Some(#bound) },
None => quote! { ::core::option::Option::None },
};
let r_recurse_expr = match &r_recurse {
Some(bound) => quote! { ::core::option::Option::Some(#bound) },
None => quote! { ::core::option::Option::None },
};
let l_recurse_flag = l_recurse.is_some();
let r_recurse_flag = r_recurse.is_some();
(
quote! {
::uor_foundation::pipeline::sdk_concat_product_constraints_v2::<#l, #r>(
#l_recurse_expr,
#r_recurse_expr,
)
},
quote! {
::uor_foundation::pipeline::sdk_product_constraints_v2_len::<#l, #r>(
#l_recurse_flag,
#r_recurse_flag,
)
},
quote! { u64::MAX },
)
} else {
(
quote! { ::uor_foundation::pipeline::sdk_concat_product_constraints::<#l, #r>() },
quote! { ::uor_foundation::pipeline::sdk_product_constraints_len::<#l, #r>() },
quote! {
::uor_foundation::pipeline::cycle_size_product(
<#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::CYCLE_SIZE,
<#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::CYCLE_SIZE,
)
},
)
};
let expansion = quote! {
/// UOR ADR-026 G17 partition-product shape (binary form).
pub struct #name;
const #raw_const:
[::uor_foundation::pipeline::ConstraintRef;
2 * ::uor_foundation::enforcement::NERVE_CONSTRAINTS_CAP]
= #raw_const_init;
const #len_const: usize = #len_const_init;
impl ::uor_foundation::pipeline::ConstrainedTypeShape for #name {
const IRI: &'static str = #iri;
const SITE_BUDGET: usize =
<#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_BUDGET
+ <#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_BUDGET;
const SITE_COUNT: usize =
<#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT
+ <#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT;
const CONSTRAINTS: &'static [::uor_foundation::pipeline::ConstraintRef] = {
let buf: &'static [::uor_foundation::pipeline::ConstraintRef] = &#raw_const;
match buf.split_at_checked(#len_const) {
Some((head, _tail)) => head,
None => &[],
}
};
// ADR-032 + ADR-057: cardinality saturates at u64::MAX when
// any operand is recurse-marked (the runtime resolves the
// recursive expansion against the registered shape's
// `<T>::CYCLE_SIZE`, which itself may be saturated).
const CYCLE_SIZE: u64 = #cycle_size_init;
}
impl ::uor_foundation::pipeline::__sdk_seal::Sealed for #name {}
impl<'a> ::uor_foundation::pipeline::IntoBindingValue<'a> for #name {
fn as_binding_value<const INLINE_BYTES: usize>(
&self,
) -> ::uor_foundation::pipeline::TermValue<'a, INLINE_BYTES> {
::uor_foundation::pipeline::TermValue::empty()
}
}
impl ::uor_foundation::enforcement::GroundedShape for #name {}
// ADR-033 G20: factor-field directory. FIELD_NAMES carries the
// named-form identifiers when supplied, "" otherwise.
impl ::uor_foundation::pipeline::PartitionProductFields for #name {
const FIELDS: &'static [(u32, u32)] = &[
(0u32, <#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT as u32),
(<#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT as u32,
<#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT as u32),
];
const FIELD_NAMES: &'static [&'static str] = &[#l_name_lit, #r_name_lit];
}
// ADR-033 G4: per-factor static-type carriers — used by the
// `prism_model!` proc-macro to thread the static type of a
// chained field access (`input.outer.inner`) so the inner
// ProjectField's offset/length lookup names the right
// `PartitionProductFields` impl.
impl ::uor_foundation::pipeline::PartitionProductFactor<0> for #name {
type Factor = #l;
}
impl ::uor_foundation::pipeline::PartitionProductFactor<1> for #name {
type Factor = #r;
}
};
expansion.into()
} else {
// Variadic form, ≥3 operands.
let any_named = field_names.iter().any(|n| n.is_some());
if any_named {
// ADR-033 G3 named-variadic form: emit the final shape as a
// flat N-factor product with FIELDS/FIELD_NAMES exposing each
// operand directly. The byte offsets are running sums of
// SITE_COUNT.
return expand_partition_product_named_flat(
name,
operands,
field_names,
recurse_bounds,
);
}
// Positional variadic: keep the existing left-associative
// helper-step chain; FIELD_NAMES stays positional ("","").
// ADR-057: each helper step folds an operand's recurse_bound into
// the binary product; intermediate step types are non-recurse
// (they're synthesized partition products).
let mut intermediate_names: Vec<Ident> = Vec::with_capacity(operands.len() - 1);
for i in 0..operands.len() - 2 {
intermediate_names.push(Ident::new(&format!("{}PpStep{}", name, i), name.span()));
}
let mut chain: Vec<proc_macro2::TokenStream> = Vec::with_capacity(operands.len() - 1);
// First step: A × B → PpStep0
let mut prev = if operands.len() > 2 {
intermediate_names[0].clone()
} else {
name.clone()
};
let first_a = &operands[0];
let first_b = &operands[1];
let first_step_call = expand_partition_product_helper(
prev.clone(),
first_a,
first_b,
&recurse_bounds[0],
&recurse_bounds[1],
);
chain.push(first_step_call);
// Each subsequent step: prev × operand[i+1] → next. `prev` is
// always a synthesized intermediate Ident; wrap as Type::Path so
// the helper's `&syn::Type` signature accepts it. The
// intermediate-step type is never recurse-marked; operand[i]'s
// recurse bound flows into the right side.
for i in 2..operands.len() {
let next = if i == operands.len() - 1 {
name.clone()
} else {
intermediate_names[i - 1].clone()
};
let prev_ty: syn::Type = syn::parse_quote! { #prev };
let next_call = expand_partition_product_helper(
next.clone(),
&prev_ty,
&operands[i],
&None,
&recurse_bounds[i],
);
chain.push(next_call);
prev = next;
}
let combined = quote! { #( #chain )* };
combined.into()
}
}
/// ADR-033 G3 named-variadic emission: `partition_product!(N, a: A, b: B, c: C)`
/// produces a flat N-factor shape whose `FIELDS` and `FIELD_NAMES` expose
/// each operand directly (running-sum offsets over SITE_COUNT). This is
/// the architecturally-correct form for named variadic — the alternative
/// (left-associative helper steps) would force users to access fields
/// via `input.0.0` rather than the names they supplied.
fn expand_partition_product_named_flat(
name: Ident,
operands: &[syn::Type],
field_names: &[Option<Ident>],
recurse_bounds: &[Option<proc_macro2::TokenStream>],
) -> TokenStream {
let any_recurse = recurse_bounds.iter().any(|b| b.is_some());
// Build the FIELDS array: `(running_sum, operand_i.SITE_COUNT)`.
let mut fields_entries: Vec<proc_macro2::TokenStream> = Vec::with_capacity(operands.len());
for (i, op) in operands.iter().enumerate() {
// Running sum: Σ_{j<i} operand_j.SITE_COUNT
let running_sum: proc_macro2::TokenStream = if i == 0 {
quote::quote! { 0u32 }
} else {
let prior = &operands[..i];
quote::quote! {
0u32 #(
+ <#prior as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT as u32
)*
}
};
fields_entries.push(quote::quote! {
(#running_sum, <#op as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT as u32)
});
}
// FIELD_NAMES: the user-supplied identifiers as string literals.
let name_lits: Vec<String> = field_names
.iter()
.map(|n| n.as_ref().map(|i| i.to_string()).unwrap_or_default())
.collect();
// Per-index PartitionProductFactor impls.
let factor_impls: Vec<proc_macro2::TokenStream> = operands
.iter()
.enumerate()
.map(|(i, op)| {
quote::quote! {
impl ::uor_foundation::pipeline::PartitionProductFactor<#i> for #name {
type Factor = #op;
}
}
})
.collect();
// SITE_COUNT and SITE_BUDGET: sums.
let site_count_sum: proc_macro2::TokenStream = quote::quote! {
0usize #(
+ <#operands as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT
)*
};
let site_budget_sum: proc_macro2::TokenStream = quote::quote! {
0usize #(
+ <#operands as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_BUDGET
)*
};
// CYCLE_SIZE: left-associative product fold via cycle_size_product.
// ADR-057: when any operand is recurse-marked, CYCLE_SIZE saturates
// at u64::MAX.
let cycle_size_expr: proc_macro2::TokenStream = if any_recurse {
quote::quote! { u64::MAX }
} else {
let mut acc = quote::quote! { 1u64 };
for op in operands {
acc = quote::quote! {
::uor_foundation::pipeline::cycle_size_product(
#acc,
<#op as ::uor_foundation::pipeline::ConstrainedTypeShape>::CYCLE_SIZE,
)
};
}
acc
};
// IRI: enumerate operands lexicographically (by token-stream-string,
// which incorporates generic-arg lists) for stability.
let mut sorted: Vec<&syn::Type> = operands.iter().collect();
sorted.sort_by_key(|t| type_token_string(t));
let iri_body: String = sorted
.iter()
.map(|t| type_token_string(t))
.collect::<Vec<_>>()
.join(":");
let iri = format!("urn:uor:product:{iri_body}");
let raw_const = format_ident_suffix(&name, "__CONSTRAINTS_RAW");
let len_const = format_ident_suffix(&name, "__CONSTRAINTS_LEN");
// CONSTRAINTS: build via the binary helper applied to the first two
// operands' (type, recurse_bound) pair. For ≥3 operands the
// architectural fold (left-associative product) makes the
// first-pair representation a structural witness; downstream
// preflight consumes this slice. ADR-057-marked operands flow
// through the v2 helper.
let l = &operands[0];
let r = &operands[1];
let l_recurse = &recurse_bounds[0];
let r_recurse = &recurse_bounds[1];
let (raw_const_init, len_const_init): (proc_macro2::TokenStream, proc_macro2::TokenStream) =
if l_recurse.is_some() || r_recurse.is_some() {
let l_recurse_expr = match l_recurse {
Some(bound) => quote::quote! { ::core::option::Option::Some(#bound) },
None => quote::quote! { ::core::option::Option::None },
};
let r_recurse_expr = match r_recurse {
Some(bound) => quote::quote! { ::core::option::Option::Some(#bound) },
None => quote::quote! { ::core::option::Option::None },
};
let l_recurse_flag = l_recurse.is_some();
let r_recurse_flag = r_recurse.is_some();
(
quote::quote! {
::uor_foundation::pipeline::sdk_concat_product_constraints_v2::<#l, #r>(
#l_recurse_expr,
#r_recurse_expr,
)
},
quote::quote! {
::uor_foundation::pipeline::sdk_product_constraints_v2_len::<#l, #r>(
#l_recurse_flag,
#r_recurse_flag,
)
},
)
} else {
(
quote::quote! {
::uor_foundation::pipeline::sdk_concat_product_constraints::<#l, #r>()
},
quote::quote! {
::uor_foundation::pipeline::sdk_product_constraints_len::<#l, #r>()
},
)
};
let expansion = quote::quote! {
/// UOR ADR-026 G17 partition-product shape (named variadic form).
pub struct #name;
const #raw_const:
[::uor_foundation::pipeline::ConstraintRef;
2 * ::uor_foundation::enforcement::NERVE_CONSTRAINTS_CAP]
= #raw_const_init;
const #len_const: usize = #len_const_init;
impl ::uor_foundation::pipeline::ConstrainedTypeShape for #name {
const IRI: &'static str = #iri;
const SITE_BUDGET: usize = #site_budget_sum;
const SITE_COUNT: usize = #site_count_sum;
const CONSTRAINTS: &'static [::uor_foundation::pipeline::ConstraintRef] = {
let buf: &'static [::uor_foundation::pipeline::ConstraintRef] = &#raw_const;
match buf.split_at_checked(#len_const) {
Some((head, _tail)) => head,
None => &[],
}
};
const CYCLE_SIZE: u64 = #cycle_size_expr;
}
impl ::uor_foundation::pipeline::__sdk_seal::Sealed for #name {}
impl<'a> ::uor_foundation::pipeline::IntoBindingValue<'a> for #name {
fn as_binding_value<const INLINE_BYTES: usize>(
&self,
) -> ::uor_foundation::pipeline::TermValue<'a, INLINE_BYTES> {
::uor_foundation::pipeline::TermValue::empty()
}
}
impl ::uor_foundation::enforcement::GroundedShape for #name {}
impl ::uor_foundation::pipeline::PartitionProductFields for #name {
const FIELDS: &'static [(u32, u32)] = &[ #( #fields_entries ),* ];
const FIELD_NAMES: &'static [&'static str] = &[ #( #name_lits ),* ];
}
#( #factor_impls )*
};
expansion.into()
}
/// Emit the `ConstrainedTypeShape` + supporting impl-block for a
/// binary partition-product step. Used by `expand_partition_product`'s
/// left-associative variadic chain.
fn expand_partition_product_helper(
name: Ident,
left: &syn::Type,
right: &syn::Type,
left_recurse: &Option<proc_macro2::TokenStream>,
right_recurse: &Option<proc_macro2::TokenStream>,
) -> proc_macro2::TokenStream {
let iri = format!(
"urn:uor:product:{}:{}",
lexically_earlier_ty(left, right),
lexically_later_ty(left, right),
);
// ADR-057: canonical ordering pairs the (type, recurse_bound) together
// so the recurse marker travels with the operand it qualifies.
let (l, r, l_recurse, r_recurse) = if type_token_string(left) <= type_token_string(right) {
(
left.clone(),
right.clone(),
left_recurse.clone(),
right_recurse.clone(),
)
} else {
(
right.clone(),
left.clone(),
right_recurse.clone(),
left_recurse.clone(),
)
};
let _ = canonical_operand_pair_ty; // helper still exported; suppress unused
let any_recurse = l_recurse.is_some() || r_recurse.is_some();
let raw_const = format_ident_suffix(&name, "__CONSTRAINTS_RAW");
let len_const = format_ident_suffix(&name, "__CONSTRAINTS_LEN");
let (raw_const_init, len_const_init, cycle_size_init): (
proc_macro2::TokenStream,
proc_macro2::TokenStream,
proc_macro2::TokenStream,
) = if any_recurse {
let l_recurse_expr = match &l_recurse {
Some(bound) => quote! { ::core::option::Option::Some(#bound) },
None => quote! { ::core::option::Option::None },
};
let r_recurse_expr = match &r_recurse {
Some(bound) => quote! { ::core::option::Option::Some(#bound) },
None => quote! { ::core::option::Option::None },
};
let l_recurse_flag = l_recurse.is_some();
let r_recurse_flag = r_recurse.is_some();
(
quote! {
::uor_foundation::pipeline::sdk_concat_product_constraints_v2::<#l, #r>(
#l_recurse_expr,
#r_recurse_expr,
)
},
quote! {
::uor_foundation::pipeline::sdk_product_constraints_v2_len::<#l, #r>(
#l_recurse_flag,
#r_recurse_flag,
)
},
quote! { u64::MAX },
)
} else {
(
quote! { ::uor_foundation::pipeline::sdk_concat_product_constraints::<#l, #r>() },
quote! { ::uor_foundation::pipeline::sdk_product_constraints_len::<#l, #r>() },
quote! {
::uor_foundation::pipeline::cycle_size_product(
<#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::CYCLE_SIZE,
<#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::CYCLE_SIZE,
)
},
)
};
quote! {
/// UOR ADR-026 G17 partition-product step.
pub struct #name;
const #raw_const:
[::uor_foundation::pipeline::ConstraintRef;
2 * ::uor_foundation::enforcement::NERVE_CONSTRAINTS_CAP]
= #raw_const_init;
const #len_const: usize = #len_const_init;
impl ::uor_foundation::pipeline::ConstrainedTypeShape for #name {
const IRI: &'static str = #iri;
const SITE_BUDGET: usize =
<#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_BUDGET
+ <#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_BUDGET;
const SITE_COUNT: usize =
<#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT
+ <#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT;
const CONSTRAINTS: &'static [::uor_foundation::pipeline::ConstraintRef] = {
let buf: &'static [::uor_foundation::pipeline::ConstraintRef] = &#raw_const;
match buf.split_at_checked(#len_const) {
Some((head, _tail)) => head,
None => &[],
}
};
// ADR-032 + ADR-057: cardinality saturates at u64::MAX when
// any operand is recurse-marked (the runtime expansion against
// the registry resolves the recursive contribution).
const CYCLE_SIZE: u64 = #cycle_size_init;
}
impl ::uor_foundation::pipeline::__sdk_seal::Sealed for #name {}
impl<'a> ::uor_foundation::pipeline::IntoBindingValue<'a> for #name {
fn as_binding_value<const INLINE_BYTES: usize>(
&self,
) -> ::uor_foundation::pipeline::TermValue<'a, INLINE_BYTES> {
::uor_foundation::pipeline::TermValue::empty()
}
}
impl ::uor_foundation::enforcement::GroundedShape for #name {}
// ADR-033 G20: positional-only field directory for the helper
// step. SITE_COUNT-derived (see ADR-033 conventions in the
// emit_term_for_field helper).
impl ::uor_foundation::pipeline::PartitionProductFields for #name {
const FIELDS: &'static [(u32, u32)] = &[
(0u32, <#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT as u32),
(<#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT as u32,
<#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT as u32),
];
const FIELD_NAMES: &'static [&'static str] = &["", ""];
}
// ADR-033 G4: per-factor static-type carriers for chained access
// resolution by the `prism_model!` proc-macro.
impl ::uor_foundation::pipeline::PartitionProductFactor<0> for #name {
type Factor = #l;
}
impl ::uor_foundation::pipeline::PartitionProductFactor<1> for #name {
type Factor = #r;
}
}
}
/// `partition_coproduct!` — wiki ADR-026 G18 type-level shape constructor.
/// Variadic named form. Folds left-associatively into binary
/// coproducts. Each binary step emits the same shape `coproduct_shape!`
/// produces (ST_10 canonical structure).
#[proc_macro]
pub fn partition_coproduct(input: TokenStream) -> TokenStream {
let parsed = parse_macro_input!(input as VariadicShapeArgs);
if parsed.field_names.iter().any(|n| n.is_some()) {
return syn::Error::new(
parsed.name.span(),
"partition_coproduct! does not accept named-field form (coproducts discriminate by tag, not by named field; ADR-033 G3 named-field form applies to partition_product!)",
)
.to_compile_error()
.into();
}
expand_partition_coproduct(parsed.name, &parsed.operands, &parsed.recurse_bounds)
}
fn expand_partition_coproduct(
name: Ident,
operands: &[syn::Type],
recurse_bounds: &[Option<proc_macro2::TokenStream>],
) -> TokenStream {
if operands.len() == 2 {
let combined = expand_partition_coproduct_helper(
name,
&operands[0],
&operands[1],
&recurse_bounds[0],
&recurse_bounds[1],
);
return combined.into();
}
let mut intermediate_names: Vec<Ident> = Vec::with_capacity(operands.len() - 1);
for i in 0..operands.len() - 2 {
intermediate_names.push(Ident::new(&format!("{}PcStep{}", name, i), name.span()));
}
let mut chain: Vec<proc_macro2::TokenStream> = Vec::with_capacity(operands.len() - 1);
let mut prev = if operands.len() > 2 {
intermediate_names[0].clone()
} else {
name.clone()
};
let first_step = expand_partition_coproduct_helper(
prev.clone(),
&operands[0],
&operands[1],
&recurse_bounds[0],
&recurse_bounds[1],
);
chain.push(first_step);
for i in 2..operands.len() {
let next = if i == operands.len() - 1 {
name.clone()
} else {
intermediate_names[i - 1].clone()
};
let prev_ty: syn::Type = syn::parse_quote! { #prev };
// The intermediate-step type is never recurse-marked.
let step = expand_partition_coproduct_helper(
next.clone(),
&prev_ty,
&operands[i],
&None,
&recurse_bounds[i],
);
chain.push(step);
prev = next;
}
let combined = quote! { #( #chain )* };
combined.into()
}
fn expand_partition_coproduct_helper(
name: Ident,
left: &syn::Type,
right: &syn::Type,
left_recurse: &Option<proc_macro2::TokenStream>,
right_recurse: &Option<proc_macro2::TokenStream>,
) -> proc_macro2::TokenStream {
let iri = format!(
"urn:uor:coproduct:{}:{}",
lexically_earlier_ty(left, right),
lexically_later_ty(left, right),
);
// ADR-057: canonical ordering pairs (type, recurse_bound) together.
let (l, r, l_recurse, r_recurse) = if type_token_string(left) <= type_token_string(right) {
(
left.clone(),
right.clone(),
left_recurse.clone(),
right_recurse.clone(),
)
} else {
(
right.clone(),
left.clone(),
right_recurse.clone(),
left_recurse.clone(),
)
};
let _ = canonical_operand_pair_ty;
let any_recurse = l_recurse.is_some() || r_recurse.is_some();
let raw_const = format_ident_suffix(&name, "__CONSTRAINTS_RAW");
let len_const = format_ident_suffix(&name, "__CONSTRAINTS_LEN");
let tag_coeffs_l = format_ident_suffix(&name, "__TAG_COEFFS_L");
let tag_coeffs_r = format_ident_suffix(&name, "__TAG_COEFFS_R");
let tag_coeff_count = format_ident_suffix(&name, "__TAG_COEFF_COUNT");
// ADR-057: per-operand contribution blocks. Each block is a
// statement-list emitted inside the const-init for #raw_const; it
// advances `i` by the operand's number of constraint entries
// (`<T>::CONSTRAINTS.len()` for inline, `1` for recurse).
let left_block: proc_macro2::TokenStream = match &l_recurse {
Some(bound) => quote! {
out[i] = ::uor_foundation::pipeline::ConstraintRef::Recurse {
shape_iri: <#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::IRI,
descent_bound: #bound,
};
i += 1;
},
None => quote! {
let left_arr = <#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::CONSTRAINTS;
let mut li = 0;
while li < left_arr.len() {
out[i] = left_arr[li];
i += 1;
li += 1;
}
},
};
let right_block: proc_macro2::TokenStream = match &r_recurse {
Some(bound) => quote! {
out[i] = ::uor_foundation::pipeline::ConstraintRef::Recurse {
shape_iri: <#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::IRI,
descent_bound: #bound,
};
i += 1;
},
None => quote! {
let right_arr = <#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::CONSTRAINTS;
let mut ri = 0;
while ri < right_arr.len() {
out[i] = right_arr[ri];
i += 1;
ri += 1;
}
},
};
// Length is left-contribution + 1 (tag) + right-contribution + 1 (tag).
let len_const_init: proc_macro2::TokenStream = {
let left_len = match &l_recurse {
Some(_) => quote! { 1usize },
None => quote! {
<#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::CONSTRAINTS.len()
},
};
let right_len = match &r_recurse {
Some(_) => quote! { 1usize },
None => quote! {
<#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::CONSTRAINTS.len()
},
};
quote! { #left_len + #right_len + 2 }
};
let cycle_size_init: proc_macro2::TokenStream = if any_recurse {
quote! { u64::MAX }
} else {
quote! {
::uor_foundation::pipeline::cycle_size_coproduct(
<#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::CYCLE_SIZE,
<#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::CYCLE_SIZE,
)
}
};
quote! {
/// UOR ADR-026 G18 partition-coproduct step.
pub struct #name;
const #tag_coeffs_l: [i64; ::uor_foundation::pipeline::AFFINE_MAX_COEFFS] = {
let mut out = [0i64; ::uor_foundation::pipeline::AFFINE_MAX_COEFFS];
let tag_site = {
let a = <#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT;
let b = <#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT;
if a > b { a } else { b }
};
if tag_site < ::uor_foundation::pipeline::AFFINE_MAX_COEFFS {
out[tag_site] = 1;
}
out
};
const #tag_coeffs_r: [i64; ::uor_foundation::pipeline::AFFINE_MAX_COEFFS] = #tag_coeffs_l;
const #tag_coeff_count: u32 = {
let a = <#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT;
let b = <#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT;
let tag_site = if a > b { a } else { b };
(tag_site as u32).saturating_add(1)
};
const #raw_const:
[::uor_foundation::pipeline::ConstraintRef;
2 * ::uor_foundation::enforcement::NERVE_CONSTRAINTS_CAP + 2]
= {
let mut out =
[::uor_foundation::pipeline::ConstraintRef::Site { position: u32::MAX };
2 * ::uor_foundation::enforcement::NERVE_CONSTRAINTS_CAP + 2];
// ADR-057: per-operand contribution is either the operand's
// inline `CONSTRAINTS` array (default) or a single Recurse
// entry referencing the operand's shape IRI.
let mut i = 0;
#left_block
out[i] = ::uor_foundation::pipeline::ConstraintRef::Affine {
coefficients: #tag_coeffs_l,
coefficient_count: #tag_coeff_count,
bias: 0,
};
i += 1;
#right_block
out[i] = ::uor_foundation::pipeline::ConstraintRef::Affine {
coefficients: #tag_coeffs_r,
coefficient_count: #tag_coeff_count,
bias: -1,
};
out
};
const #len_const: usize = #len_const_init;
impl ::uor_foundation::pipeline::ConstrainedTypeShape for #name {
const IRI: &'static str = #iri;
const SITE_BUDGET: usize = {
let a = <#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_BUDGET;
let b = <#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_BUDGET;
if a > b { a } else { b }
};
const SITE_COUNT: usize = {
let a = <#l as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT;
let b = <#r as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT;
(if a > b { a } else { b }) + 1
};
const CONSTRAINTS: &'static [::uor_foundation::pipeline::ConstraintRef] = {
let buf: &'static [::uor_foundation::pipeline::ConstraintRef] = &#raw_const;
match buf.split_at_checked(#len_const) {
Some((head, _tail)) => head,
None => &[],
}
};
// ADR-032 + ADR-057: coproduct cardinality = saturating sum + 1
// for non-recurse; saturates at u64::MAX when any operand
// carries a Recurse reference.
const CYCLE_SIZE: u64 = #cycle_size_init;
}
impl ::uor_foundation::pipeline::__sdk_seal::Sealed for #name {}
impl<'a> ::uor_foundation::pipeline::IntoBindingValue<'a> for #name {
fn as_binding_value<const INLINE_BYTES: usize>(
&self,
) -> ::uor_foundation::pipeline::TermValue<'a, INLINE_BYTES> {
::uor_foundation::pipeline::TermValue::empty()
}
}
impl ::uor_foundation::enforcement::GroundedShape for #name {}
}
}
// =====================================================================
// `prism_model!` — wiki ADR-020 + ADR-022 D3.
//
// The macro accepts the closure-bodied form the wiki specifies as the
// maximally-Rust-native syntax for declaring a Prism model:
//
// ```text
// prism_model! {
// pub struct MyModel;
// pub struct MyRoute;
// impl PrismModel<HType, BType, AType> for MyModel {
// type Input = InputShape;
// type Output = OutputShape;
// type Route = MyRoute;
// fn route(input: Self::Input) -> Self::Output {
// // closure body — Rust expression syntax parsed by the macro
// // into a Term tree at expansion time. The body never executes
// // as Rust at runtime; it is consumed at macro time, mapped to
// // the term-tree representation, and the macro emits both the
// // term tree (as a `&'static [Term]` slice) and the
// // closure-checked `FoundationClosed` impl.
// //
// // Recognised foundation-vocabulary forms:
// // - integer literals → Term::Literal
// // - identifier `input` → Term::Variable
// // - lowercase PrimitiveOp → Term::Application
// // names: add, sub, mul, xor, and, or
// // neg, bnot, succ, pred
// // Anything else fails to compile, pointing at the offending
// // call site (a closure violation per ADR-020).
// }
// }
// }
// ```
//
// Emissions (per ADR-022):
// D1: `impl __sdk_seal::Sealed for MyModel`,
// `impl __sdk_seal::Sealed for MyRoute`
// D2: `const ROUTE_TERMS_<MODEL>: &'static [Term] = &[…]` (fully const
// — `TermArena::from_slice(ROUTE_TERMS_<MODEL>)` is a `const fn`)
// D5: `impl FoundationClosed for MyRoute { arena_slice() → ROUTE_TERMS_<MODEL> }`
// D4: `impl PrismModel<H,B,A> for MyModel { …; fn forward(input) { run_route::<H,B,A,Self>(input) } }`
/// Parsed shape of the macro input — a struct declaration for the model,
/// optionally one for the route witness, and an `impl PrismModel<…> for
/// <Model>` block carrying the three (or four, when ADR-036's ResolverTuple
/// substrate parameter is selected) associated types and the closure-bodied
/// `route` function. The optional `fn resolvers() -> R { … }` clause
/// supplies the ResolverTuple instance for routes that walk the resolver-
/// bound ψ-Term variants (ADR-035 + ADR-036).
struct PrismModelInput {
model_vis: syn::Visibility,
model_name: Ident,
route_vis: syn::Visibility,
route_name: Ident,
h_ty: syn::Type,
b_ty: syn::Type,
a_ty: syn::Type,
/// `Some(R)` for `impl PrismModel<H, B, A, R> for Model` (ADR-036
/// four-position form); `None` for the three-position form
/// (R defaults to `NullResolverTuple` on the trait).
r_ty: Option<syn::Type>,
/// `Some(C)` for `impl PrismModel<H, B, A, R, C> for Model` (ADR-048
/// five-position form); `None` defaults to `EmptyCommitment` per the
/// `PrismModel` trait's default-type parameter. Wiki ADR-048 commits
/// the 5th substrate parameter as the cost-model commitment surface.
c_ty: Option<syn::Type>,
input_ty: syn::Type,
output_ty: syn::Type,
route_input_ident: Ident,
route_body: syn::Block,
/// Optional `fn resolvers() -> R { <expr> }` clause supplying the
/// ResolverTuple instance the macro-emitted `forward` body borrows.
/// Present iff the user includes the clause; foundation derives the
/// default (`R::default()` for `R: Default`, falling back to
/// `NullResolverTuple` when `r_ty` is `None`) at expansion time.
resolvers_body: Option<syn::Block>,
/// Optional `fn commitment() -> C { <expr> }` clause supplying the
/// TypedCommitment instance the macro-emitted `forward` body borrows.
/// Present iff the user includes the clause; foundation derives the
/// default (`C::default()` for `C: Default`, falling back to
/// `EmptyCommitment` when `c_ty` is `None`) at expansion time.
commitment_body: Option<syn::Block>,
}
impl Parse for PrismModelInput {
fn parse(input: ParseStream) -> Result<Self> {
// Model struct: `pub struct ModelName;`
let model_vis: syn::Visibility = input.parse()?;
input.parse::<Token![struct]>()?;
let model_name: Ident = input.parse()?;
input.parse::<Token![;]>()?;
// Route witness struct: `pub struct RouteName;`
let route_vis: syn::Visibility = input.parse()?;
input.parse::<Token![struct]>()?;
let route_name: Ident = input.parse()?;
input.parse::<Token![;]>()?;
// `impl PrismModel<H, B, A[, R]> for ModelName`
input.parse::<Token![impl]>()?;
let trait_ident: Ident = input.parse()?;
if trait_ident != "PrismModel" {
return Err(syn::Error::new(
trait_ident.span(),
"prism_model! expects an `impl PrismModel<H, B, A[, R[, C]]> for <Model>` block",
));
}
input.parse::<Token![<]>()?;
let h_ty: syn::Type = input.parse()?;
input.parse::<Token![,]>()?;
let b_ty: syn::Type = input.parse()?;
input.parse::<Token![,]>()?;
let a_ty: syn::Type = input.parse()?;
// ADR-036: optional fourth substrate-parameter position (R: ResolverTuple).
let r_ty: Option<syn::Type> = if input.peek(Token![,]) {
input.parse::<Token![,]>()?;
Some(input.parse::<syn::Type>()?)
} else {
None
};
// ADR-048: optional fifth substrate-parameter position (C: TypedCommitment).
let c_ty: Option<syn::Type> = if input.peek(Token![,]) {
input.parse::<Token![,]>()?;
Some(input.parse::<syn::Type>()?)
} else {
None
};
input.parse::<Token![>]>()?;
input.parse::<Token![for]>()?;
let impl_target: Ident = input.parse()?;
if impl_target != model_name {
return Err(syn::Error::new(
impl_target.span(),
"prism_model!'s `impl PrismModel<…> for <Model>` target must match the declared model struct",
));
}
// Body of the impl block:
// { type Input = …; type Output = …; type Route = …;
// fn route(…) { … } [ fn resolvers() -> R { … } ] }
let body;
syn::braced!(body in input);
// type Input = …;
body.parse::<Token![type]>()?;
let input_kw: Ident = body.parse()?;
if input_kw != "Input" {
return Err(syn::Error::new(
input_kw.span(),
"expected `type Input = …;`",
));
}
body.parse::<Token![=]>()?;
let input_ty: syn::Type = body.parse()?;
body.parse::<Token![;]>()?;
// type Output = …;
body.parse::<Token![type]>()?;
let output_kw: Ident = body.parse()?;
if output_kw != "Output" {
return Err(syn::Error::new(
output_kw.span(),
"expected `type Output = …;`",
));
}
body.parse::<Token![=]>()?;
let output_ty: syn::Type = body.parse()?;
body.parse::<Token![;]>()?;
// type Route = …;
body.parse::<Token![type]>()?;
let route_kw: Ident = body.parse()?;
if route_kw != "Route" {
return Err(syn::Error::new(
route_kw.span(),
"expected `type Route = …;`",
));
}
body.parse::<Token![=]>()?;
let route_ty_ident: Ident = body.parse()?;
if route_ty_ident != route_name {
return Err(syn::Error::new(
route_ty_ident.span(),
"prism_model!'s `type Route = <RouteName>;` must match the declared route struct",
));
}
body.parse::<Token![;]>()?;
// fn route(input: Self::Input) -> Self::Output { … }
body.parse::<Token![fn]>()?;
let fn_kw: Ident = body.parse()?;
if fn_kw != "route" {
return Err(syn::Error::new(
fn_kw.span(),
"expected `fn route(input: Self::Input) -> Self::Output { … }`",
));
}
let params;
syn::parenthesized!(params in body);
let route_input_ident: Ident = params.parse()?;
params.parse::<Token![:]>()?;
let _input_param_ty: syn::Type = params.parse()?;
// Discard return-type position — we already know it from `type Output`.
body.parse::<Token![->]>()?;
let _output_param_ty: syn::Type = body.parse()?;
let route_body: syn::Block = body.parse()?;
// Optional `fn resolvers() -> R { … }` (ADR-036) followed by
// optional `fn commitment() -> C { … }` (ADR-048). The two
// clauses are independent and order-flexible — the parser
// consumes whichever `fn` it sees and matches by identifier.
let mut resolvers_body: Option<syn::Block> = None;
let mut commitment_body: Option<syn::Block> = None;
while body.peek(Token![fn]) {
body.parse::<Token![fn]>()?;
let method_kw: Ident = body.parse()?;
let method_name = method_kw.to_string();
if method_name != "resolvers" && method_name != "commitment" {
return Err(syn::Error::new(
method_kw.span(),
"the only optional methods after `fn route` are `fn resolvers() -> R { … }` (ADR-036) and `fn commitment() -> C { … }` (ADR-048)",
));
}
let method_params;
syn::parenthesized!(method_params in body);
if !method_params.is_empty() {
return Err(syn::Error::new(
method_kw.span(),
"`fn resolvers()` / `fn commitment()` take no parameters — their return value is the per-call substrate instance",
));
}
body.parse::<Token![->]>()?;
let _ret_ty: syn::Type = body.parse()?;
let block: syn::Block = body.parse()?;
if method_name == "resolvers" {
if resolvers_body.is_some() {
return Err(syn::Error::new(
method_kw.span(),
"duplicate `fn resolvers()` clause in `prism_model!` body",
));
}
resolvers_body = Some(block);
} else {
if commitment_body.is_some() {
return Err(syn::Error::new(
method_kw.span(),
"duplicate `fn commitment()` clause in `prism_model!` body",
));
}
commitment_body = Some(block);
}
}
Ok(Self {
model_vis,
model_name,
route_vis,
route_name,
h_ty,
b_ty,
a_ty,
r_ty,
c_ty,
input_ty,
output_ty,
route_input_ident,
route_body,
resolvers_body,
commitment_body,
})
}
}
/// One spec entry in the term arena being built. Maps to a `Term::*`
/// variant token stream at emission time.
/// Wiki ADR-035 receiver-shape kinds for ψ-chain compatibility checks.
/// The closure-body parser tags each emitted TermSpec with its produced
/// shape and validates ψ-chain operand-shape mismatches at proc-macro
/// expansion (`chain_complex` requires a simplicial-complex operand,
/// `homology_groups` requires a chain-complex operand, etc.).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PsiShape {
/// Byte sequence — Literal, Variable, Application, ProjectField,
/// Try, Recurse, Unfold, Match, Lift, Project. Also the output of
/// `Term::Betti` (the β-vector serialization, a byte sequence) and
/// `Term::KInvariants` (the κ-label byte serialization).
Byte,
/// SimplicialComplex — output of `Term::Nerve` (ψ_1).
SimplicialComplex,
/// ChainComplex — output of `Term::ChainComplex` (ψ_2).
ChainComplex,
/// HomologyGroups — output of `Term::HomologyGroups` (ψ_3).
HomologyGroups,
/// CochainComplex — output of `Term::CochainComplex` (ψ_5).
CochainComplex,
/// CohomologyGroups — output of `Term::CohomologyGroups` (ψ_6).
CohomologyGroups,
/// PostnikovTower — output of `Term::PostnikovTower` (ψ_7).
PostnikovTower,
/// HomotopyGroups — output of `Term::HomotopyGroups` (ψ_8).
HomotopyGroups,
}
impl PsiShape {
/// Human-readable description used in receiver-shape violation
/// error messages.
fn describe(self) -> &'static str {
match self {
PsiShape::Byte => "byte-shaped",
PsiShape::SimplicialComplex => "simplicial-complex-shaped",
PsiShape::ChainComplex => "chain-complex-shaped",
PsiShape::HomologyGroups => "homology-groups-shaped",
PsiShape::CochainComplex => "cochain-complex-shaped",
PsiShape::CohomologyGroups => "cohomology-groups-shaped",
PsiShape::PostnikovTower => "Postnikov-tower-shaped",
PsiShape::HomotopyGroups => "homotopy-groups-shaped",
}
}
}
/// Determine the produced shape of a TermSpec. Combinatorial Term
/// variants produce byte-shaped values; ψ-Term variants produce their
/// per-stage ontology-defined shape (per ADR-035's nine ψ-maps).
fn term_spec_shape(spec: &TermSpec) -> PsiShape {
match spec {
TermSpec::Nerve { .. } => PsiShape::SimplicialComplex,
TermSpec::ChainComplex { .. } => PsiShape::ChainComplex,
TermSpec::HomologyGroups { .. } => PsiShape::HomologyGroups,
TermSpec::CochainComplex { .. } => PsiShape::CochainComplex,
TermSpec::CohomologyGroups { .. } => PsiShape::CohomologyGroups,
TermSpec::PostnikovTower { .. } => PsiShape::PostnikovTower,
TermSpec::HomotopyGroups { .. } => PsiShape::HomotopyGroups,
// `Betti` extracts a β-vector serialization — byte-shaped at the
// catamorphism's TermValue level. `KInvariants` produces the
// κ-label byte serialization — byte-shaped. All other Term
// variants are byte-shaped per the existing closure-body
// grammar (ADR-022 D3 G1..G20).
_ => PsiShape::Byte,
}
}
/// Receiver-shape compatibility per wiki ADR-035:
/// - `nerve` (G21): operand must be byte-shaped (per-value bytes).
/// - All other ψ-Term variants (G22..G29): operand must be the exact
/// upstream ψ-stage shape — receiver and operand match exactly.
fn psi_shape_compatible(expected: PsiShape, actual: PsiShape) -> bool {
expected == actual
}
// `TermSpec::AxisInvocation`, `TermSpec::FirstAdmit`,
// `TermSpec::FirstAdmitIdxPlaceholder`, and `TermSpec::LiteralExpr` are
// retained as inert variants for substrate compatibility with prior
// macro-emitter shapes. Under the wiki ADR-035 ψ-residuals discipline,
// the closure-body parser rejects `first_admit(...)`, `hash(...)`, and
// byte-comparison/concat operators at emission time, so these variants
// are not constructed by the current verb-body emitter. The match arms
// against them survive in clone/render paths to keep the enum
// total-functioned should non-verb-body callers (conformance generators,
// trace replay) emit a TermSpec arena containing them.
#[allow(dead_code)]
enum TermSpec {
/// `Term::Literal { value, level: WittLevel::W8 }`
Literal(u64),
/// `Term::Variable { name_index: 0 }` (the macro recognises `input`
/// as the sole bound name; future iterations support `let` bindings).
Variable,
/// `Term::Application { operator, args: TermList { start, len } }`
Application {
operator: proc_macro2::TokenStream,
args_start: u32,
args_len: u32,
},
/// `Term::AxisInvocation { axis_index, kernel_id, input_index }` —
/// wiki ADR-030 (replaces ADR-026 G19's HasherProjection). G19's
/// `hash(input)` form lowers to AxisInvocation against axis 0
/// (the application's HashAxis position) and kernel 0 (HashAxis::KERNEL_HASH).
AxisInvocation {
axis_index: u32,
kernel_id: u32,
input_index: u32,
},
/// `Term::ProjectField { source_index, byte_offset, byte_length }`
/// — wiki ADR-033 G20. Byte-slice projection over a partition_product
/// source; offsets/lengths are const-eval token streams referencing
/// `<RouteInputTy as PartitionProductFields>::FIELDS[idx]` so the
/// values are computed by the trait impl at the consumer's compile
/// time (positional and named forms both lower to indexed lookup).
ProjectField {
source_index: u32,
byte_offset: proc_macro2::TokenStream,
byte_length: proc_macro2::TokenStream,
},
/// `Term::FirstAdmit { domain_size_index, predicate_index }` — wiki
/// ADR-034 Mechanism 2. Bounded structural search over a domain of
/// size N (read from the domain type's `CYCLE_SIZE` per ADR-032);
/// the catamorphism iterates `idx` ascending and short-circuits on
/// the first non-zero predicate result.
FirstAdmit {
domain_size_index: u32,
predicate_index: u32,
},
/// FirstAdmit candidate-value placeholder — wiki ADR-034 Mechanism 2.
/// Lowers to `Term::Variable { name_index: FIRST_ADMIT_IDX_NAME_INDEX }`.
/// The catamorphism's Variable handler returns the threaded
/// `first_admit_idx_value` (the current candidate `idx` packed at the
/// domain's byte width).
FirstAdmitIdxPlaceholder,
/// Recurse iteration-counter placeholder — wiki ADR-034 Mechanism 1.
/// Lowers to `Term::Variable { name_index: RECURSE_IDX_NAME_INDEX }`.
/// The catamorphism's Variable handler returns the threaded
/// `recurse_idx_value` (the current measure value, i.e. the
/// iteration counter at this descent).
RecurseIdxPlaceholder,
/// ψ_1 (wiki ADR-035 G21): `Term::Nerve { value_index }`.
Nerve { value_index: u32 },
/// ψ_2 (wiki ADR-035 G22): `Term::ChainComplex { simplicial_index }`.
ChainComplex { simplicial_index: u32 },
/// ψ_3 (wiki ADR-035 G23): `Term::HomologyGroups { chain_index }`.
HomologyGroups { chain_index: u32 },
/// ψ_4 (wiki ADR-035 G24): `Term::Betti { homology_index }`.
Betti { homology_index: u32 },
/// ψ_5 (wiki ADR-035 G25): `Term::CochainComplex { chain_index }`.
CochainComplex { chain_index: u32 },
/// ψ_6 (wiki ADR-035 G26): `Term::CohomologyGroups { cochain_index }`.
CohomologyGroups { cochain_index: u32 },
/// ψ_7 (wiki ADR-035 G27): `Term::PostnikovTower { simplicial_index }`.
PostnikovTower { simplicial_index: u32 },
/// ψ_8 (wiki ADR-035 G28): `Term::HomotopyGroups { postnikov_index }`.
HomotopyGroups { postnikov_index: u32 },
/// ψ_9 (wiki ADR-035 G29): `Term::KInvariants { homotopy_index }`.
KInvariants { homotopy_index: u32 },
/// `Term::Literal { value: <const-eval expr>, level: <expr> }` — a
/// Literal whose value is a const-eval token stream rather than a
/// macro-time u64. Used by ADR-032's `first_admit` lowering to read
/// the descent measure from `<DomainTy as ConstrainedTypeShape>::CYCLE_SIZE`
/// at the consumer's compile time.
LiteralExpr {
value: proc_macro2::TokenStream,
level: proc_macro2::TokenStream,
},
/// ADR-051 wide-Witt literal carrier (Dependency 2 in v0.4.10): a
/// `Term::Literal` whose `value` is a byte sequence (rather than a
/// u64). Surfaces as `literal_bytes(&[u8], WittLevel)` in verb bodies.
/// Renders to `pipeline::literal_bytes(<bytes_expr>, <level_expr>)`
/// at the consumer's compile time, producing a const Term::Literal
/// whose TermValue carrier holds the full byte sequence.
///
/// Required for wide Witt-level literals (W128+) that don't fit in
/// a u64 — secp256k1 P_LITERAL (W256), AES round constants (W128),
/// FHE plaintext-coefficient tables, etc.
LiteralBytesExpr {
bytes: proc_macro2::TokenStream,
level: proc_macro2::TokenStream,
},
/// Compile-time verb splice — wiki ADR-024.
///
/// Inlines the verb's `&'static [Term]` fragment into the host
/// arena at expansion time via `inline_verb_fragment` (with each
/// internal arena index shifted by the host's current length) plus
/// substitution: every `Term::Variable { name_index: 0 }` in the
/// fragment is replaced by the host arena's term at `arg_root_idx`.
/// The substitution makes the verb's `input` parameter bind to the
/// caller's argument expression.
///
/// `arg_root_idx` is the TermSpec arena index whose result position
/// the verb's input substitutes to. The render layer translates
/// TermSpec indices to dynamic host positions via per-spec
/// `pos_<N>` const-let bindings emitted in the arena builder.
VerbSplice {
arg_root_idx: u32,
fragment_path: proc_macro2::TokenStream,
},
/// `Term::Lift { operand_index, target }` — wiki ADR-022 D3 G4.
/// Canonical injection from the operand's Witt level to a strictly
/// higher target level (lossless zero-extension).
Lift {
operand_index: u32,
target_witt: proc_macro2::TokenStream,
},
/// `Term::Project { operand_index, target }` — wiki ADR-022 D3 G5.
/// Canonical surjection from the operand's Witt level to a strictly
/// lower target level (lossy truncation).
Project {
operand_index: u32,
target_witt: proc_macro2::TokenStream,
},
/// `Term::Try { body_index, handler_index: u32::MAX }` — wiki
/// ADR-022 D3 G9. The postfix `?` operator on a sub-expression.
/// Foundation's catamorphism interprets the `u32::MAX` sentinel as
/// "propagate the failure unchanged through `PipelineFailure`".
Try { body_index: u32 },
/// `Term::Recurse { measure_index, base_index, step_index }` — wiki
/// ADR-022 D3 G7. Bounded recursion guarded by a descent measure.
Recurse {
measure_index: u32,
base_index: u32,
step_index: u32,
},
/// `Term::Unfold { seed_index, step_index }` — wiki ADR-022 D3 G8.
/// Anamorphism step.
Unfold { seed_index: u32, step_index: u32 },
/// `Term::Match { scrutinee_index, arms }` — wiki ADR-022 D3 G6.
/// Arms alternate (pattern, body) per the convention foundation's
/// catamorphism reads to dispatch.
Match {
scrutinee_index: u32,
arms_start: u32,
arms_len: u32,
},
/// Wildcard pattern sentinel — wiki ADR-022 D3 G6 (and G9 default
/// handler). Lowers to `Term::Variable { name_index: u32::MAX }`.
WildcardSentinel,
/// Recurse-placeholder sentinel — wiki ADR-029. Lowers to
/// `Term::Variable { name_index: RECURSE_PLACEHOLDER_NAME_INDEX }`.
/// The catamorphism's Variable handler returns the threaded
/// `recurse_value` (the previous iteration's accumulator) when the
/// name_index matches `pipeline::RECURSE_PLACEHOLDER_NAME_INDEX`.
RecursePlaceholder,
/// Unfold-placeholder sentinel — wiki ADR-029. Lowers to
/// `Term::Variable { name_index: UNFOLD_PLACEHOLDER_NAME_INDEX }`.
/// The catamorphism's Variable handler returns the threaded
/// `unfold_value` (the unfold's current state) when the name_index
/// matches `pipeline::UNFOLD_PLACEHOLDER_NAME_INDEX`. The Term::Unfold
/// fold-rule iterates step with the placeholder bound to the
/// accumulated state until a Kleene fixpoint or
/// `pipeline::UNFOLD_MAX_ITERATIONS` is reached.
UnfoldPlaceholder,
}
/// Per-scope binding table the closure-body parser maintains. Maps a
/// `let`-introduced identifier to the arena index where that binding's
/// value-tree's root lives, so identifier references inside the
/// `let`'s scope resolve to that root. Per wiki ADR-022 D3 G10 the
/// macro builds this incrementally as it descends through `let`
/// statements; the route's input parameter is its own special case
/// (`Term::Variable { name_index: 0 }`) and lives outside this table.
#[derive(Default, Clone)]
struct BindingScope {
bindings: Vec<(Ident, usize)>,
/// ADR-033 G20: the route input type, threaded through the closure-
/// body parser so field-access expressions can synthesize const-eval
/// lookups against `<RouteInputTy as PartitionProductFields>::FIELDS`.
/// Set for `prism_model!` route bodies, `verb!` bodies (since v0.4.9),
/// and `axis!` body clauses (since v0.4.9).
route_input_ty: Option<syn::Type>,
/// ADR-056 scope refinement: the ψ-residuals discipline (rejection of
/// `concat`/`hash`/`first_admit` calls + `Le`/`Lt`/`Ge`/`Gt`
/// binary-op syntax) applies ONLY to the route body's syntactic
/// surface (the `prism_model!`-declared `route` function's closure
/// body). Verb bodies declared via `verb!` and axis impl bodies
/// declared via `axis!`'s `body = …;` clause are unrestricted within
/// the substrate vocabulary per ADR-024 + ADR-055; they may use the
/// full `PrimitiveOp` catalog (including `Concat`, `Le`, `Lt`, `Ge`,
/// `Gt`), `Term::FirstAdmit`, and `Term::AxisInvocation`.
///
/// `true` only for `prism_model!`'s route body; `false` for `verb!`
/// bodies and `axis!` body clauses (and the default).
in_route_body: bool,
}
impl BindingScope {
fn lookup(&self, ident: &Ident) -> Option<usize> {
// Iterate in reverse so inner shadowing (G10 forbids it but the
// lookup works either way) finds the latest declaration.
self.bindings
.iter()
.rev()
.find(|(name, _)| name == ident)
.map(|(_, idx)| *idx)
}
fn shadow_check(&self, ident: &Ident) -> Result<()> {
if self.bindings.iter().any(|(name, _)| name == ident) {
return Err(syn::Error::new(
ident.span(),
format!(
"closure violation: shadowing `{ident}` (ADR-022 D3 G10 forbids declaring two `let`s with the same identifier in the same scope)"
),
));
}
Ok(())
}
fn push(&mut self, ident: Ident, root_idx: usize) {
self.bindings.push((ident, root_idx));
}
}
/// Recursively walk a Rust expression and append the terms that compute
/// it to `arena`, returning the index where this expression's *root*
/// term lands. `route_input` is the name of the route's bound input
/// parameter (mapped to `Term::Variable { name_index: 0 }`); `scope`
/// carries `let`-introduced bindings (G10) the parser has accumulated.
fn emit_term_for_expr(
expr: &syn::Expr,
route_input: &Ident,
arena: &mut Vec<TermSpec>,
scope: &mut BindingScope,
) -> Result<usize> {
match expr {
syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Int(int_lit), .. }) => {
let value: u64 = int_lit.base10_parse().map_err(|e| {
syn::Error::new(int_lit.span(), format!("integer literal out of u64 range: {e}"))
})?;
let idx = arena.len();
arena.push(TermSpec::Literal(value));
Ok(idx)
}
syn::Expr::Path(path_expr) if path_expr.path.get_ident() == Some(route_input) => {
let idx = arena.len();
arena.push(TermSpec::Variable);
Ok(idx)
}
syn::Expr::Path(path_expr) => {
// ADR-022 D3 G10: a bare identifier may be a `let`-introduced
// binding from the surrounding scope. The macro splices the
// binding's value-tree root by emitting a duplicate path that
// shares the same arena root index — semantically identical
// because Term values are content-determined.
if let Some(name) = path_expr.path.get_ident() {
if let Some(root) = scope.lookup(name) {
return Ok(root);
}
}
Err(syn::Error::new_spanned(
path_expr,
"closure violation: identifier is not a foundation-vocabulary name (only the route's `input` parameter, `let`-introduced bindings, and reserved macro-vocabulary identifiers are recognised)",
))
}
syn::Expr::Call(call_expr) => emit_term_for_call(call_expr, route_input, arena, scope),
// ADR-013/TR-08 substrate amendment: byte-level comparison operators
// <= < >= > == != lower to Term::Application(Le/Lt/Ge/Gt/Eq/Ne, [lhs, rhs]).
syn::Expr::Binary(bin_expr) => emit_term_for_binary(bin_expr, route_input, arena, scope),
syn::Expr::Block(block_expr) => emit_term_for_block(&block_expr.block, route_input, arena, scope),
syn::Expr::Paren(paren_expr) => {
emit_term_for_expr(&paren_expr.expr, route_input, arena, scope)
}
// ADR-022 D3 G9: postfix `?` operator. Emits Term::Try with the
// default-propagation handler (`u32::MAX`) — the catamorphism
// propagates the body's failure unchanged through PipelineFailure.
syn::Expr::Try(try_expr) => {
let body_root = emit_term_for_expr(&try_expr.expr, route_input, arena, scope)?;
let idx = arena.len();
arena.push(TermSpec::Try { body_index: body_root as u32 });
Ok(idx)
}
// ADR-022 D3 G6: `match <scrutinee> { <pat> => <arm>, …, _ => <default> }`.
syn::Expr::Match(match_expr) => emit_term_for_match(match_expr, route_input, arena, scope),
// ADR-033 G20: field-access projection over a partition_product
// input. `<expr>.<index>` (positional) or `<expr>.<field_name>`
// (named, requires partition_product! to use the named-field
// form). Lowers to `Term::ProjectField` whose offset/length are
// const-eval lookups against `<SourceTy as PartitionProductFields>::FIELDS`.
syn::Expr::Field(field_expr) => emit_term_for_field(field_expr, route_input, arena, scope),
other => Err(syn::Error::new_spanned(
other,
"closure violation: expression form is not in foundation vocabulary (recognised forms: integer literals, the route's `input` parameter, `let`-introduced bindings, postfix `?`, `match`, field access on partition_product inputs, and macro-vocabulary function calls — PrimitiveOps, hash, lift, project, recurse, unfold, plus implementation verbs)",
)),
}
}
/// ADR-033 G20: emit `Term::ProjectField` for a `<expr>.<member>` form.
/// `<member>` is either a positional index (numeric) or a field name.
/// The byte_offset and byte_length are emitted as const-eval token
/// streams against `<SourceTy as PartitionProductFields>::FIELDS`. For
/// chained access (e.g. `input.outer.inner`), each `.<member>` emits one
/// `Term::ProjectField` whose `source_index` is the prior projection's
/// arena root, and whose static source type is resolved through
/// `<PrevTy as PartitionProductFactor<I>>::Factor` (per ADR-033 G4).
///
/// Source-type resolution proceeds as follows:
/// - if the receiver is the route input ident, the source type is the
/// route input type (read from `scope.route_input_ty`);
/// - if the receiver is a chained `<expr>.<member>` field-access, the
/// source type is `<PrevTy as PartitionProductFactor<INDEX>>::Factor`
/// where `INDEX` is the const-eval index of the prior member (literal
/// for positional, `field_index_by_name(...)` for named);
/// - if the receiver is anything else (let-binding, etc.), we cannot
/// determine the source type at proc-macro time and reject.
fn emit_term_for_field(
field_expr: &syn::ExprField,
route_input: &Ident,
arena: &mut Vec<TermSpec>,
scope: &mut BindingScope,
) -> Result<usize> {
// Emit the source expression first; capture its arena root.
let source_root = emit_term_for_expr(&field_expr.base, route_input, arena, scope)?;
// Determine the source's static type for the FIELDS lookup.
let source_ty: syn::Type = resolve_field_receiver_type(&field_expr.base, route_input, scope)?;
// Resolve the member to a const-eval index expression — either a
// literal index (G20 positional) or a name lookup against FIELD_NAMES
// (G20 named).
let index_expr = field_index_expr(&field_expr.member, &source_ty);
let offset_expr = quote::quote! {
<#source_ty as ::uor_foundation::pipeline::PartitionProductFields>::FIELDS[#index_expr].0
};
let length_expr = quote::quote! {
<#source_ty as ::uor_foundation::pipeline::PartitionProductFields>::FIELDS[#index_expr].1
};
let idx = arena.len();
arena.push(TermSpec::ProjectField {
source_index: source_root as u32,
byte_offset: offset_expr,
byte_length: length_expr,
});
Ok(idx)
}
/// ADR-033 G4 helper: given a field-access member (`Unnamed(i)` or
/// `Named(name)`), produce the const-eval token stream that evaluates to
/// the factor index in the source type's `PartitionProductFields::FIELDS`
/// directory. For positional access this is a literal; for named it is a
/// call to `field_index_by_name(<name>)` on the source type.
fn field_index_expr(member: &syn::Member, source_ty: &syn::Type) -> proc_macro2::TokenStream {
match member {
syn::Member::Unnamed(idx) => {
let i = idx.index as usize;
quote::quote! { #i }
}
syn::Member::Named(name) => {
let name_lit = name.to_string();
// ADR-033 G3/G4: invoke the free `const fn`
// `field_index_by_name_in` against the source's FIELD_NAMES
// (stable Rust 1.83 substitute for a const trait method).
quote::quote! {
::uor_foundation::pipeline::field_index_by_name_in(
<#source_ty as ::uor_foundation::pipeline::PartitionProductFields>::FIELD_NAMES,
#name_lit,
)
}
}
}
}
/// ADR-033 G4 helper: resolve the static type of a chained-field-access
/// receiver. For the route-input base case the type comes from the
/// closure scope. For each chained step `<inner>.<member>` the type is
/// `<InnerTy as PartitionProductFactor<INDEX>>::Factor`. INDEX is the
/// const-eval expression returned by [`field_index_expr`].
fn resolve_field_receiver_type(
base: &syn::Expr,
route_input: &Ident,
scope: &BindingScope,
) -> Result<syn::Type> {
match base {
syn::Expr::Path(path_expr) if path_expr.path.get_ident() == Some(route_input) => {
match &scope.route_input_ty {
Some(ty) => Ok(ty.clone()),
None => Err(syn::Error::new_spanned(
base,
"closure violation: ADR-033 G20 field access requires the route input type to be known (only `prism_model!` and macros that pin `route_input_ty` admit field-access expressions)",
)),
}
}
syn::Expr::Paren(paren_expr) => {
resolve_field_receiver_type(&paren_expr.expr, route_input, scope)
}
syn::Expr::Field(inner) => {
// Recursively resolve the inner receiver's type, then descend
// through `<InnerTy as PartitionProductFactor<INDEX>>::Factor`.
let inner_ty = resolve_field_receiver_type(&inner.base, route_input, scope)?;
let inner_index = field_index_expr(&inner.member, &inner_ty);
// Synthesize the qualified path
// <#inner_ty as PartitionProductFactor<{#inner_index}>>::Factor
// as a syn::Type. We stitch it together via parse_quote!.
let synth: syn::Type = syn::parse_quote! {
<#inner_ty as ::uor_foundation::pipeline::PartitionProductFactor<{#inner_index}>>::Factor
};
Ok(synth)
}
other => Err(syn::Error::new_spanned(
other,
"closure violation: ADR-033 G20 field access receiver must be the route's `input` parameter or another field-access (let-binding receivers are not supported)",
)),
}
}
/// Handle `match <scrutinee> { <lit_pat> => <body>, …, _ => <default> }`
/// per wiki ADR-022 D3 G6. Each arm's pattern is an atomic term
/// (Literal or WildcardSentinel); each arm's body is an arbitrary
/// expression whose sub-tree lives in the arena. The wiki specifies the
/// arms span as a contiguous block of `2 * num_arms` terms alternating
/// (pattern, body); the body in that span is a *copy of the body's root
/// term* so the catamorphism's evaluator can dispatch by reading
/// `arena[start + 2k]` (pattern) and `arena[start + 2k + 1]` (body
/// root). The body's sub-tree lives at lower indices.
fn emit_term_for_match(
match_expr: &syn::ExprMatch,
route_input: &Ident,
arena: &mut Vec<TermSpec>,
scope: &mut BindingScope,
) -> Result<usize> {
let scrutinee_root = emit_term_for_expr(&match_expr.expr, route_input, arena, scope)?;
if match_expr.arms.is_empty() {
return Err(syn::Error::new_spanned(
match_expr,
"closure violation: `match` (G6) must have at least one arm; non-exhaustive matches are closure violations",
));
}
let last_arm = &match_expr.arms[match_expr.arms.len() - 1];
let last_is_wildcard = matches!(last_arm.pat, syn::Pat::Wild(_));
if !last_is_wildcard {
return Err(syn::Error::new_spanned(
&last_arm.pat,
"closure violation: `match` (G6) MUST end with a wildcard arm `_ => <default>`; non-exhaustive matches are closure violations",
));
}
// First pass: emit each arm's body sub-tree, recording the pattern
// spec and body-root arena index. The pattern is atomic so we
// construct the spec inline rather than reserving an arena slot.
let mut arm_pairs: Vec<(TermSpec, usize)> = Vec::with_capacity(match_expr.arms.len());
for arm in &match_expr.arms {
if arm.guard.is_some() {
return Err(syn::Error::new_spanned(
arm,
"closure violation: match arm guards are not in the closure-body grammar (G6)",
));
}
let pattern_spec = match &arm.pat {
syn::Pat::Lit(lit_pat) => {
if let syn::Lit::Int(int_lit) = &lit_pat.lit {
let value: u64 = int_lit.base10_parse().map_err(|e| {
syn::Error::new(
int_lit.span(),
format!("integer literal out of u64 range: {e}"),
)
})?;
TermSpec::Literal(value)
} else {
return Err(syn::Error::new_spanned(
lit_pat,
"closure violation: match patterns must be integer literals or `_` (G6)",
));
}
}
syn::Pat::Wild(_) => TermSpec::WildcardSentinel,
other => {
return Err(syn::Error::new_spanned(
other,
"closure violation: match patterns must be integer literals or `_` (G6)",
));
}
};
let body_root = emit_term_for_expr(&arm.body, route_input, arena, scope)?;
arm_pairs.push((pattern_spec, body_root));
}
// Second pass: emit the contiguous arms span with alternating
// (pattern, body_root_copy). The body_root_copy duplicates the
// TermSpec at the body's root so the arms span is exactly
// `2 * num_arms` terms — the layout the catamorphism's evaluator
// expects per ADR-029's `Term::Match` fold rule.
let arms_start = arena.len();
for (pattern_spec, body_root_idx) in arm_pairs {
arena.push(pattern_spec);
let body_copy = clone_term_spec(&arena[body_root_idx]);
arena.push(body_copy);
}
let arms_len = arena.len() - arms_start;
let idx = arena.len();
arena.push(TermSpec::Match {
scrutinee_index: scrutinee_root as u32,
arms_start: arms_start as u32,
arms_len: arms_len as u32,
});
Ok(idx)
}
/// Build the closure-violation error for a ψ-residual op emission per
/// wiki ADR-035. The error spans the offending syntactic form and
/// names the ψ-residual category + the architectural reason +
/// the canonical alternative (ψ-chain composition).
fn reject_psi_residual_op<E: quote::ToTokens>(
expr: &E,
op_syntax: &str,
op_name: &str,
) -> Result<usize> {
let message = format!(
"ψ-residual violation (wiki ADR-035): byte-comparison `{op_syntax}` \
(`PrimitiveOp::{op_name}`) is excluded from verb-body composition. \
The canonical compiled form is structural — admission is a property \
of the value's k-invariant signature, not a comparison predicate. \
Express the admission relation through the ψ-chain (G21..G29) \
instead: e.g. `k_invariants(homotopy_groups(postnikov_tower(nerve(input))))` \
produces the κ-label that classifies the input's homotopy type."
);
Err(syn::Error::new_spanned(expr, message))
}
/// Build the closure-violation error for a ψ-residual call form.
fn reject_psi_residual_call<E: quote::ToTokens>(
expr: &E,
form: &str,
term_variant: &str,
rationale: &str,
) -> Result<usize> {
let message = format!(
"ψ-residual violation (wiki ADR-035): `{form}` lowers to `Term::{term_variant}` \
and is excluded from verb-body composition. {rationale}"
);
Err(syn::Error::new_spanned(expr, message))
}
/// Map a binary operator expression to a `Term::Application` with the
/// corresponding `PrimitiveOp` discriminant. Wiki ADR-013/TR-08 substrate
/// amendment: foundation extends `PrimitiveOp` with `Le`, `Lt`, `Ge`,
/// `Gt` (byte-level comparison) — those discriminants remain in the
/// substrate for non-verb-body contexts but are rejected here per
/// ADR-035's ψ-residuals discipline.
fn emit_term_for_binary(
expr: &syn::ExprBinary,
route_input: &Ident,
arena: &mut Vec<TermSpec>,
scope: &mut BindingScope,
) -> Result<usize> {
let operator = match expr.op {
// ADR-035 ψ-residuals discipline scoped per ADR-056: byte-comparison
// PrimitiveOps (Le, Lt, Ge, Gt) are ψ-enumeration residuals of
// search-based admission predicates and excluded from the route
// body's syntactic surface. Per ADR-056 the rejection applies ONLY
// to `prism_model!` route bodies (`in_route_body == true`); verb!
// bodies and axis! body clauses may use the full substrate
// vocabulary including these comparisons (SHA padding length
// comparison, tensor saturation clamp bounds, etc.).
syn::BinOp::Le(_) if scope.in_route_body => {
return reject_psi_residual_op(expr, "<=", "Le")
}
syn::BinOp::Lt(_) if scope.in_route_body => return reject_psi_residual_op(expr, "<", "Lt"),
syn::BinOp::Ge(_) if scope.in_route_body => {
return reject_psi_residual_op(expr, ">=", "Ge")
}
syn::BinOp::Gt(_) if scope.in_route_body => return reject_psi_residual_op(expr, ">", "Gt"),
syn::BinOp::Le(_) => quote! { ::uor_foundation::PrimitiveOp::Le },
syn::BinOp::Lt(_) => quote! { ::uor_foundation::PrimitiveOp::Lt },
syn::BinOp::Ge(_) => quote! { ::uor_foundation::PrimitiveOp::Ge },
syn::BinOp::Gt(_) => quote! { ::uor_foundation::PrimitiveOp::Gt },
syn::BinOp::Add(_) => quote! { ::uor_foundation::PrimitiveOp::Add },
syn::BinOp::Sub(_) => quote! { ::uor_foundation::PrimitiveOp::Sub },
syn::BinOp::Mul(_) => quote! { ::uor_foundation::PrimitiveOp::Mul },
syn::BinOp::BitXor(_) => quote! { ::uor_foundation::PrimitiveOp::Xor },
syn::BinOp::BitAnd(_) => quote! { ::uor_foundation::PrimitiveOp::And },
syn::BinOp::BitOr(_) => quote! { ::uor_foundation::PrimitiveOp::Or },
_ => {
return Err(syn::Error::new_spanned(
expr,
"closure violation: binary operator is not in the closure-body grammar; recognised operators are arithmetic (+, -, *) and bitwise (^, &, |). Byte-level comparison (<=, <, >=, >) is admissible in verb bodies and axis impl bodies per ADR-056; it is excluded only from the route body's syntactic surface (per ADR-035/ADR-056).",
));
}
};
let lhs_root = emit_term_for_expr(&expr.left, route_input, arena, scope)?;
let rhs_root = emit_term_for_expr(&expr.right, route_input, arena, scope)?;
let already_contiguous = rhs_root == lhs_root + 1;
let (args_start, args_len) = if already_contiguous {
(lhs_root as u32, 2u32)
} else {
let start = arena.len();
let lhs_dup = clone_term_spec(&arena[lhs_root]);
arena.push(lhs_dup);
let rhs_dup = clone_term_spec(&arena[rhs_root]);
arena.push(rhs_dup);
(start as u32, 2u32)
};
let idx = arena.len();
arena.push(TermSpec::Application {
operator,
args_start,
args_len,
});
Ok(idx)
}
/// Duplicate a `TermSpec`. Used when emitting `match` arm-spans where
/// the body's root term must be copied into the arms range alongside
/// its pattern.
fn clone_term_spec(spec: &TermSpec) -> TermSpec {
match spec {
TermSpec::Literal(v) => TermSpec::Literal(*v),
TermSpec::Variable => TermSpec::Variable,
TermSpec::Application {
operator,
args_start,
args_len,
} => TermSpec::Application {
operator: operator.clone(),
args_start: *args_start,
args_len: *args_len,
},
TermSpec::AxisInvocation {
axis_index,
kernel_id,
input_index,
} => TermSpec::AxisInvocation {
axis_index: *axis_index,
kernel_id: *kernel_id,
input_index: *input_index,
},
TermSpec::ProjectField {
source_index,
byte_offset,
byte_length,
} => TermSpec::ProjectField {
source_index: *source_index,
byte_offset: byte_offset.clone(),
byte_length: byte_length.clone(),
},
TermSpec::LiteralExpr { value, level } => TermSpec::LiteralExpr {
value: value.clone(),
level: level.clone(),
},
TermSpec::LiteralBytesExpr { bytes, level } => TermSpec::LiteralBytesExpr {
bytes: bytes.clone(),
level: level.clone(),
},
TermSpec::VerbSplice {
arg_root_idx,
fragment_path,
} => TermSpec::VerbSplice {
arg_root_idx: *arg_root_idx,
fragment_path: fragment_path.clone(),
},
TermSpec::Lift {
operand_index,
target_witt,
} => TermSpec::Lift {
operand_index: *operand_index,
target_witt: target_witt.clone(),
},
TermSpec::Project {
operand_index,
target_witt,
} => TermSpec::Project {
operand_index: *operand_index,
target_witt: target_witt.clone(),
},
TermSpec::Try { body_index } => TermSpec::Try {
body_index: *body_index,
},
TermSpec::Recurse {
measure_index,
base_index,
step_index,
} => TermSpec::Recurse {
measure_index: *measure_index,
base_index: *base_index,
step_index: *step_index,
},
TermSpec::Unfold {
seed_index,
step_index,
} => TermSpec::Unfold {
seed_index: *seed_index,
step_index: *step_index,
},
TermSpec::Match {
scrutinee_index,
arms_start,
arms_len,
} => TermSpec::Match {
scrutinee_index: *scrutinee_index,
arms_start: *arms_start,
arms_len: *arms_len,
},
TermSpec::WildcardSentinel => TermSpec::WildcardSentinel,
TermSpec::RecursePlaceholder => TermSpec::RecursePlaceholder,
TermSpec::UnfoldPlaceholder => TermSpec::UnfoldPlaceholder,
TermSpec::FirstAdmit {
domain_size_index,
predicate_index,
} => TermSpec::FirstAdmit {
domain_size_index: *domain_size_index,
predicate_index: *predicate_index,
},
TermSpec::FirstAdmitIdxPlaceholder => TermSpec::FirstAdmitIdxPlaceholder,
TermSpec::RecurseIdxPlaceholder => TermSpec::RecurseIdxPlaceholder,
TermSpec::Nerve { value_index } => TermSpec::Nerve {
value_index: *value_index,
},
TermSpec::ChainComplex { simplicial_index } => TermSpec::ChainComplex {
simplicial_index: *simplicial_index,
},
TermSpec::HomologyGroups { chain_index } => TermSpec::HomologyGroups {
chain_index: *chain_index,
},
TermSpec::Betti { homology_index } => TermSpec::Betti {
homology_index: *homology_index,
},
TermSpec::CochainComplex { chain_index } => TermSpec::CochainComplex {
chain_index: *chain_index,
},
TermSpec::CohomologyGroups { cochain_index } => TermSpec::CohomologyGroups {
cochain_index: *cochain_index,
},
TermSpec::PostnikovTower { simplicial_index } => TermSpec::PostnikovTower {
simplicial_index: *simplicial_index,
},
TermSpec::HomotopyGroups { postnikov_index } => TermSpec::HomotopyGroups {
postnikov_index: *postnikov_index,
},
TermSpec::KInvariants { homotopy_index } => TermSpec::KInvariants {
homotopy_index: *homotopy_index,
},
}
}
/// Handle a `{ <stmts>; <tail_expr> }` block — wiki ADR-022 D3 G10 + G11.
/// `let` statements bind identifiers to the `let`'s value-tree root; the
/// final expression is the block's value.
fn emit_term_for_block(
block: &syn::Block,
route_input: &Ident,
arena: &mut Vec<TermSpec>,
scope: &mut BindingScope,
) -> Result<usize> {
if block.stmts.is_empty() {
return Err(syn::Error::new_spanned(
block,
"closure violation: block expressions must contain at least one statement (G11) — empty blocks are unreachable in the closure-body grammar",
));
}
let mut local_scope = scope.clone();
let last = block.stmts.len() - 1;
for (i, stmt) in block.stmts.iter().enumerate() {
match stmt {
syn::Stmt::Local(local) => {
if i == last {
return Err(syn::Error::new_spanned(
stmt,
"closure violation: block must end with an expression statement (G11), not a `let` binding",
));
}
let ident = match &local.pat {
syn::Pat::Ident(pat_ident) => {
if pat_ident.by_ref.is_some() || pat_ident.mutability.is_some() {
return Err(syn::Error::new_spanned(
pat_ident,
"closure violation: `let` binding patterns must be plain identifiers (no `ref`, no `mut`) per ADR-022 D3 G10",
));
}
if pat_ident.subpat.is_some() {
return Err(syn::Error::new_spanned(
pat_ident,
"closure violation: `let` binding patterns must be plain identifiers per ADR-022 D3 G10",
));
}
pat_ident.ident.clone()
}
other => {
return Err(syn::Error::new_spanned(
other,
"closure violation: `let` binding patterns must be plain identifiers per ADR-022 D3 G10",
));
}
};
local_scope.shadow_check(&ident)?;
let init = local.init.as_ref().ok_or_else(|| {
syn::Error::new_spanned(
local,
"closure violation: `let` bindings must have an initializer (`let <name> = <expr>;`)",
)
})?;
if init.diverge.is_some() {
return Err(syn::Error::new_spanned(
local,
"closure violation: `let ... else` is not in the closure-body grammar (G10)",
));
}
let value_root =
emit_term_for_expr(&init.expr, route_input, arena, &mut local_scope)?;
local_scope.push(ident, value_root);
}
syn::Stmt::Expr(inner, semi) => {
if i == last {
if semi.is_some() {
return Err(syn::Error::new_spanned(
stmt,
"closure violation: block must end with a tail expression (G11), no trailing `;`",
));
}
return emit_term_for_expr(inner, route_input, arena, &mut local_scope);
}
return Err(syn::Error::new_spanned(
stmt,
"closure violation: only `let` statements may precede the block's tail expression (G10/G11)",
));
}
other => {
return Err(syn::Error::new_spanned(
other,
"closure violation: block statement is not in the closure-body grammar (G10/G11 admits only `let` and a final expression)",
));
}
}
}
// Unreachable in well-typed flow — the loop always returns or errors.
Err(syn::Error::new_spanned(
block,
"closure violation: block lacks a tail expression (G11)",
))
}
/// Map a function-call expression to a `Term::Application` (G3),
/// `Term::Lift` (G4), `Term::Project` (G5), `Term::AxisInvocation`
/// (G19, ADR-030 — replaces the legacy `HasherProjection`),
/// `Term::Recurse` (G7), `Term::Unfold` (G8), or — for
/// non-reserved identifiers — a `TermSpec::VerbSplice` that the
/// `prism_model!` const-fn arena builder inlines at compile time per
/// ADR-024. Rejects anything else as a closure violation.
fn emit_term_for_call(
call: &syn::ExprCall,
route_input: &Ident,
arena: &mut Vec<TermSpec>,
scope: &mut BindingScope,
) -> Result<usize> {
// ADR-022 D3 G4 / G5: `lift::<W{n}>(operand)` and `project::<W{n}>(operand)`
// — the call target is a path with a generic Witt-level argument.
if let syn::Expr::Path(path_expr) = call.func.as_ref() {
let segments = &path_expr.path.segments;
if segments.len() == 1 {
let segment = &segments[0];
let last_ident = &segment.ident;
if last_ident == "lift" || last_ident == "project" {
let target_witt = match &segment.arguments {
syn::PathArguments::AngleBracketed(args) if args.args.len() == 1 => {
match &args.args[0] {
syn::GenericArgument::Type(syn::Type::Path(tp)) => tp.path.clone(),
other => {
return Err(syn::Error::new_spanned(
other,
"closure violation: lift/project's generic argument must be a Witt-level type (e.g., `WittLevel::W32`)",
));
}
}
}
_ => {
return Err(syn::Error::new_spanned(
segment,
format!(
"closure violation: `{last_ident}` requires a generic Witt-level argument: `{last_ident}::<WittLevel::W{{n}}>(operand)`"
),
));
}
};
if call.args.len() != 1 {
return Err(syn::Error::new(
last_ident.span(),
format!(
"closure violation: `{last_ident}` (G4/G5) expects 1 argument, got {}",
call.args.len()
),
));
}
let operand_root = emit_term_for_expr(&call.args[0], route_input, arena, scope)?;
let target_witt_ts = quote! { #target_witt };
let idx = arena.len();
let spec = if last_ident == "lift" {
TermSpec::Lift {
operand_index: operand_root as u32,
target_witt: target_witt_ts,
}
} else {
TermSpec::Project {
operand_index: operand_root as u32,
target_witt: target_witt_ts,
}
};
arena.push(spec);
return Ok(idx);
}
}
}
// All other call shapes require a bare identifier callee.
let func_ident = match call.func.as_ref() {
syn::Expr::Path(p) => p.path.get_ident().cloned().ok_or_else(|| {
syn::Error::new_spanned(
&call.func,
"closure violation: call target must be a bare identifier matching a PrimitiveOp name, the `hash` verb form, or a declared verb identifier",
)
})?,
other => {
return Err(syn::Error::new_spanned(
other,
"closure violation: call target must be a bare identifier",
));
}
};
// ADR-024 verb invocation: any non-reserved, non-PrimitiveOp
// identifier in call position is treated as a verb call. The macro
// records a `TermSpec::VerbSplice` referencing `VERB_TERMS_<NAME>`;
// when the route emits its arena, `render_const_fn_arena_builder`
// inlines the verb's fragment at compile time via foundation's
// `inline_verb_fragment` const-fn helper. Rust's name resolution
// surfaces "cannot find value" at the verb-call span if the
// referenced const isn't in scope.
// ADR-053: `mod` is a Rust keyword so closure-body authors write
// `r#mod(a, b)`; `syn::Ident::to_string()` on a raw ident includes
// the `r#` prefix, so we normalize before matching.
let unraw_name = func_ident.unraw().to_string();
let verb_resolution = match unraw_name.as_str() {
// Exclude all reserved + PrimitiveOp identifiers from verb
// resolution; these have dedicated handling below.
"add" | "sub" | "mul" | "xor" | "and" | "or" | "neg" | "bnot" | "succ" | "pred"
// ADR-053: Div/Mod/Pow ring-axis completion + Concat byte-packing.
| "div" | "mod" | "pow"
| "hash" | "parallel" | "fold_n" | "tree_fold" | "first_admit"
| "recurse" | "unfold" | "concat"
// ADR-051: wide-value literal carriers (Dependency 2).
| "literal_u64" | "literal_bytes"
// ADR-035 G21..G29 ψ-chain identifiers.
| "nerve" | "chain_complex" | "homology_groups" | "betti" | "cochain_complex"
| "cohomology_groups" | "postnikov_tower" | "homotopy_groups" | "k_invariants" => false,
_ => true,
};
if verb_resolution {
if call.args.len() != 1 {
return Err(syn::Error::new(
func_ident.span(),
format!(
"verb invocation `{}` expects 1 argument (the verb's input value), got {}",
func_ident,
call.args.len()
),
));
}
let arg_root = emit_term_for_expr(&call.args[0], route_input, arena, scope)?;
let const_name = Ident::new(
&format!("VERB_TERMS_{}", to_screaming_snake(&func_ident.to_string())),
func_ident.span(),
);
let fragment_path = quote! { #const_name };
let idx = arena.len();
arena.push(TermSpec::VerbSplice {
arg_root_idx: arg_root as u32,
fragment_path,
});
return Ok(idx);
}
// ADR-026 G14: `fold_n(n, init, |state, idx| step)`. Lowers to an
// unrolled `Term::Application`-style chain when `n` is a const
// literal at or below `pipeline::FOLD_UNROLL_THRESHOLD`; lowers to
// `Term::Recurse` otherwise.
if func_ident == "fold_n" {
if call.args.len() != 3 {
return Err(syn::Error::new(
func_ident.span(),
format!(
"closure violation: `fold_n` (G14) expects 3 arguments (count, init, step closure), got {}",
call.args.len()
),
));
}
// The count must be a const expression. The macro recognises
// const integer literals (the unroll path) and any other
// expression (the Term::Recurse path, with the count's tree as
// the descent measure).
let count_lit: Option<u64> = match &call.args[0] {
syn::Expr::Lit(syn::ExprLit {
lit: syn::Lit::Int(int_lit),
..
}) => int_lit.base10_parse::<u64>().ok(),
_ => None,
};
let init_root = emit_term_for_expr(&call.args[1], route_input, arena, scope)?;
let step_closure = match &call.args[2] {
syn::Expr::Closure(c) => c,
other => {
return Err(syn::Error::new_spanned(
other,
"closure violation: `fold_n`'s third argument must be a closure `|state, idx| <step_expr>` (G14)",
));
}
};
if step_closure.inputs.len() != 2 {
return Err(syn::Error::new_spanned(
step_closure,
"closure violation: `fold_n`'s step closure expects exactly 2 parameters (state, idx) per G14",
));
}
let state_ident = match &step_closure.inputs[0] {
syn::Pat::Ident(p) => p.ident.clone(),
other => {
return Err(syn::Error::new_spanned(
other,
"closure violation: `fold_n`'s state parameter must be a plain identifier (G14)",
));
}
};
let idx_ident = match &step_closure.inputs[1] {
syn::Pat::Ident(p) => p.ident.clone(),
other => {
return Err(syn::Error::new_spanned(
other,
"closure violation: `fold_n`'s idx parameter must be a plain identifier (G14)",
));
}
};
// Unroll path: const literal at or below threshold.
const FOLD_UNROLL_THRESHOLD: u64 = 8;
if let Some(n) = count_lit {
if n <= FOLD_UNROLL_THRESHOLD {
let mut state_root = init_root;
for i in 0..n {
let idx_root = arena.len();
arena.push(TermSpec::Literal(i));
let mut iter_scope = scope.clone();
iter_scope.shadow_check(&state_ident)?;
iter_scope.shadow_check(&idx_ident)?;
iter_scope.push(state_ident.clone(), state_root);
iter_scope.push(idx_ident.clone(), idx_root);
state_root = emit_term_for_expr(
&step_closure.body,
route_input,
arena,
&mut iter_scope,
)?;
}
return Ok(state_root);
}
}
// Recurse path: count is parametric or exceeds the threshold.
// Lower to Term::Recurse with the count's tree as descent measure,
// init as base, and the step body as the step subtree per
// ADR-029. State binds to the RecursePlaceholder Variable so the
// catamorphism's recurse_value threading resolves it.
let measure_root = emit_term_for_expr(&call.args[0], route_input, arena, scope)?;
let mut step_scope = scope.clone();
step_scope.shadow_check(&state_ident)?;
step_scope.shadow_check(&idx_ident)?;
let placeholder_idx = arena.len();
arena.push(TermSpec::RecursePlaceholder);
step_scope.push(state_ident, placeholder_idx);
step_scope.push(idx_ident, measure_root);
let step_root =
emit_term_for_expr(&step_closure.body, route_input, arena, &mut step_scope)?;
let idx = arena.len();
arena.push(TermSpec::Recurse {
measure_index: measure_root as u32,
base_index: init_root as u32,
step_index: step_root as u32,
});
return Ok(idx);
}
// ADR-022 D3 G7: `recurse(measure, base, |self_ident| step)`.
if func_ident == "recurse" {
if call.args.len() != 3 {
return Err(syn::Error::new(
func_ident.span(),
format!(
"closure violation: `recurse` (G7) expects 3 arguments (measure, base, step closure), got {}",
call.args.len()
),
));
}
let measure_root = emit_term_for_expr(&call.args[0], route_input, arena, scope)?;
let base_root = emit_term_for_expr(&call.args[1], route_input, arena, scope)?;
// Third arg is a closure `|self_ident| step`.
let step_closure = match &call.args[2] {
syn::Expr::Closure(c) => c,
other => {
return Err(syn::Error::new_spanned(
other,
"closure violation: `recurse`'s third argument must be a closure `|self_ident| <step_expr>` (G7)",
));
}
};
// ADR-022 D3 G7 + ADR-034 Mechanism 1: the step closure admits
// either 1 parameter (`|self_ident|`, the recursive-call
// placeholder) or 2 parameters (`|self_ident, idx_ident|`, the
// recursive-call placeholder + the iteration counter).
if step_closure.inputs.is_empty() || step_closure.inputs.len() > 2 {
return Err(syn::Error::new_spanned(
step_closure,
"closure violation: `recurse`'s step closure expects 1 parameter (`|self_ident| <step>` per G7) or 2 parameters (`|self_ident, idx_ident| <step>` per ADR-034 Mechanism 1)",
));
}
let self_ident = match &step_closure.inputs[0] {
syn::Pat::Ident(p) => p.ident.clone(),
other => {
return Err(syn::Error::new_spanned(
other,
"closure violation: `recurse`'s step parameter must be a plain identifier (G7)",
));
}
};
let idx_ident_opt: Option<Ident> = if step_closure.inputs.len() == 2 {
match &step_closure.inputs[1] {
syn::Pat::Ident(p) => Some(p.ident.clone()),
other => {
return Err(syn::Error::new_spanned(
other,
"closure violation: `recurse`'s iteration-counter parameter must be a plain identifier (ADR-034 Mechanism 1)",
));
}
}
} else {
None
};
// Wiki ADR-029: emit a `Term::Variable { name_index =
// RECURSE_PLACEHOLDER_NAME_INDEX }` BEFORE the step body and
// bind `self_ident` to that Variable's arena index. ADR-034 M1:
// when the two-parameter form is used, also emit a
// `Term::Variable { name_index = RECURSE_IDX_NAME_INDEX }`
// placeholder and bind `idx_ident` to it.
let mut step_scope = scope.clone();
step_scope.shadow_check(&self_ident)?;
let self_placeholder_idx = arena.len();
arena.push(TermSpec::RecursePlaceholder);
step_scope.push(self_ident, self_placeholder_idx);
if let Some(idx_ident) = idx_ident_opt {
step_scope.shadow_check(&idx_ident)?;
let idx_placeholder_idx = arena.len();
arena.push(TermSpec::RecurseIdxPlaceholder);
step_scope.push(idx_ident, idx_placeholder_idx);
}
let step_root =
emit_term_for_expr(&step_closure.body, route_input, arena, &mut step_scope)?;
let idx = arena.len();
arena.push(TermSpec::Recurse {
measure_index: measure_root as u32,
base_index: base_root as u32,
step_index: step_root as u32,
});
return Ok(idx);
}
// ADR-022 D3 G8: `unfold(seed, |state_ident| step)`.
if func_ident == "unfold" {
if call.args.len() != 2 {
return Err(syn::Error::new(
func_ident.span(),
format!(
"closure violation: `unfold` (G8) expects 2 arguments (seed, step closure), got {}",
call.args.len()
),
));
}
let seed_root = emit_term_for_expr(&call.args[0], route_input, arena, scope)?;
let step_closure = match &call.args[1] {
syn::Expr::Closure(c) => c,
other => {
return Err(syn::Error::new_spanned(
other,
"closure violation: `unfold`'s second argument must be a closure `|state_ident| <step_expr>` (G8)",
));
}
};
if step_closure.inputs.len() != 1 {
return Err(syn::Error::new_spanned(
step_closure,
"closure violation: `unfold`'s step closure expects exactly 1 parameter (the state placeholder, G8)",
));
}
let state_ident = match &step_closure.inputs[0] {
syn::Pat::Ident(p) => p.ident.clone(),
other => {
return Err(syn::Error::new_spanned(
other,
"closure violation: `unfold`'s step parameter must be a plain identifier (G8)",
));
}
};
// ADR-029 anamorphism: emit a `Variable { name_index =
// UNFOLD_PLACEHOLDER_NAME_INDEX }` BEFORE the step body and bind
// state_ident to that placeholder's arena index, so any reference
// to state_ident inside step lowers to the placeholder Variable.
// The catamorphism's Term::Unfold fold-rule iterates step with
// the placeholder bound to the current accumulated state until a
// Kleene fixpoint or UNFOLD_MAX_ITERATIONS.
let mut step_scope = scope.clone();
step_scope.shadow_check(&state_ident)?;
let placeholder_idx = arena.len();
arena.push(TermSpec::UnfoldPlaceholder);
step_scope.push(state_ident, placeholder_idx);
let step_root =
emit_term_for_expr(&step_closure.body, route_input, arena, &mut step_scope)?;
let idx = arena.len();
arena.push(TermSpec::Unfold {
seed_index: seed_root as u32,
step_index: step_root as u32,
});
return Ok(idx);
}
// ADR-026 G13: `parallel(f, g)` produces the parallel-composed
// route. The result's term tree is the partition-product of f's
// and g's term trees: each operand's subtree is emitted, and the
// composite is realised as a binary `Term::Application` whose
// operator is the structural-combine `Or` (the foundation-default
// partition-product byte combiner per the ten-Term-variant
// commitment of ADR-029; implementations override the runtime per
// ADR-024's three-way split if they need parallel-execution
// semantics). The macro recognises `parallel(f, g)` so the verb-
// closure check + the operator set's closure both hold.
if func_ident == "parallel" {
if call.args.len() != 2 {
return Err(syn::Error::new(
func_ident.span(),
format!(
"closure violation: `parallel` (G13) expects 2 routes (left, right), got {}",
call.args.len()
),
));
}
let lhs_root = emit_term_for_expr(&call.args[0], route_input, arena, scope)?;
let rhs_root = emit_term_for_expr(&call.args[1], route_input, arena, scope)?;
// The args block must be contiguous in the arena per ADR-022 D2.
// Build a contiguous duplicate block at the end if the operands
// aren't already adjacent.
let already_contiguous = rhs_root == lhs_root + 1;
let (args_start, args_len) = if already_contiguous {
(lhs_root as u32, 2u32)
} else {
let start = arena.len();
let lhs_dup = clone_term_spec(&arena[lhs_root]);
arena.push(lhs_dup);
let rhs_dup = clone_term_spec(&arena[rhs_root]);
arena.push(rhs_dup);
(start as u32, 2u32)
};
let idx = arena.len();
arena.push(TermSpec::Application {
operator: quote! { ::uor_foundation::PrimitiveOp::Or },
args_start,
args_len,
});
return Ok(idx);
}
// ADR-026 G15: `tree_fold(reducer, [a, b, c, …])` lowers to a
// pairwise reduction chain — at each level, the reducer is applied
// to adjacent operand pairs, halving the count. For a power-of-two
// count `n`, the output is a balanced tree of depth `log2(n)`. For
// odd levels, the unpaired leaf is carried forward. The reducer is
// a binary identifier (PrimitiveOp or verb).
if func_ident == "tree_fold" {
if call.args.len() != 2 {
return Err(syn::Error::new(
func_ident.span(),
format!(
"closure violation: `tree_fold` (G15) expects 2 arguments (reducer, leaves array), got {}",
call.args.len()
),
));
}
// The reducer is an identifier (PrimitiveOp like `add` or a verb).
let reducer_ident = match &call.args[0] {
syn::Expr::Path(p) => p.path.get_ident().cloned().ok_or_else(|| {
syn::Error::new_spanned(
&call.args[0],
"closure violation: `tree_fold`'s reducer must be a bare identifier (PrimitiveOp or verb)",
)
})?,
other => {
return Err(syn::Error::new_spanned(
other,
"closure violation: `tree_fold`'s reducer must be a bare identifier",
));
}
};
// The leaves are an array literal `[expr, expr, …]`.
let leaves_array = match &call.args[1] {
syn::Expr::Array(a) => a,
other => {
return Err(syn::Error::new_spanned(
other,
"closure violation: `tree_fold`'s leaves must be an array literal `[a, b, c, …]`",
));
}
};
if leaves_array.elems.is_empty() {
return Err(syn::Error::new_spanned(
leaves_array,
"closure violation: `tree_fold`'s leaves array must be non-empty (G15)",
));
}
// Emit each leaf's subtree, recording its root index.
let mut current_level: Vec<usize> = Vec::with_capacity(leaves_array.elems.len());
for leaf_expr in &leaves_array.elems {
current_level.push(emit_term_for_expr(leaf_expr, route_input, arena, scope)?);
}
// The reducer is rendered via emit_term_for_call's path (via a
// synthesized two-arg call) so the same identifier-resolution
// applies (PrimitiveOp / verb / closure violation).
let reducer_op_or_verb = match reducer_ident.unraw().to_string().as_str() {
"add" => Some(quote! { ::uor_foundation::PrimitiveOp::Add }),
"sub" => Some(quote! { ::uor_foundation::PrimitiveOp::Sub }),
"mul" => Some(quote! { ::uor_foundation::PrimitiveOp::Mul }),
"xor" => Some(quote! { ::uor_foundation::PrimitiveOp::Xor }),
"and" => Some(quote! { ::uor_foundation::PrimitiveOp::And }),
"or" => Some(quote! { ::uor_foundation::PrimitiveOp::Or }),
// ADR-053 ring-axis completion as tree_fold reducers.
"div" => Some(quote! { ::uor_foundation::PrimitiveOp::Div }),
"mod" => Some(quote! { ::uor_foundation::PrimitiveOp::Mod }),
"pow" => Some(quote! { ::uor_foundation::PrimitiveOp::Pow }),
_ => None,
};
// Pairwise reduction: at each level, fold adjacent pairs.
while current_level.len() > 1 {
let mut next_level: Vec<usize> = Vec::with_capacity(current_level.len().div_ceil(2));
let mut i = 0;
while i + 1 < current_level.len() {
let l_idx = current_level[i];
let r_idx = current_level[i + 1];
// Build the reducer application; args must be contiguous.
let already_contiguous = r_idx == l_idx + 1;
let (args_start, args_len) = if already_contiguous {
(l_idx as u32, 2u32)
} else {
let start = arena.len();
let l_dup = clone_term_spec(&arena[l_idx]);
arena.push(l_dup);
let r_dup = clone_term_spec(&arena[r_idx]);
arena.push(r_dup);
(start as u32, 2u32)
};
let app_idx = arena.len();
if let Some(op) = &reducer_op_or_verb {
arena.push(TermSpec::Application {
operator: op.clone(),
args_start,
args_len,
});
} else {
// Verb-style reducer: emit a VerbSplice. The verb's
// term-tree fragment will be inlined at compile time.
// The verb call takes the LEFT operand as its arg per
// ADR-024's substitution semantics; the right operand
// is fed via a wrapping Application (Or as combine).
// For tree_fold over verbs, the verb must be unary; if
// used here as binary, we wrap via Or.
let const_name = Ident::new(
&format!(
"VERB_TERMS_{}",
to_screaming_snake(&reducer_ident.to_string())
),
reducer_ident.span(),
);
let fragment_path = quote! { #const_name };
arena.push(TermSpec::VerbSplice {
arg_root_idx: l_idx as u32,
fragment_path,
});
let _ = (args_start, args_len, r_idx);
}
next_level.push(app_idx);
i += 2;
}
// Carry an unpaired final leaf to the next level.
if i < current_level.len() {
next_level.push(current_level[i]);
}
current_level = next_level;
}
return Ok(current_level[0]);
}
// ADR-051 wide-Witt literal embedding (Dependency 2 in v0.4.10):
// `literal_u64(<value>, <level>)` lowers to `TermSpec::LiteralExpr`
// which renders to a const-evaluated `pipeline::literal_u64(...)`
// call producing a `Term::Literal { value: TermValue, level }` at
// the consumer's compile time. The u64 form is sufficient for
// widths up to W64; the level argument controls the byte-width of
// the resulting TermValue.
if unraw_name == "literal_u64" {
if call.args.len() != 2 {
return Err(syn::Error::new(
func_ident.span(),
format!(
"`literal_u64(<value>, <level>)` expects 2 arguments, got {}",
call.args.len()
),
));
}
let value_tokens = quote::ToTokens::to_token_stream(&call.args[0]);
let level_tokens = quote::ToTokens::to_token_stream(&call.args[1]);
let idx = arena.len();
arena.push(TermSpec::LiteralExpr {
value: value_tokens,
level: level_tokens,
});
return Ok(idx);
}
// ADR-051 wide-Witt literal embedding (Dependency 2 in v0.4.10):
// `literal_bytes(<bytes>, <level>)` lowers to `TermSpec::LiteralBytesExpr`
// which renders to a const-evaluated `pipeline::literal_bytes(...)`
// call producing a `Term::Literal { value: TermValue, level }` whose
// TermValue carrier holds the full byte sequence. Required for wide
// Witt-level literals (W128+) that don't fit in a u64 — secp256k1
// P_LITERAL (W256), AES round constants (W128), FHE plaintext-
// coefficient tables, etc.
if unraw_name == "literal_bytes" {
if call.args.len() != 2 {
return Err(syn::Error::new(
func_ident.span(),
format!(
"`literal_bytes(<bytes>, <level>)` expects 2 arguments, got {}",
call.args.len()
),
));
}
let bytes_tokens = quote::ToTokens::to_token_stream(&call.args[0]);
let level_tokens = quote::ToTokens::to_token_stream(&call.args[1]);
let idx = arena.len();
arena.push(TermSpec::LiteralBytesExpr {
bytes: bytes_tokens,
level: level_tokens,
});
return Ok(idx);
}
// ADR-035 ψ-residuals discipline scoped per ADR-056: `first_admit`
// lowers to `Term::FirstAdmit` — ψ-enumeration over a counter domain.
// Per ADR-056 the rejection applies only when the syntactic emission
// is in the route body (`in_route_body == true`); verb! bodies and
// axis! body clauses may use `first_admit` for bounded search per
// ADR-034 (its canonical use site).
if func_ident == "first_admit" && scope.in_route_body {
return reject_psi_residual_call(
call,
"first_admit(<domain>, |idx| <pred>)",
"FirstAdmit",
"The canonical compiled form is structural — admission is a \
property of the value's k-invariant signature, not a search \
predicate enumerated over a counter domain. Express the \
admission relation through the ψ-chain (G21..G29): \
e.g. `k_invariants(homotopy_groups(postnikov_tower(nerve(input))))` \
produces the κ-label that classifies the input's homotopy type. \
Per ADR-056 this restriction applies only to the route body's \
syntactic surface; verb and axis impl bodies admit `first_admit` \
directly.",
);
}
// ADR-056: `concat` is admissible in verb! / axis! bodies per the
// ADR-035 scope refinement. In route bodies (in_route_body == true),
// the rejection remains — admission predicates may not depend on
// byte-level concatenation. In verb / axis body contexts, concat
// emits `Term::Application { operator: PrimitiveOp::Concat, … }`
// and is the canonical realization of SHA padding, HMAC composition,
// Merkle tree internal-node combination, etc.
if func_ident == "concat" {
if scope.in_route_body {
return reject_psi_residual_call(
call,
"concat(<lhs>, <rhs>)",
"Application { operator: PrimitiveOp::Concat }",
"The canonical compiled form is structural — admission is a \
property of the value's k-invariant signature, not a \
byte-shape predicate. If byte-concatenation is the input's \
structural decomposition, use `partition_product!` to \
declare the typed shape and `Term::ProjectField` (G20) to \
extract sub-byte ranges; pipe each component through the \
ψ-chain instead of byte-manipulating before admission. \
Per ADR-056 this restriction applies only to the route \
body's syntactic surface; verb and axis impl bodies admit \
`concat` directly.",
);
}
// Verb / axis body: emit `Term::Application { operator: Concat }`.
if call.args.len() != 2 {
return Err(syn::Error::new(
func_ident.span(),
format!(
"PrimitiveOp `concat` expects 2 arguments (lhs, rhs), got {}",
call.args.len()
),
));
}
let lhs_root = emit_term_for_expr(&call.args[0], route_input, arena, scope)?;
let rhs_root = emit_term_for_expr(&call.args[1], route_input, arena, scope)?;
let already_contiguous = rhs_root == lhs_root + 1;
let (args_start, args_len) = if already_contiguous {
(lhs_root as u32, 2u32)
} else {
let start = arena.len();
let lhs_dup = clone_term_spec(&arena[lhs_root]);
arena.push(lhs_dup);
let rhs_dup = clone_term_spec(&arena[rhs_root]);
arena.push(rhs_dup);
(start as u32, 2u32)
};
let idx = arena.len();
arena.push(TermSpec::Application {
operator: quote! { ::uor_foundation::PrimitiveOp::Concat },
args_start,
args_len,
});
return Ok(idx);
}
// ADR-056: `hash(input)` lowers to `Term::AxisInvocation` (axis 0 =
// canonical hash axis, kernel 0 = `fold_bytes` ∘ `finalize`). In
// route bodies it's rejected (the route's surface composes ψ-chain
// forms, not axis dispatch). In verb / axis bodies it's admissible
// — canonical hash invocations are exactly how SHA, BLAKE3, etc.
// expose themselves to compound operations like HMAC and Merkle.
if func_ident == "hash" {
if scope.in_route_body {
return reject_psi_residual_call(
call,
"hash(<value>)",
"AxisInvocation",
"The canonical hash axis is consumed by resolvers and verb \
bodies, not directly by the route body (ADR-036 + ADR-056). \
Move the `hash(...)` call into a `NerveResolver` (or other \
resolver-trait impl) where the per-value content fingerprint \
is computed as part of the resolver's internal resolution \
semantics — or into a verb body, which admits `hash(...)` \
freely per ADR-056. The route body composes ψ-chain forms \
(G21..G29) over the input's structural decomposition.",
);
}
// Verb / axis body: emit `Term::AxisInvocation { axis 0, kernel 0 }`.
if call.args.len() != 1 {
return Err(syn::Error::new(
func_ident.span(),
format!(
"`hash(<value>)` expects 1 argument, got {}",
call.args.len()
),
));
}
let value_root = emit_term_for_expr(&call.args[0], route_input, arena, scope)?;
let idx = arena.len();
arena.push(TermSpec::AxisInvocation {
axis_index: 0,
kernel_id: 0,
input_index: value_root as u32,
});
return Ok(idx);
}
// Wiki ADR-035 G21..G29: closure-body grammar identifiers for the
// nine ψ-chain Term variants. Each takes a single operand whose
// arena root becomes the corresponding `*_index` field. The
// receiver-shape check (wiki ADR-035: G22 takes simplicial-complex,
// G23/G25 take chain-complex, G24 takes homology-groups, G26 takes
// cochain-complex, G27 takes simplicial-complex, G28 takes
// Postnikov-tower, G29 takes homotopy-groups; G21 takes byte) is
// enforced at proc-macro expansion by walking the operand TermSpec
// and asserting its produced shape matches.
let psi_chain: &[(&str, &str, PsiShape)] = &[
("nerve", "G21", PsiShape::Byte),
("chain_complex", "G22", PsiShape::SimplicialComplex),
("homology_groups", "G23", PsiShape::ChainComplex),
("betti", "G24", PsiShape::HomologyGroups),
("cochain_complex", "G25", PsiShape::ChainComplex),
("cohomology_groups", "G26", PsiShape::CochainComplex),
("postnikov_tower", "G27", PsiShape::SimplicialComplex),
("homotopy_groups", "G28", PsiShape::PostnikovTower),
("k_invariants", "G29", PsiShape::HomotopyGroups),
];
for (name, grammar, expected_shape) in psi_chain {
if func_ident == name {
if call.args.len() != 1 {
return Err(syn::Error::new(
func_ident.span(),
format!(
"closure violation: `{name}` (ADR-035 {grammar}) expects 1 argument, got {}",
call.args.len()
),
));
}
let operand_root = emit_term_for_expr(&call.args[0], route_input, arena, scope)?;
let operand_shape = term_spec_shape(&arena[operand_root]);
if !psi_shape_compatible(*expected_shape, operand_shape) {
return Err(syn::Error::new_spanned(
&call.args[0],
format!(
"receiver-shape violation (wiki ADR-035 {grammar}): `{name}` expects \
a {expected} receiver, but the operand produces a {actual} value. \
The ψ-chain stages compose along the ontology's identity maps \
(ψ_1 → ψ_2 → … → ψ_9); receiver-shape mismatches break the \
canonical compiled form's structural-witness chain.",
expected = expected_shape.describe(),
actual = operand_shape.describe(),
),
));
}
let idx = arena.len();
let spec = match *name {
"nerve" => TermSpec::Nerve {
value_index: operand_root as u32,
},
"chain_complex" => TermSpec::ChainComplex {
simplicial_index: operand_root as u32,
},
"homology_groups" => TermSpec::HomologyGroups {
chain_index: operand_root as u32,
},
"betti" => TermSpec::Betti {
homology_index: operand_root as u32,
},
"cochain_complex" => TermSpec::CochainComplex {
chain_index: operand_root as u32,
},
"cohomology_groups" => TermSpec::CohomologyGroups {
cochain_index: operand_root as u32,
},
"postnikov_tower" => TermSpec::PostnikovTower {
simplicial_index: operand_root as u32,
},
"homotopy_groups" => TermSpec::HomotopyGroups {
postnikov_index: operand_root as u32,
},
"k_invariants" => TermSpec::KInvariants {
homotopy_index: operand_root as u32,
},
_ => unreachable!(),
};
arena.push(spec);
return Ok(idx);
}
}
let (operator, expected_arity) = match func_ident.unraw().to_string().as_str() {
"add" => (quote! { ::uor_foundation::PrimitiveOp::Add }, 2usize),
"sub" => (quote! { ::uor_foundation::PrimitiveOp::Sub }, 2),
"mul" => (quote! { ::uor_foundation::PrimitiveOp::Mul }, 2),
"xor" => (quote! { ::uor_foundation::PrimitiveOp::Xor }, 2),
"and" => (quote! { ::uor_foundation::PrimitiveOp::And }, 2),
"or" => (quote! { ::uor_foundation::PrimitiveOp::Or }, 2),
"neg" => (quote! { ::uor_foundation::PrimitiveOp::Neg }, 1),
"bnot" => (quote! { ::uor_foundation::PrimitiveOp::Bnot }, 1),
"succ" => (quote! { ::uor_foundation::PrimitiveOp::Succ }, 1),
"pred" => (quote! { ::uor_foundation::PrimitiveOp::Pred }, 1),
// ADR-053 ring-axis completion: Div/Mod/Pow as substrate primitives.
// ADR-054 cites these in canonical body composition examples
// (rotr decomposition, pad-and-finalize via Concat). Per ADR-053's
// catalog the runtime catamorphism evaluates them as
// folding-transformations over Z/(2^n)Z.
//
// Note: `mod` is a Rust keyword, so closure-body authors invoke it as
// a raw identifier `r#mod(a, b)`; `Ident::unraw().to_string()`
// returns "mod" which the arm matches.
"div" => (quote! { ::uor_foundation::PrimitiveOp::Div }, 2),
"mod" => (quote! { ::uor_foundation::PrimitiveOp::Mod }, 2),
"pow" => (quote! { ::uor_foundation::PrimitiveOp::Pow }, 2),
// ADR-026 reserved macro-vocabulary identifiers (G13–G18). The
// closure-body lowering for these forms is specified
// architecturally; the substrate-level macro recognises them so
// they never fall through to the closure-violation branch as
// unknown identifiers, but the structural lowering is owned by
// the implementation (per ADR-024's three-way responsibility split
// between substrate, prism, and implementation). Implementations
// that need these forms supply their own SDK macros that desugar
// into the substrate primitives; the substrate macro reserves the
// identifiers so they cannot be re-used as `verb!` names.
"partition_product" | "partition_coproduct" => {
return Err(syn::Error::new(
func_ident.span(),
format!(
"closure violation: `{}` (ADR-026 G17/G18) is a type-level shape constructor — invoke it at item position via the named SDK form `partition_product!(<Name>, <A>, <B>)` or `partition_coproduct!(<Name>, <A>, <B>)`, then reference `<Name>` in `type Input` / `type Output`",
func_ident
),
));
}
other => {
return Err(syn::Error::new(
func_ident.span(),
format!(
"closure violation: `{other}` is not a foundation PrimitiveOp (recognised: add, sub, mul, div, r#mod, pow, xor, and, or, neg, bnot, succ, pred, concat), nor an ADR-026 macro-vocabulary identifier (hash/parallel/fold_n/tree_fold/first_admit/recurse/unfold), nor a declared verb"
),
));
}
};
if call.args.len() != expected_arity {
return Err(syn::Error::new(
func_ident.span(),
format!(
"PrimitiveOp `{}` expects {} argument(s), got {}",
func_ident,
expected_arity,
call.args.len()
),
));
}
// Emit each arg's subtree and record its root index.
let mut arg_root_indices: Vec<usize> = Vec::with_capacity(call.args.len());
for arg in call.args.iter() {
arg_root_indices.push(emit_term_for_expr(arg, route_input, arena, scope)?);
}
// ADR-022 D2: the args block must be CONTIGUOUS in the arena. If
// the arg roots already are (the common case for leaf args or for
// the canonical post-order layout), use them directly. Otherwise
// duplicate each arg's root term into a fresh contiguous block —
// a duplicate carries the same `Term` value (same operator + same
// args.start), so it is semantically identical.
let already_contiguous = arg_root_indices.windows(2).all(|w| w[1] == w[0] + 1);
let (args_start, args_len) = if already_contiguous && !arg_root_indices.is_empty() {
let len = arg_root_indices.len();
let start = arg_root_indices[0];
(start as u32, len as u32)
} else {
// Build a contiguous duplicate block at the end of the arena.
let start = arena.len();
for &idx in &arg_root_indices {
// Clone the spec at idx into a new slot. Since TermSpec is
// not Clone, hand-build a fresh entry referring to the same
// contents. (Operators are token streams; clone via .clone()
// on the field.)
let dup = match &arena[idx] {
TermSpec::Literal(v) => TermSpec::Literal(*v),
TermSpec::Variable => TermSpec::Variable,
TermSpec::Application {
operator,
args_start,
args_len,
} => TermSpec::Application {
operator: operator.clone(),
args_start: *args_start,
args_len: *args_len,
},
TermSpec::AxisInvocation {
axis_index,
kernel_id,
input_index,
} => TermSpec::AxisInvocation {
axis_index: *axis_index,
kernel_id: *kernel_id,
input_index: *input_index,
},
TermSpec::ProjectField {
source_index,
byte_offset,
byte_length,
} => TermSpec::ProjectField {
source_index: *source_index,
byte_offset: byte_offset.clone(),
byte_length: byte_length.clone(),
},
TermSpec::LiteralExpr { value, level } => TermSpec::LiteralExpr {
value: value.clone(),
level: level.clone(),
},
TermSpec::LiteralBytesExpr { bytes, level } => TermSpec::LiteralBytesExpr {
bytes: bytes.clone(),
level: level.clone(),
},
TermSpec::VerbSplice {
arg_root_idx,
fragment_path,
} => TermSpec::VerbSplice {
arg_root_idx: *arg_root_idx,
fragment_path: fragment_path.clone(),
},
TermSpec::Lift {
operand_index,
target_witt,
} => TermSpec::Lift {
operand_index: *operand_index,
target_witt: target_witt.clone(),
},
TermSpec::Project {
operand_index,
target_witt,
} => TermSpec::Project {
operand_index: *operand_index,
target_witt: target_witt.clone(),
},
TermSpec::Try { body_index } => TermSpec::Try {
body_index: *body_index,
},
TermSpec::Recurse {
measure_index,
base_index,
step_index,
} => TermSpec::Recurse {
measure_index: *measure_index,
base_index: *base_index,
step_index: *step_index,
},
TermSpec::Unfold {
seed_index,
step_index,
} => TermSpec::Unfold {
seed_index: *seed_index,
step_index: *step_index,
},
TermSpec::Match {
scrutinee_index,
arms_start,
arms_len,
} => TermSpec::Match {
scrutinee_index: *scrutinee_index,
arms_start: *arms_start,
arms_len: *arms_len,
},
TermSpec::WildcardSentinel => TermSpec::WildcardSentinel,
TermSpec::RecursePlaceholder => TermSpec::RecursePlaceholder,
TermSpec::UnfoldPlaceholder => TermSpec::UnfoldPlaceholder,
TermSpec::FirstAdmit {
domain_size_index,
predicate_index,
} => TermSpec::FirstAdmit {
domain_size_index: *domain_size_index,
predicate_index: *predicate_index,
},
TermSpec::FirstAdmitIdxPlaceholder => TermSpec::FirstAdmitIdxPlaceholder,
TermSpec::RecurseIdxPlaceholder => TermSpec::RecurseIdxPlaceholder,
TermSpec::Nerve { value_index } => TermSpec::Nerve {
value_index: *value_index,
},
TermSpec::ChainComplex { simplicial_index } => TermSpec::ChainComplex {
simplicial_index: *simplicial_index,
},
TermSpec::HomologyGroups { chain_index } => TermSpec::HomologyGroups {
chain_index: *chain_index,
},
TermSpec::Betti { homology_index } => TermSpec::Betti {
homology_index: *homology_index,
},
TermSpec::CochainComplex { chain_index } => TermSpec::CochainComplex {
chain_index: *chain_index,
},
TermSpec::CohomologyGroups { cochain_index } => TermSpec::CohomologyGroups {
cochain_index: *cochain_index,
},
TermSpec::PostnikovTower { simplicial_index } => TermSpec::PostnikovTower {
simplicial_index: *simplicial_index,
},
TermSpec::HomotopyGroups { postnikov_index } => TermSpec::HomotopyGroups {
postnikov_index: *postnikov_index,
},
TermSpec::KInvariants { homotopy_index } => TermSpec::KInvariants {
homotopy_index: *homotopy_index,
},
};
arena.push(dup);
}
(start as u32, arg_root_indices.len() as u32)
};
let app_idx = arena.len();
arena.push(TermSpec::Application {
operator,
args_start,
args_len,
});
Ok(app_idx)
}
/// Emit the macro-time-built term arena as a sequence of `Term::*`
/// constructor expressions, ready to splice into a `&'static [Term]`
/// const-array literal.
fn render_arena(arena: &[TermSpec]) -> Vec<proc_macro2::TokenStream> {
arena
.iter()
.map(|spec| match spec {
TermSpec::Literal(value) => quote! {
::uor_foundation::pipeline::literal_u64(
#value,
::uor_foundation::WittLevel::W8,
)
},
TermSpec::LiteralExpr { value, level } => quote! {
::uor_foundation::pipeline::literal_u64(
#value,
#level,
)
},
TermSpec::LiteralBytesExpr { bytes, level } => quote! {
::uor_foundation::pipeline::literal_bytes(
#bytes,
#level,
)
},
TermSpec::Variable => quote! {
::uor_foundation::enforcement::Term::Variable { name_index: 0u32 }
},
TermSpec::Application {
operator,
args_start,
args_len,
} => {
let s = *args_start;
let l = *args_len;
quote! {
::uor_foundation::enforcement::Term::Application {
operator: #operator,
args: ::uor_foundation::enforcement::TermList {
start: #s,
len: #l,
},
}
}
}
TermSpec::AxisInvocation {
axis_index,
kernel_id,
input_index,
} => {
let a = *axis_index;
let k = *kernel_id;
let i = *input_index;
quote! {
::uor_foundation::enforcement::Term::AxisInvocation {
axis_index: #a,
kernel_id: #k,
input_index: #i,
}
}
}
TermSpec::ProjectField {
source_index,
byte_offset,
byte_length,
} => {
let s = *source_index;
quote! {
::uor_foundation::enforcement::Term::ProjectField {
source_index: #s,
byte_offset: (#byte_offset) as u32,
byte_length: (#byte_length) as u32,
}
}
}
TermSpec::VerbSplice { .. } => {
// VerbSplice never reaches the slice-literal renderer:
// when an arena contains a VerbSplice the caller falls
// back to `render_const_fn_arena_builder` which inlines
// the verb fragment via foundation's const-fn helper
// `inline_verb_fragment` at const-eval time per
// ADR-024. Reaching this branch indicates a logic bug
// in the macro's emission selection.
quote! {
compile_error!(
"internal error: VerbSplice reached the slice-literal renderer; \
render_const_fn_arena_builder should have been chosen"
)
}
}
TermSpec::Lift {
operand_index,
target_witt,
} => {
let i = *operand_index;
quote! {
::uor_foundation::enforcement::Term::Lift {
operand_index: #i,
target: #target_witt,
}
}
}
TermSpec::Project {
operand_index,
target_witt,
} => {
let i = *operand_index;
quote! {
::uor_foundation::enforcement::Term::Project {
operand_index: #i,
target: #target_witt,
}
}
}
TermSpec::Try { body_index } => {
let i = *body_index;
quote! {
::uor_foundation::enforcement::Term::Try {
body_index: #i,
handler_index: u32::MAX,
}
}
}
TermSpec::Recurse {
measure_index,
base_index,
step_index,
} => {
let m = *measure_index;
let b = *base_index;
let s = *step_index;
quote! {
::uor_foundation::enforcement::Term::Recurse {
measure_index: #m,
base_index: #b,
step_index: #s,
}
}
}
TermSpec::Unfold {
seed_index,
step_index,
} => {
let s = *seed_index;
let st = *step_index;
quote! {
::uor_foundation::enforcement::Term::Unfold {
seed_index: #s,
step_index: #st,
}
}
}
TermSpec::Match {
scrutinee_index,
arms_start,
arms_len,
} => {
let s = *scrutinee_index;
let st = *arms_start;
let l = *arms_len;
quote! {
::uor_foundation::enforcement::Term::Match {
scrutinee_index: #s,
arms: ::uor_foundation::enforcement::TermList {
start: #st,
len: #l,
},
}
}
}
TermSpec::WildcardSentinel => quote! {
::uor_foundation::enforcement::Term::Variable {
name_index: u32::MAX,
}
},
TermSpec::RecursePlaceholder => quote! {
::uor_foundation::enforcement::Term::Variable {
name_index: ::uor_foundation::pipeline::RECURSE_PLACEHOLDER_NAME_INDEX,
}
},
TermSpec::UnfoldPlaceholder => quote! {
::uor_foundation::enforcement::Term::Variable {
name_index: ::uor_foundation::pipeline::UNFOLD_PLACEHOLDER_NAME_INDEX,
}
},
TermSpec::FirstAdmit {
domain_size_index,
predicate_index,
} => {
let d = *domain_size_index;
let p = *predicate_index;
quote! {
::uor_foundation::enforcement::Term::FirstAdmit {
domain_size_index: #d,
predicate_index: #p,
}
}
}
TermSpec::FirstAdmitIdxPlaceholder => quote! {
::uor_foundation::enforcement::Term::Variable {
name_index: ::uor_foundation::pipeline::FIRST_ADMIT_IDX_NAME_INDEX,
}
},
TermSpec::RecurseIdxPlaceholder => quote! {
::uor_foundation::enforcement::Term::Variable {
name_index: ::uor_foundation::pipeline::RECURSE_IDX_NAME_INDEX,
}
},
TermSpec::Nerve { value_index } => {
let v = *value_index;
quote! {
::uor_foundation::enforcement::Term::Nerve { value_index: #v }
}
}
TermSpec::ChainComplex { simplicial_index } => {
let s = *simplicial_index;
quote! {
::uor_foundation::enforcement::Term::ChainComplex { simplicial_index: #s }
}
}
TermSpec::HomologyGroups { chain_index } => {
let c = *chain_index;
quote! {
::uor_foundation::enforcement::Term::HomologyGroups { chain_index: #c }
}
}
TermSpec::Betti { homology_index } => {
let h = *homology_index;
quote! {
::uor_foundation::enforcement::Term::Betti { homology_index: #h }
}
}
TermSpec::CochainComplex { chain_index } => {
let c = *chain_index;
quote! {
::uor_foundation::enforcement::Term::CochainComplex { chain_index: #c }
}
}
TermSpec::CohomologyGroups { cochain_index } => {
let c = *cochain_index;
quote! {
::uor_foundation::enforcement::Term::CohomologyGroups { cochain_index: #c }
}
}
TermSpec::PostnikovTower { simplicial_index } => {
let s = *simplicial_index;
quote! {
::uor_foundation::enforcement::Term::PostnikovTower { simplicial_index: #s }
}
}
TermSpec::HomotopyGroups { postnikov_index } => {
let p = *postnikov_index;
quote! {
::uor_foundation::enforcement::Term::HomotopyGroups { postnikov_index: #p }
}
}
TermSpec::KInvariants { homotopy_index } => {
let h = *homotopy_index;
quote! {
::uor_foundation::enforcement::Term::KInvariants { homotopy_index: #h }
}
}
})
.collect()
}
/// Render a single non-VerbSplice TermSpec as a `Term::*` constructor
/// expression that uses the dynamic `len` variable for index fields
/// when those fields reference the spec at the given TermSpec index.
/// `spec_pos[i]` is the TokenStream for spec `i`'s result-position
/// const-let (e.g., `pos_3` for atomic specs, `len - 1` for verb
/// splices' last term).
fn render_atomic_term_in_builder(
spec: &TermSpec,
spec_pos: &[proc_macro2::TokenStream],
) -> proc_macro2::TokenStream {
let pos_at = |idx: u32| -> proc_macro2::TokenStream {
let i = idx as usize;
if i < spec_pos.len() {
spec_pos[i].clone()
} else {
// Out-of-bounds index — emit u32::MAX so const-eval surfaces a
// recognizable arena-bounds error.
quote! { u32::MAX }
}
};
match spec {
TermSpec::Literal(value) => {
let v = *value;
quote! {
::uor_foundation::pipeline::literal_u64(
#v,
::uor_foundation::WittLevel::W8,
)
}
}
TermSpec::LiteralExpr { value, level } => quote! {
::uor_foundation::pipeline::literal_u64(
#value,
#level,
)
},
TermSpec::LiteralBytesExpr { bytes, level } => quote! {
::uor_foundation::pipeline::literal_bytes(
#bytes,
#level,
)
},
TermSpec::Variable => quote! {
::uor_foundation::enforcement::Term::Variable { name_index: 0u32 }
},
TermSpec::Application {
operator,
args_start,
args_len,
} => {
let s = pos_at(*args_start);
let l = *args_len;
quote! {
::uor_foundation::enforcement::Term::Application {
operator: #operator,
args: ::uor_foundation::enforcement::TermList {
start: (#s) as u32,
len: #l,
},
}
}
}
TermSpec::AxisInvocation {
axis_index,
kernel_id,
input_index,
} => {
let a = *axis_index;
let k = *kernel_id;
let i = pos_at(*input_index);
quote! {
::uor_foundation::enforcement::Term::AxisInvocation {
axis_index: #a,
kernel_id: #k,
input_index: (#i) as u32,
}
}
}
TermSpec::ProjectField {
source_index,
byte_offset,
byte_length,
} => {
let s = pos_at(*source_index);
quote! {
::uor_foundation::enforcement::Term::ProjectField {
source_index: (#s) as u32,
byte_offset: (#byte_offset) as u32,
byte_length: (#byte_length) as u32,
}
}
}
TermSpec::Lift {
operand_index,
target_witt,
} => {
let i = pos_at(*operand_index);
quote! {
::uor_foundation::enforcement::Term::Lift {
operand_index: (#i) as u32,
target: #target_witt,
}
}
}
TermSpec::Project {
operand_index,
target_witt,
} => {
let i = pos_at(*operand_index);
quote! {
::uor_foundation::enforcement::Term::Project {
operand_index: (#i) as u32,
target: #target_witt,
}
}
}
TermSpec::Try { body_index } => {
let i = pos_at(*body_index);
quote! {
::uor_foundation::enforcement::Term::Try {
body_index: (#i) as u32,
handler_index: u32::MAX,
}
}
}
TermSpec::Recurse {
measure_index,
base_index,
step_index,
} => {
let m = pos_at(*measure_index);
let b = pos_at(*base_index);
let s = pos_at(*step_index);
quote! {
::uor_foundation::enforcement::Term::Recurse {
measure_index: (#m) as u32,
base_index: (#b) as u32,
step_index: (#s) as u32,
}
}
}
TermSpec::Unfold {
seed_index,
step_index,
} => {
let s = pos_at(*seed_index);
let st = pos_at(*step_index);
quote! {
::uor_foundation::enforcement::Term::Unfold {
seed_index: (#s) as u32,
step_index: (#st) as u32,
}
}
}
TermSpec::Match {
scrutinee_index,
arms_start,
arms_len,
} => {
let sc = pos_at(*scrutinee_index);
let st = *arms_start;
let l = *arms_len;
// For Match, arms are emitted as a contiguous span at fixed
// positional offsets (the macro emits them sequentially in
// the host arena); arms.start references the first such
// position which lives at the static spec-index `st`.
let st_pos = if (st as usize) < spec_pos.len() {
spec_pos[st as usize].clone()
} else {
quote! { u32::MAX }
};
quote! {
::uor_foundation::enforcement::Term::Match {
scrutinee_index: (#sc) as u32,
arms: ::uor_foundation::enforcement::TermList {
start: (#st_pos) as u32,
len: #l,
},
}
}
}
TermSpec::WildcardSentinel => quote! {
::uor_foundation::enforcement::Term::Variable { name_index: u32::MAX }
},
TermSpec::RecursePlaceholder => quote! {
::uor_foundation::enforcement::Term::Variable {
name_index: ::uor_foundation::pipeline::RECURSE_PLACEHOLDER_NAME_INDEX,
}
},
TermSpec::UnfoldPlaceholder => quote! {
::uor_foundation::enforcement::Term::Variable {
name_index: ::uor_foundation::pipeline::UNFOLD_PLACEHOLDER_NAME_INDEX,
}
},
TermSpec::FirstAdmit {
domain_size_index,
predicate_index,
} => {
let d = pos_at(*domain_size_index);
let p = pos_at(*predicate_index);
quote! {
::uor_foundation::enforcement::Term::FirstAdmit {
domain_size_index: (#d) as u32,
predicate_index: (#p) as u32,
}
}
}
TermSpec::FirstAdmitIdxPlaceholder => quote! {
::uor_foundation::enforcement::Term::Variable {
name_index: ::uor_foundation::pipeline::FIRST_ADMIT_IDX_NAME_INDEX,
}
},
TermSpec::RecurseIdxPlaceholder => quote! {
::uor_foundation::enforcement::Term::Variable {
name_index: ::uor_foundation::pipeline::RECURSE_IDX_NAME_INDEX,
}
},
TermSpec::Nerve { value_index } => {
let v = pos_at(*value_index);
quote! {
::uor_foundation::enforcement::Term::Nerve { value_index: (#v) as u32 }
}
}
TermSpec::ChainComplex { simplicial_index } => {
let s = pos_at(*simplicial_index);
quote! {
::uor_foundation::enforcement::Term::ChainComplex {
simplicial_index: (#s) as u32,
}
}
}
TermSpec::HomologyGroups { chain_index } => {
let c = pos_at(*chain_index);
quote! {
::uor_foundation::enforcement::Term::HomologyGroups {
chain_index: (#c) as u32,
}
}
}
TermSpec::Betti { homology_index } => {
let h = pos_at(*homology_index);
quote! {
::uor_foundation::enforcement::Term::Betti {
homology_index: (#h) as u32,
}
}
}
TermSpec::CochainComplex { chain_index } => {
let c = pos_at(*chain_index);
quote! {
::uor_foundation::enforcement::Term::CochainComplex {
chain_index: (#c) as u32,
}
}
}
TermSpec::CohomologyGroups { cochain_index } => {
let c = pos_at(*cochain_index);
quote! {
::uor_foundation::enforcement::Term::CohomologyGroups {
cochain_index: (#c) as u32,
}
}
}
TermSpec::PostnikovTower { simplicial_index } => {
let s = pos_at(*simplicial_index);
quote! {
::uor_foundation::enforcement::Term::PostnikovTower {
simplicial_index: (#s) as u32,
}
}
}
TermSpec::HomotopyGroups { postnikov_index } => {
let p = pos_at(*postnikov_index);
quote! {
::uor_foundation::enforcement::Term::HomotopyGroups {
postnikov_index: (#p) as u32,
}
}
}
TermSpec::KInvariants { homotopy_index } => {
let h = pos_at(*homotopy_index);
quote! {
::uor_foundation::enforcement::Term::KInvariants {
homotopy_index: (#h) as u32,
}
}
}
TermSpec::VerbSplice { .. } => quote! {
compile_error!("VerbSplice handled separately in render_const_fn_arena_builder")
},
}
}
/// Render the TermSpec arena as a const-fn arena builder when the arena
/// contains verb splices (wiki ADR-024). The builder emits a sequence
/// of statements in a const block that:
///
/// - allocates a fixed-capacity `[Term; CAP]` buffer
/// - emits each TermSpec as either a direct `buf[len] = Term::...; len += 1;`
/// (for atomic specs) or a `inline_verb_fragment` call (for verb splices)
/// - tracks each spec's result position via `pos_<N>` const-let bindings
/// so subsequent specs reference verb-spliced positions correctly
/// - returns `(buf, len)` and exposes `&buf[..len]` as the route's
/// `&'static [Term]` slice
fn render_const_fn_arena_builder(
arena: &[TermSpec],
inline_bytes: &proc_macro2::TokenStream,
) -> proc_macro2::TokenStream {
// Step 1: compute each spec's result-position TokenStream. For
// atomic specs, the position is a fresh `pos_<N>` const-let. For
// VerbSplice specs, the position is `len - 1` evaluated AFTER the
// splice (the last term of the spliced fragment is the verb's
// result root per ADR-024).
let spec_pos: Vec<proc_macro2::TokenStream> = (0..arena.len())
.map(|i| {
let id = Ident::new(&format!("pos_{}", i), proc_macro2::Span::call_site());
quote! { #id }
})
.collect();
// Step 2: emit the build-step statements per spec.
let mut stmts: Vec<proc_macro2::TokenStream> = Vec::with_capacity(arena.len());
for (i, spec) in arena.iter().enumerate() {
let pos_id = &spec_pos[i];
match spec {
TermSpec::VerbSplice {
arg_root_idx,
fragment_path,
} => {
// The caller's argument expression's root position is
// captured in `pos_<arg_root_idx>`. inline_verb_fragment
// substitutes Variable(0) in the verb's body with a copy
// of `buf[arg_pos]` and shifts non-Variable(0) terms by
// the host's current length per ADR-024.
let arg_pos = &spec_pos[*arg_root_idx as usize];
stmts.push(quote! {
let __spliced = ::uor_foundation::enforcement::inline_verb_fragment(
buf,
len,
#fragment_path::<#inline_bytes>(),
(#arg_pos) as u32,
);
buf = __spliced.0;
len = __spliced.1;
let #pos_id: usize = len - 1;
});
}
other => {
let term_expr = render_atomic_term_in_builder(other, &spec_pos);
stmts.push(quote! {
buf[len] = #term_expr;
let #pos_id: usize = len;
len += 1;
});
}
}
}
// Step 3: assemble the const-fn block. Cap the arena at a generous
// foundation default; const-eval will reject overflows.
quote! {
{
const ROUTE_ARENA_CAP: usize = 256;
const fn __build_arena() -> ([::uor_foundation::enforcement::Term<'static, #inline_bytes>; ROUTE_ARENA_CAP], usize) {
let mut buf: [::uor_foundation::enforcement::Term<'static, #inline_bytes>; ROUTE_ARENA_CAP] =
[::uor_foundation::enforcement::Term::Variable { name_index: 0u32 }; ROUTE_ARENA_CAP];
let mut len: usize = 0;
#( #stmts )*
(buf, len)
}
const ROUTE_BUILT: ([::uor_foundation::enforcement::Term<'static, #inline_bytes>; ROUTE_ARENA_CAP], usize) =
__build_arena();
const ROUTE_LEN: usize = ROUTE_BUILT.1;
// Slice the active prefix; const split_at_checked is stable on Rust 1.83.
match ROUTE_BUILT.0.split_at_checked(ROUTE_LEN) {
Some((head, _)) => head,
None => &[],
}
}
}
}
/// `prism_model!` — wiki ADR-020 + ADR-022 D3 closure-bodied form.
///
/// Parses the model declaration (struct, route witness struct, impl block
/// with `Input` / `Output` / `Route` associated types and a closure-bodied
/// `route` function), maps the closure body to a foundation-vocabulary
/// term tree at expansion time, and emits:
///
/// - `pub struct <Model>;` and `pub struct <Route>;` (re-emitted from input)
/// - `const ROUTE_TERMS_<MODEL>: &'static [Term] = &[…];` (the term tree)
/// - `impl __sdk_seal::Sealed for <Model>` and `for <Route>` (D1)
/// - `impl FoundationClosed for <Route> { arena_slice() → ROUTE_TERMS_<MODEL> }` (D5)
/// - `impl PrismModel<H, B, A> for <Model>` with `forward` body delegating
/// to `pipeline::run_route::<H, B, A, Self>(input)` (D4 + D5)
///
/// A function call to a name not in the foundation PrimitiveOp catalogue
/// (add, sub, mul, xor, and, or, neg, bnot, succ, pred) fails to compile,
/// pointing at the offending span — the wiki's closure-violation
/// enforcement (ADR-020).
#[proc_macro]
pub fn prism_model(input: TokenStream) -> TokenStream {
let parsed = parse_macro_input!(input as PrismModelInput);
let PrismModelInput {
model_vis,
model_name,
route_vis,
route_name,
h_ty,
b_ty,
a_ty,
r_ty,
c_ty,
input_ty,
output_ty,
route_input_ident,
route_body,
resolvers_body,
commitment_body,
} = parsed;
// ADR-036 resolver-tuple wiring:
// - When the user names a fourth substrate parameter R, the impl
// binds it explicitly and `forward` constructs an R instance
// either from the optional `fn resolvers() -> R { … }` clause or
// via `<R as Default>::default()` when the clause is omitted.
// - When R is omitted (the 3-position form), R defaults to
// `NullResolverTuple` and `forward` borrows the foundation's
// zero-sized null tuple — RESOLVER_ABSENT propagation per
// ADR-022 D3 G9 for any resolver-bound ψ-Term encountered.
let (resolver_ty_tokens, resolver_construction) = match (&r_ty, &resolvers_body) {
(Some(r), Some(block)) => (quote! { #r }, quote! { #block }),
(Some(r), None) => (
quote! { #r },
quote! { <#r as ::core::default::Default>::default() },
),
(None, _) => (
quote! { ::uor_foundation::pipeline::NullResolverTuple },
quote! { ::uor_foundation::pipeline::NullResolverTuple },
),
};
// ADR-048 typed-commitment wiring — prism's cost-model surface:
// - When the user names a fifth substrate parameter C, the impl
// binds it explicitly and `forward` constructs a C instance
// either from the optional `fn commitment() -> C { … }` clause
// or via `<C as Default>::default()` when the clause is omitted.
// - When C is omitted (3- or 4-position form), C defaults to
// `EmptyCommitment` and the catamorphism's post-resolver
// `evaluate(kappa_label)` consultation accepts unconditionally
// (the bare base-admission semantics from ADR-035).
let (commitment_ty_tokens, commitment_construction) = match (&c_ty, &commitment_body) {
(Some(c), Some(block)) => (quote! { #c }, quote! { #block }),
(Some(c), None) => (
quote! { #c },
quote! { <#c as ::core::default::Default>::default() },
),
(None, _) => (
quote! { ::uor_foundation::pipeline::EmptyCommitment },
quote! { ::uor_foundation::pipeline::EmptyCommitment },
),
};
// Walk the closure body — the macro-time mapping that ADR-020 / D3
// names. The body is processed via the block handler so `let`
// bindings (G10) and the trailing tail expression (G11) are both
// recognised.
//
// ADR-033 G20: pin the route input type into the binding scope so
// field-access expressions can synthesize the const-eval lookup
// against `<RouteInputTy as PartitionProductFields>::FIELDS`.
//
// ADR-056: this is the `prism_model!` route body — the only syntactic
// surface the ψ-residuals discipline applies to. Verb! bodies and
// axis! body clauses keep `in_route_body == false` (the default).
let mut arena: Vec<TermSpec> = Vec::new();
let mut scope = BindingScope {
route_input_ty: Some(input_ty.clone()),
in_route_body: true,
..BindingScope::default()
};
if let Err(e) = emit_term_for_block(&route_body, &route_input_ident, &mut arena, &mut scope) {
return e.to_compile_error().into();
}
// ADR-060: the foundation-derived inline carrier width for this model's
// selected `HostBounds` (#b_ty). `#b_ty` is concrete at the call site, so
// `carrier_inline_bytes::<#b_ty>()` is a concrete `const` expression
// admissible as a const-generic argument on stable Rust. Threaded through
// `Term`/`TermArena`, `FoundationClosed`, `PrismModel`, `run_route`,
// `Grounded`, and the verb-splice arena builder.
let inline_bytes = quote! {
{ ::uor_foundation::pipeline::carrier_inline_bytes::<#b_ty>() }
};
// ADR-018/060: the application's selected fingerprint width, read from its
// `HostBounds` (#b_ty). `#b_ty` is concrete at the call site so this is a
// concrete `const` expression, admissible as a const-generic argument on
// stable Rust (no `generic_const_exprs`). Threaded through `PrismModel`,
// `Grounded`, and `run_route` exactly parallel to `inline_bytes`, so the
// application's substituted `Hasher` width flows end-to-end without the
// author writing it — ergonomically identical to the `=32`-default form.
let fp_max = quote! {
{ <#b_ty as ::uor_foundation::HostBounds>::FINGERPRINT_MAX_BYTES }
};
// Per wiki ADR-024, verb fragments are inlined into the route's
// arena at compile time via the const-fn arena builder when any
// verb invocation is present. Pure (verb-free) routes use the
// simple slice-literal form.
let route_has_verb_splices = arena
.iter()
.any(|s| matches!(s, TermSpec::VerbSplice { .. }));
let route_arena_expr = if route_has_verb_splices {
render_const_fn_arena_builder(&arena, &inline_bytes)
} else {
let term_specs = render_arena(&arena);
quote! { &[ #( #term_specs ),* ] }
};
// Synthesize a unique const name from the model's identifier so two
// models in the same module don't clash on `ROUTE_TERMS`.
let route_terms_const = Ident::new(
&format!(
"ROUTE_TERMS_FOR_{}",
to_screaming_snake(&model_name.to_string())
),
model_name.span(),
);
let expansion = quote! {
// Re-emit the model + route witness structs from the input.
#model_vis struct #model_name;
#route_vis struct #route_name;
// ADR-022 D2 + ADR-024: const term-tree slice. Macro-time-built,
// with verb fragments inlined at compile time per ADR-024 (the
// catamorphism walks a flat arena over the ten Term variants —
// no runtime depth guard). `pipeline::run_route` reads the
// slice via `FoundationClosed::arena_slice`.
#[allow(non_upper_case_globals, dead_code)]
const #route_terms_const: &[::uor_foundation::enforcement::Term<'static, #inline_bytes>] =
#route_arena_expr;
// ADR-022 D1: seal impls. Foundation-internal macro is the
// only sanctioned producer outside foundation itself.
impl ::uor_foundation::pipeline::__sdk_seal::Sealed for #model_name {}
impl ::uor_foundation::pipeline::__sdk_seal::Sealed for #route_name {}
// ADR-022 D5 + ADR-060: FoundationClosed impl returning the parsed
// term-tree, const-generic over the foundation-derived inline width.
impl ::uor_foundation::pipeline::FoundationClosed<#inline_bytes> for #route_name {
fn arena_slice() -> &'static [::uor_foundation::enforcement::Term<'static, #inline_bytes>] {
#route_terms_const
}
}
// ADR-020 + ADR-022 D4 + ADR-036 + ADR-048 + ADR-060: PrismModel impl.
// The 4th slot is the foundation-derived INLINE_BYTES carrier width
// (ADR-060); the 5th binds the route's ResolverTuple per ADR-036
// (NullResolverTuple default); the 6th binds the model's
// TypedCommitment per ADR-048 (EmptyCommitment default). The
// macro-emitted `forward` body constructs both substrate instances
// and threads them to `pipeline::run_route` per ADR-022 D5.
impl<'a> ::uor_foundation::pipeline::PrismModel<'a, #h_ty, #b_ty, #a_ty, #inline_bytes, #fp_max, #resolver_ty_tokens, #commitment_ty_tokens> for #model_name {
type Input = #input_ty;
type Output = #output_ty;
type Route = #route_name;
fn forward(
input: <Self as ::uor_foundation::pipeline::PrismModel<'a, #h_ty, #b_ty, #a_ty, #inline_bytes, #fp_max, #resolver_ty_tokens, #commitment_ty_tokens>>::Input,
) -> ::core::result::Result<
::uor_foundation::enforcement::Grounded<
'a,
<Self as ::uor_foundation::pipeline::PrismModel<'a, #h_ty, #b_ty, #a_ty, #inline_bytes, #fp_max, #resolver_ty_tokens, #commitment_ty_tokens>>::Output,
#inline_bytes,
#fp_max,
>,
::uor_foundation::PipelineFailure,
> {
let __resolvers: #resolver_ty_tokens = #resolver_construction;
let __commitment: #commitment_ty_tokens = #commitment_construction;
::uor_foundation::pipeline::run_route::<
#h_ty,
#b_ty,
#a_ty,
Self,
#resolver_ty_tokens,
#commitment_ty_tokens,
#inline_bytes,
#fp_max,
>(input, &__resolvers, &__commitment)
}
}
};
expansion.into()
}
// =====================================================================
// `output_shape!` — wiki ADR-027.
//
// Generalizes `GroundedShape`'s seal: the foundation source seals the
// trait via `__sdk_seal::Sealed`, and the `output_shape!` SDK macro
// emits — alongside the application's `ConstrainedTypeShape` impl — the
// `__sdk_seal::Sealed`, `GroundedShape`, and `IntoBindingValue` impls
// gated on the seal. This widens the path applications can declare a
// custom Output shape without lifting the seal entirely.
//
// Macro form:
//
// ```text
// output_shape! {
// pub struct OutputHash;
// impl ConstrainedTypeShape for OutputHash {
// const IRI: &'static str = "https://prism.btc/shape/OutputHash";
// const SITE_COUNT: usize = 32;
// const CONSTRAINTS: &'static [ConstraintRef] = &[];
// }
// }
// ```
//
// Emissions (per ADR-027):
// - `pub struct <Name>;` (re-emitted)
// - `impl ConstrainedTypeShape for <Name>` (re-emitted)
// - `impl __sdk_seal::Sealed for <Name>`
// - `impl GroundedShape for <Name>`
// - `impl IntoBindingValue for <Name>` with MAX_BYTES = SITE_COUNT
// (byte-level granularity default; shapes whose Witt level is
// greater than 8 bits use a wider per-site multiplier the
// application sets via a custom `IntoBindingValue` impl).
/// Parsed shape of the macro input.
struct OutputShapeInput {
struct_vis: syn::Visibility,
struct_name: Ident,
impl_iri: syn::LitStr,
impl_site_count: syn::Expr,
impl_constraints: syn::Expr,
/// ADR-032: optional explicit `const CYCLE_SIZE: u64 = …`. If
/// omitted, the macro defaults to `cycle_size_power(256, SITE_COUNT)`
/// (saturating to `u64::MAX` for SITE_COUNT ≥ 8 bytes).
impl_cycle_size: Option<syn::Expr>,
}
impl Parse for OutputShapeInput {
fn parse(input: ParseStream) -> Result<Self> {
// `pub struct OutputHash;`
let struct_vis: syn::Visibility = input.parse()?;
input.parse::<Token![struct]>()?;
let struct_name: Ident = input.parse()?;
input.parse::<Token![;]>()?;
// `impl ConstrainedTypeShape for OutputHash { ... }`
input.parse::<Token![impl]>()?;
let trait_ident: Ident = input.parse()?;
if trait_ident != "ConstrainedTypeShape" {
return Err(syn::Error::new(
trait_ident.span(),
"output_shape! expects `impl ConstrainedTypeShape for <Name>`",
));
}
input.parse::<Token![for]>()?;
let target: Ident = input.parse()?;
if target != struct_name {
return Err(syn::Error::new(
target.span(),
"output_shape!'s `impl ConstrainedTypeShape for <Name>` target must match the declared struct",
));
}
let body;
syn::braced!(body in input);
// `const IRI: &'static str = "...";`
body.parse::<Token![const]>()?;
let kw_iri: Ident = body.parse()?;
if kw_iri != "IRI" {
return Err(syn::Error::new(
kw_iri.span(),
"expected `const IRI: &'static str = ...`",
));
}
body.parse::<Token![:]>()?;
let _ty: syn::Type = body.parse()?;
body.parse::<Token![=]>()?;
let impl_iri: syn::LitStr = body.parse()?;
body.parse::<Token![;]>()?;
// `const SITE_COUNT: usize = ...;`
body.parse::<Token![const]>()?;
let kw_sc: Ident = body.parse()?;
if kw_sc != "SITE_COUNT" {
return Err(syn::Error::new(
kw_sc.span(),
"expected `const SITE_COUNT: usize = ...`",
));
}
body.parse::<Token![:]>()?;
let _ty: syn::Type = body.parse()?;
body.parse::<Token![=]>()?;
let impl_site_count: syn::Expr = body.parse()?;
body.parse::<Token![;]>()?;
// `const CONSTRAINTS: &'static [ConstraintRef] = ...;`
body.parse::<Token![const]>()?;
let kw_cn: Ident = body.parse()?;
if kw_cn != "CONSTRAINTS" {
return Err(syn::Error::new(
kw_cn.span(),
"expected `const CONSTRAINTS: &'static [ConstraintRef] = ...`",
));
}
body.parse::<Token![:]>()?;
let _ty: syn::Type = body.parse()?;
body.parse::<Token![=]>()?;
let impl_constraints: syn::Expr = body.parse()?;
body.parse::<Token![;]>()?;
// ADR-032: optional `const CYCLE_SIZE: u64 = ...;` — if absent,
// the expansion defaults to `cycle_size_power(256, SITE_COUNT)`.
let impl_cycle_size: Option<syn::Expr> = if body.peek(Token![const]) {
body.parse::<Token![const]>()?;
let kw_cs: Ident = body.parse()?;
if kw_cs != "CYCLE_SIZE" {
return Err(syn::Error::new(
kw_cs.span(),
"expected `const CYCLE_SIZE: u64 = ...` (the only optional const recognised by output_shape! is CYCLE_SIZE per ADR-032)",
));
}
body.parse::<Token![:]>()?;
let _ty: syn::Type = body.parse()?;
body.parse::<Token![=]>()?;
let expr: syn::Expr = body.parse()?;
body.parse::<Token![;]>()?;
Some(expr)
} else {
None
};
Ok(Self {
struct_vis,
struct_name,
impl_iri,
impl_site_count,
impl_constraints,
impl_cycle_size,
})
}
}
/// `output_shape!` — wiki ADR-027 custom Output shape declaration.
///
/// Emits the application-named struct, the `ConstrainedTypeShape` impl
/// (re-emitted from the user's body), and the additional impls
/// `__sdk_seal::Sealed`, `GroundedShape`, and `IntoBindingValue` so the
/// shape qualifies as a `PrismModel::Output`.
#[proc_macro]
pub fn output_shape(input: TokenStream) -> TokenStream {
let parsed = parse_macro_input!(input as OutputShapeInput);
let OutputShapeInput {
struct_vis,
struct_name,
impl_iri,
impl_site_count,
impl_constraints,
impl_cycle_size,
} = parsed;
// ADR-032: explicit CYCLE_SIZE if supplied, else saturating
// `256.pow(SITE_COUNT)` (the byte-shaped upper bound).
let cycle_size_tokens = match impl_cycle_size {
Some(expr) => quote! { #expr },
None => quote! {
::uor_foundation::pipeline::cycle_size_power(256, #impl_site_count)
},
};
let expansion = quote! {
// Re-emit the user's struct and ConstrainedTypeShape impl.
#struct_vis struct #struct_name;
impl ::uor_foundation::pipeline::ConstrainedTypeShape for #struct_name {
const IRI: &'static str = #impl_iri;
const SITE_COUNT: usize = #impl_site_count;
const CONSTRAINTS: &'static [::uor_foundation::pipeline::ConstraintRef] =
#impl_constraints;
// ADR-032: explicit CYCLE_SIZE if supplied, else default.
const CYCLE_SIZE: u64 = #cycle_size_tokens;
}
// ADR-027 emissions: the four sealed-trait impls.
impl ::uor_foundation::pipeline::__sdk_seal::Sealed for #struct_name {}
impl ::uor_foundation::enforcement::GroundedShape for #struct_name {}
impl<'a> ::uor_foundation::pipeline::IntoBindingValue<'a> for #struct_name {
fn as_binding_value<const INLINE_BYTES: usize>(
&self,
) -> ::uor_foundation::pipeline::TermValue<'a, INLINE_BYTES> {
// The output shape carries the catamorphism's evaluation result, not a
// user-supplied input, so the input-side carrier is the empty Inline
// carrier. Applications that re-use the output shape as a downstream
// model's Input write a bespoke `IntoBindingValue` impl reflecting the
// bytes they emit at runtime.
::uor_foundation::pipeline::TermValue::empty()
}
}
};
expansion.into()
}
// =====================================================================
// `verb!` — wiki ADR-024 Layer-3 implementation closure.
//
// An implementation declares a named, reusable composition of prism
// operators applied to substrate primitives. The macro:
//
// - parses a closure-bodied function declaration
// (`pub fn name(input: T) -> U { … }`)
// - emits a `&'static [Term]` slice carrying the verb's term-tree
// fragment (built via the same G1–G19 closure-body grammar as
// `prism_model!`)
// - emits a `pub fn name_term_arena() -> &'static [Term]` accessor
// so `prism_model!` can reference the verb by name during
// route-closure expansion
//
// Form:
//
// ```text
// verb! {
// pub fn sha256_compression(input: BlockInput) -> CompressionState {
// // closure body — same G1–G19 grammar as prism_model!
// hash(input)
// }
// }
// ```
//
// Per ADR-024's three-way responsibility split, the verb's runtime
// is implementation-owned: the term-tree fragment is the structural
// declaration; how an implementation evaluates it (sequential,
// parallel, optimised) is the implementation's choice. Foundation's
// `pipeline::run_route` evaluates verb-reachable Term trees per the
// per-variant fold-rules (ADR-029).
/// Parsed shape of the `verb!` macro input.
struct VerbInput {
fn_vis: syn::Visibility,
fn_name: Ident,
input_param: Ident,
input_ty: syn::Type,
output_ty: syn::Type,
body: syn::Block,
}
impl Parse for VerbInput {
fn parse(input: ParseStream) -> Result<Self> {
let fn_vis: syn::Visibility = input.parse()?;
input.parse::<Token![fn]>()?;
let fn_name: Ident = input.parse()?;
let params;
syn::parenthesized!(params in input);
let input_param: Ident = params.parse()?;
params.parse::<Token![:]>()?;
let input_ty: syn::Type = params.parse()?;
input.parse::<Token![->]>()?;
let output_ty: syn::Type = input.parse()?;
let body: syn::Block = input.parse()?;
Ok(Self {
fn_vis,
fn_name,
input_param,
input_ty,
output_ty,
body,
})
}
}
/// `verb!` — wiki ADR-024 Layer-3 verb declaration. Emits a const
/// term-tree fragment and a public accessor.
#[proc_macro]
pub fn verb(input: TokenStream) -> TokenStream {
let parsed = parse_macro_input!(input as VerbInput);
let VerbInput {
fn_vis,
fn_name,
input_param,
input_ty,
output_ty,
body,
} = parsed;
let mut arena: Vec<TermSpec> = Vec::new();
// ADR-033 G20: pin the verb's input type into the binding scope so
// field-access expressions can synthesize const-eval lookups
// (including depth-2 chains like `input.0.0` per Dependency 1).
//
// ADR-056: verb bodies are NOT subject to the ψ-residuals discipline
// (which applies only to the route body's syntactic surface). Verbs
// may use the full substrate vocabulary — `Concat`, `Le`/`Lt`/`Ge`/
// `Gt`, `hash(...)` axis invocations, `first_admit(...)` bounded
// search — to realize compound operations like SHA padding, HMAC,
// Merkle tree construction, and tensor saturation.
let mut scope = BindingScope {
route_input_ty: Some(input_ty.clone()),
in_route_body: false,
..BindingScope::default()
};
if let Err(e) = emit_term_for_block(&body, &input_param, &mut arena, &mut scope) {
return e.to_compile_error().into();
}
// Wiki ADR-024 verb-closure check: a verb's body must not directly
// reference itself. Self-recursion is the local cycle the macro can
// detect at expansion time; cross-verb cycles surface at the
// application's compile time during const-eval of the splicing
// const-fn calls (Rust's const-eval rejects infinite recursion via
// its const-step ceiling).
let self_const_name = format!("VERB_TERMS_{}", to_screaming_snake(&fn_name.to_string()));
for spec in &arena {
if let TermSpec::VerbSplice { fragment_path, .. } = spec {
if fragment_path.to_string().trim() == self_const_name {
return syn::Error::new(
fn_name.span(),
format!(
"verb-closure violation (ADR-024): `{}`'s body references itself directly; the verb-reference graph through non-`recurse` operators must be acyclic. Lift the recursion through `recurse(...)` (G7) instead.",
fn_name
),
)
.to_compile_error()
.into();
}
}
}
// Determine the term-tree fragment representation: if the verb
// body contains nested verb splices, we must emit a const-fn
// builder that resolves the splices at const-eval time. For pure
// (no nested splices) bodies, the simple slice literal works.
let body_has_verb_splices = arena
.iter()
.any(|s| matches!(s, TermSpec::VerbSplice { .. }));
let verb_fragment_expr = if body_has_verb_splices {
render_const_fn_arena_builder(&arena, "e! { INLINE_BYTES })
} else {
let term_specs = render_arena(&arena);
quote! { &[ #( #term_specs ),* ] }
};
let const_name = Ident::new(
&format!("VERB_TERMS_{}", to_screaming_snake(&fn_name.to_string())),
fn_name.span(),
);
let accessor_name = Ident::new(&format!("{}_term_arena", fn_name), fn_name.span());
// ADR-060: a generic-`INLINE_BYTES` `&'static` term slice cannot be
// returned by a generic `const fn` via rvalue static promotion (the
// promoted array's type depends on the const-generic parameter). The
// stable idiom is a zero-sized holder type with an **associated const**,
// which is `'static` by construction. The verb's const fn / accessor read
// that associated const.
let frag_holder = Ident::new(
&format!("__VerbFrag_{}", to_screaming_snake(&fn_name.to_string())),
fn_name.span(),
);
let expansion = quote! {
// ADR-024 + ADR-060: the verb's term-tree fragment, held as an
// associated const on a const-generic holder type so the
// `&'static [Term<'static, INLINE_BYTES>]` slice is well-formed for any
// consuming model's foundation-derived inline carrier width. A verb is
// model-independent; the consuming `prism_model!` route reads the
// fragment at its own `carrier_inline_bytes::<B>()` width.
#[doc(hidden)]
#[allow(non_camel_case_types)]
#fn_vis struct #frag_holder<const INLINE_BYTES: usize>;
#[allow(dead_code)]
impl<const INLINE_BYTES: usize> #frag_holder<INLINE_BYTES> {
#fn_vis const TERMS: &'static [::uor_foundation::enforcement::Term<'static, INLINE_BYTES>] =
#verb_fragment_expr;
}
// `VERB_TERMS_<NAME>` const fn — names the fragment for `prism_model!`
// splices (after `use_verbs!` re-export) and the verb's own accessor.
#[allow(non_snake_case, dead_code)]
#fn_vis const fn #const_name<const INLINE_BYTES: usize>(
) -> &'static [::uor_foundation::enforcement::Term<'static, INLINE_BYTES>] {
#frag_holder::<INLINE_BYTES>::TERMS
}
// Public accessor for the verb's term-tree fragment. Per
// ADR-024, the verb is a structural declaration — its
// runtime is implementation-owned.
#fn_vis const fn #accessor_name<const INLINE_BYTES: usize>(
) -> &'static [::uor_foundation::enforcement::Term<'static, INLINE_BYTES>] {
#frag_holder::<INLINE_BYTES>::TERMS
}
// Marker `pub fn name(_: InputTy) -> OutputTy` so the verb
// appears at the consumer's name-resolution surface. The body
// never executes as Rust at runtime; foundation's catamorphism
// walks the term-tree fragment per ADR-029.
#[allow(unused_variables, unreachable_code)]
#fn_vis fn #fn_name(#input_param: #input_ty) -> #output_ty {
// Verb bodies are catamorphism-evaluated; the Rust function
// form exists for name-resolution and macro-time reference.
// Implementations that invoke a verb directly use foundation's
// `evaluate_term_tree` against the verb's term-tree slice.
let _ = #input_param;
unimplemented!(
"verb `{}` body is catamorphism-evaluated by foundation's pipeline; \
callers reach it through the term-tree accessor `{}_term_arena()`, \
not by direct Rust invocation",
stringify!(#fn_name),
stringify!(#fn_name),
)
}
};
expansion.into()
}
// =====================================================================
// `use_verbs!` — wiki ADR-024 cross-implementation verb imports.
//
// Re-exports verbs from another crate's `verb!` emissions. The
// importing implementation's verb-closure check treats imported
// verbs as opaque atoms; the imported crate's own `verb!` macro
// performed that crate's closure check.
//
// Form:
//
// ```text
// use_verbs! {
// from other_implementation_crate {
// verb_name_a,
// verb_name_b,
// };
// }
// ```
/// Parsed shape of the `use_verbs!` macro input.
struct UseVerbsInput {
crate_path: syn::Path,
verb_names: Vec<Ident>,
}
impl Parse for UseVerbsInput {
fn parse(input: ParseStream) -> Result<Self> {
// `from <crate_path>`
let from_kw: Ident = input.parse()?;
if from_kw != "from" {
return Err(syn::Error::new(
from_kw.span(),
"expected `from <crate_path>`",
));
}
let crate_path: syn::Path = input.parse()?;
// `{ verb_a, verb_b, ... }`
let body;
syn::braced!(body in input);
let mut verb_names: Vec<Ident> = Vec::new();
while !body.is_empty() {
verb_names.push(body.parse()?);
if body.peek(Token![,]) {
body.parse::<Token![,]>()?;
}
}
// Optional trailing semicolon.
let _ = input.parse::<Token![;]>();
Ok(Self {
crate_path,
verb_names,
})
}
}
/// `use_verbs!` — wiki ADR-024 cross-implementation verb imports.
#[proc_macro]
pub fn use_verbs(input: TokenStream) -> TokenStream {
let parsed = parse_macro_input!(input as UseVerbsInput);
let UseVerbsInput {
crate_path,
verb_names,
} = parsed;
let mut imports: Vec<proc_macro2::TokenStream> = Vec::with_capacity(verb_names.len() * 3);
for name in &verb_names {
let arena_name = Ident::new(&format!("{}_term_arena", name), name.span());
let const_name = Ident::new(
&format!("VERB_TERMS_{}", to_screaming_snake(&name.to_string())),
name.span(),
);
imports.push(quote! { pub use #crate_path::#name; });
imports.push(quote! { pub use #crate_path::#arena_name; });
imports.push(quote! { pub use #crate_path::#const_name; });
}
let expansion = quote! {
#( #imports )*
};
expansion.into()
}
// =====================================================================
// `register_shape!` — wiki ADR-057 SDK macro: registers application shapes
// in the foundation's shape-IRI registry per ADR-057's bounded recursive
// structural typing surface.
//
// Form:
//
// ```text
// register_shape!(MyAppRegistry, Shape1, Shape2, Shape3);
// ```
//
// `MyAppRegistry` is a fresh marker type (struct + sealed impl). The
// remaining identifiers (or types — generic shapes admitted via the
// same Type-parser path that `partition_product!` uses) are the shapes
// to register; each must implement `ConstrainedTypeShape`.
//
// Emits:
//
// 1. `pub struct MyAppRegistry;` marker type.
// 2. `impl __sdk_seal::Sealed for MyAppRegistry`.
// 3. `impl ShapeRegistryProvider for MyAppRegistry` whose `REGISTRY`
// const is a `&'static [RegisteredShape]` aggregating one entry per
// shape, with each entry populated from the shape's `ConstrainedTypeShape`
// associated items.
//
// Application code consults the registry via:
//
// ```text
// pipeline::shape_iri_registry::lookup_shape_in::<MyAppRegistry>(iri)
// ```
//
// The trait-based, const-aggregated registry is foundation's no_std-safe
// + zero-`unsafe` realization of ADR-057's wiki-committed registry surface.
struct RegisterShapeInput {
registry_name: Ident,
shapes: Vec<syn::Type>,
}
impl Parse for RegisterShapeInput {
fn parse(input: ParseStream) -> Result<Self> {
let registry_name: Ident = input.parse()?;
input.parse::<Token![,]>()?;
let mut shapes: Vec<syn::Type> = Vec::new();
let first: syn::Type = input.parse()?;
shapes.push(first);
while input.peek(Token![,]) {
input.parse::<Token![,]>()?;
if input.is_empty() {
break;
}
let next: syn::Type = input.parse()?;
shapes.push(next);
}
if shapes.is_empty() {
return Err(syn::Error::new(
registry_name.span(),
"register_shape! requires at least one shape after the registry name",
));
}
Ok(Self {
registry_name,
shapes,
})
}
}
/// `register_shape!` — wiki ADR-057 shape-IRI registration. Emits a
/// marker type + `ShapeRegistryProvider` impl whose `REGISTRY` const
/// carries one `RegisteredShape` entry per shape, populated from each
/// shape's `ConstrainedTypeShape` associated items.
#[proc_macro]
pub fn register_shape(input: TokenStream) -> TokenStream {
let parsed = parse_macro_input!(input as RegisterShapeInput);
let RegisterShapeInput {
registry_name,
shapes,
} = parsed;
let entries: Vec<proc_macro2::TokenStream> = shapes
.iter()
.map(|shape| {
quote! {
::uor_foundation::pipeline::shape_iri_registry::RegisteredShape {
iri: <#shape as ::uor_foundation::pipeline::ConstrainedTypeShape>::IRI,
site_count: <#shape as ::uor_foundation::pipeline::ConstrainedTypeShape>::SITE_COUNT,
constraints: <#shape as ::uor_foundation::pipeline::ConstrainedTypeShape>::CONSTRAINTS,
cycle_size: <#shape as ::uor_foundation::pipeline::ConstrainedTypeShape>::CYCLE_SIZE,
}
}
})
.collect();
let registry_const = Ident::new(
&format!("{}_SHAPES", to_screaming_snake(®istry_name.to_string())),
registry_name.span(),
);
let expansion = quote! {
/// ADR-057 application shape registry. Const-aggregated through the
/// SDK `register_shape!` macro; consulted by `ψ_1` NerveResolver via
/// `lookup_shape_in::<#registry_name>(iri)` during `Term::Recurse`
/// expansion.
#[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::marker::Copy, ::core::default::Default)]
pub struct #registry_name;
impl ::uor_foundation::pipeline::__sdk_seal::Sealed for #registry_name {}
/// ADR-057 const-aggregated shape registry for [`#registry_name`].
pub const #registry_const:
&[::uor_foundation::pipeline::shape_iri_registry::RegisteredShape] = &[
#( #entries ),*
];
impl ::uor_foundation::pipeline::shape_iri_registry::ShapeRegistryProvider for #registry_name {
const REGISTRY:
&'static [::uor_foundation::pipeline::shape_iri_registry::RegisteredShape] =
#registry_const;
}
};
expansion.into()
}
// Helpers — canonical operand ordering and suffix-identifier construction.
/// Returns the lexically-earlier identifier of two — stable string compare.
/// Used to canonicalize operand ordering in emitted IRIs so
/// `product_shape!(X, A, B)` and `product_shape!(X, B, A)` produce the
/// same `IRI` constant.
fn lexically_earlier(a: &Ident, b: &Ident) -> String {
let a_s = a.to_string();
let b_s = b.to_string();
if a_s.as_str() <= b_s.as_str() {
a_s
} else {
b_s
}
}
fn lexically_later(a: &Ident, b: &Ident) -> String {
let a_s = a.to_string();
let b_s = b.to_string();
if a_s.as_str() > b_s.as_str() {
a_s
} else {
b_s
}
}
/// Returns the operand pair in canonical order. The caller's original
/// (left, right) is reordered so the lexically-earlier identifier is
/// returned first. Amendment §4e canonicalization — token-string-based
/// proxy for the runtime content fingerprint, documented in the plan.
fn canonical_operand_pair(a: &Ident, b: &Ident) -> (Ident, Ident) {
let a_s = a.to_string();
let b_s = b.to_string();
if a_s.as_str() <= b_s.as_str() {
(a.clone(), b.clone())
} else {
(b.clone(), a.clone())
}
}
/// Type-aware variants of the canonical-ordering helpers. Used by the
/// `partition_product!` / `partition_coproduct!` / `cartesian_product_shape!`
/// variadic parsers (since v0.4.11) so operands carrying const-generic or
/// turbofish arguments (`BigIntShape<128>`, `MerkleRoot<H, 32>`,
/// `Tensor<f32, [3, 4]>`) round-trip through the same canonicalization
/// rules as bare-Ident operands.
fn type_token_string(ty: &syn::Type) -> String {
// Stable string form: the full token stream so generic params and
// path qualifiers participate in canonical ordering.
quote::ToTokens::to_token_stream(ty).to_string()
}
fn lexically_earlier_ty(a: &syn::Type, b: &syn::Type) -> String {
let a_s = type_token_string(a);
let b_s = type_token_string(b);
if a_s.as_str() <= b_s.as_str() {
a_s
} else {
b_s
}
}
fn lexically_later_ty(a: &syn::Type, b: &syn::Type) -> String {
let a_s = type_token_string(a);
let b_s = type_token_string(b);
if a_s.as_str() > b_s.as_str() {
a_s
} else {
b_s
}
}
fn canonical_operand_pair_ty(a: &syn::Type, b: &syn::Type) -> (syn::Type, syn::Type) {
let a_s = type_token_string(a);
let b_s = type_token_string(b);
if a_s.as_str() <= b_s.as_str() {
(a.clone(), b.clone())
} else {
(b.clone(), a.clone())
}
}
/// Build a new identifier for a `const` declaration. Converts the base
/// name to SCREAMING_SNAKE_CASE (so a PascalCase shape name like
/// `LeafA_Times_LeafB` becomes `LEAF_A_TIMES_LEAF_B`) and appends the
/// suffix, preserving the original's call-site span for error reporting.
/// This satisfies Rust's `non_upper_case_globals` lint uniformly
/// regardless of the casing style the caller uses for shape names.
fn format_ident_suffix(base: &Ident, suffix: &str) -> Ident {
let upper_base = to_screaming_snake(&base.to_string());
let joined = format!("{upper_base}{suffix}");
Ident::new(&joined, base.span())
}
/// Converts a PascalCase / camelCase / snake_case string to
/// SCREAMING_SNAKE_CASE. Handles runs of uppercase letters, interior
/// underscores, and digit boundaries so the result is idiomatic
/// SCREAMING_SNAKE.
/// Convert CamelCase / PascalCase to lower_snake_case.
fn camel_to_snake(s: &str) -> String {
to_screaming_snake(s).to_ascii_lowercase()
}
fn to_screaming_snake(s: &str) -> String {
let mut out = String::with_capacity(s.len() + 4);
let chars: Vec<char> = s.chars().collect();
for (i, ch) in chars.iter().enumerate() {
if *ch == '_' {
if !out.ends_with('_') && !out.is_empty() {
out.push('_');
}
continue;
}
if ch.is_ascii_uppercase() {
// Insert a separator before an uppercase letter when:
// (a) previous char was lowercase or digit
// (b) previous was uppercase but next is lowercase (end of a
// run like `HTTPServer` → `HTTP_Server`).
let prev_lower_or_digit = i > 0
&& chars[i - 1] != '_'
&& (chars[i - 1].is_ascii_lowercase() || chars[i - 1].is_ascii_digit());
let run_ending = i > 0
&& chars[i - 1].is_ascii_uppercase()
&& i + 1 < chars.len()
&& chars[i + 1].is_ascii_lowercase();
if (prev_lower_or_digit || run_ending) && !out.ends_with('_') && !out.is_empty() {
out.push('_');
}
out.push(*ch);
} else {
out.push(ch.to_ascii_uppercase());
}
}
out
}
// =====================================================================
// `axis!` — wiki ADR-030 substrate-extension axis declaration.
//
// Declares a sealed `AxisExtension`-bounded trait whose author-supplied
// methods become per-method `KERNEL_*` ids; emits the trait, a blanket
// `__sdk_seal::Sealed` for any implementor, and a blanket `AxisExtension`
// impl whose `dispatch_kernel` routes by `kernel_id` to the matching
// trait method.
//
// Form (the wiki's canonical syntax — lines 3144-3155 of 09-Architecture-
// Decisions.md):
//
// ```text
// axis! {
// pub trait MyAxis: ::uor_foundation::pipeline::AxisExtension {
// const AXIS_ADDRESS: &'static str = "https://example.org/axis/MyAxis";
// const MAX_OUTPUT_BYTES: usize = 32;
// fn kernel_one(input: &[u8], out: &mut [u8]) -> Result<usize, ShapeViolation>;
// fn kernel_two(input: &[u8], out: &mut [u8]) -> Result<usize, ShapeViolation>;
// }
// }
// ```
//
// Emissions:
// - the trait declaration (verbatim re-emit)
// - per-method `pub const KERNEL_<METHOD_UPPER>: u32 = i;` ids
// - a blanket `impl<T: MyAxis> AxisExtension for T` whose `dispatch_kernel`
// matches on `kernel_id` and dispatches to the corresponding method
//
// Per ADR-030's closure-check (lines 3242-3251), all axis methods MUST
// take `(input: &[u8], out: &mut [u8]) -> Result<usize, ShapeViolation>`
// signatures; non-conforming methods produce a closure-violation error.
struct AxisInput {
trait_decl: syn::ItemTrait,
/// ADR-055 body clause: the substrate-Term decomposition of the axis
/// kernel, written as a closure `|input| { … }`. The closure body is
/// lowered to a `Term` arena via the standard closure-body grammar
/// (ADR-022 D3 + ADR-026 + ADR-033 + ADR-034 + ADR-035 + ADR-053);
/// the macro emits `impl SubstrateTermBody` returning the arena.
///
/// Wiki ADR-055 shows the clause placed inside the trait
/// (`fn body = |input| { … };`); that placement is not Rust-valid
/// trait-item syntax, so the SDK exposes it as a `body = |input|
/// { … };` clause after the trait declaration. The two surfaces are
/// semantically identical.
body: Option<syn::ExprClosure>,
}
impl Parse for AxisInput {
fn parse(input: ParseStream) -> Result<Self> {
let trait_decl: syn::ItemTrait = input.parse()?;
let mut body = None;
if !input.is_empty() {
// ADR-055 body clause syntax: `body = |input| { ... };`
let body_kw: Ident = input.parse()?;
if body_kw != "body" {
return Err(syn::Error::new(
body_kw.span(),
"expected `body = |input| { … };` clause after the axis trait declaration (ADR-055)",
));
}
input.parse::<Token![=]>()?;
let closure: syn::ExprClosure = input.parse()?;
input.parse::<Token![;]>()?;
body = Some(closure);
}
Ok(Self { trait_decl, body })
}
}
/// `axis!` — wiki ADR-030 substrate-extension axis declaration.
#[proc_macro]
pub fn axis(input: TokenStream) -> TokenStream {
let parsed = parse_macro_input!(input as AxisInput);
let mut trait_decl = parsed.trait_decl;
// ADR-060: `AxisExtension` is now const-generic over `INLINE_BYTES`, so it
// can no longer be a plain supertrait of the axis trait (the axis trait
// isn't generic over `INLINE_BYTES`). Strip the `: AxisExtension`
// supertrait from the re-emitted trait; the `AxisExtension<INLINE_BYTES>`
// relationship is provided per-struct (blanket over `INLINE_BYTES`) by the
// macro-emitted companion impl, not by a trait-level supertrait bound.
trait_decl.supertraits = syn::punctuated::Punctuated::new();
trait_decl.colon_token = None;
let trait_name = trait_decl.ident.clone();
let body_clause = parsed.body;
// Collect method idents (kernel names).
let mut kernel_idents: Vec<Ident> = Vec::new();
for item in &trait_decl.items {
if let syn::TraitItem::Fn(fn_item) = item {
kernel_idents.push(fn_item.sig.ident.clone());
}
}
// Emit per-method kernel id consts.
let mut kernel_consts: Vec<proc_macro2::TokenStream> = Vec::new();
for (i, ident) in kernel_idents.iter().enumerate() {
let upper_name = ident.to_string().to_ascii_uppercase();
let const_name = Ident::new(&format!("KERNEL_{upper_name}"), ident.span());
let id = i as u32;
kernel_consts.push(quote! {
pub const #const_name: u32 = #id;
});
}
// Emit dispatch_kernel arms. The arms live INSIDE the per-struct
// companion macro's macro_rules body, so the implementing type is
// the `$struct_ident` metavariable (not a generic `T`). The
// proc-macro emits the literal token sequence `$ struct_ident` —
// quote!'s `$` handling preserves it for macro_rules to substitute
// at the companion-macro call site.
let dollar = proc_macro2::Punct::new('$', proc_macro2::Spacing::Joint);
let struct_ident_meta: proc_macro2::TokenStream = quote!(#dollar struct_ident);
let struct_ty_meta: proc_macro2::TokenStream = quote!(#dollar struct_ty);
let dispatch_arms: Vec<proc_macro2::TokenStream> = kernel_idents
.iter()
.enumerate()
.map(|(i, ident)| {
let id = i as u32;
quote! {
#id => <#struct_ident_meta as #trait_name>::#ident(input, out),
}
})
.collect();
let dispatch_arms_generic: Vec<proc_macro2::TokenStream> = kernel_idents
.iter()
.enumerate()
.map(|(i, ident)| {
let id = i as u32;
quote! {
#id => <#struct_ty_meta as #trait_name>::#ident(input, out),
}
})
.collect();
// Wiki ADR-030: the axis trait has `AxisExtension` as a supertrait.
// The blanket `impl<T: MyAxis> AxisExtension for T` cannot be emitted
// here without violating Rust's orphan rule (AxisExtension is a
// foundation-foreign trait when the macro is invoked from an
// application crate). Instead, the macro emits a companion
// `axis_extension_impl_for_<lower_snake_case>!(<StructIdent>)` macro
// the user invokes per implementing struct; that macro produces an
// `impl AxisExtension for <StructIdent>` with the kernel-routed
// dispatch arms. The companion-macro pattern is the standard
// ecosystem idiom for foreign-trait blanket-implementation
// emission (cf. `serde::__impl_de_unsized_impl_block!`).
//
// Foundation-internal axis declarations (foundation-private crates
// invoking `axis!`) get the orphan rule for free because
// `AxisExtension` is local to foundation; the companion macro is
// optional in that context but emitted regardless for surface
// uniformity.
let trait_name_lower = camel_to_snake(&trait_name.to_string());
let companion_macro_ident = Ident::new(
&format!("axis_extension_impl_for_{trait_name_lower}"),
trait_name.span(),
);
// ADR-055 body clause lowering. When the macro's input carries a
// `body = |input| { … };` clause, lower the closure body to a Term
// arena via the standard closure-body grammar (the same path
// `prism_model!` uses for route bodies). The resulting arena lives
// in a const at the axis declaration's surrounding module so the
// companion-macro emission can reference it.
//
// When no body clause is provided, the companion macros emit
// `body_arena() -> &[]` (the primitive-fast-path interpretation per
// ADR-055 — byte-output-equivalent to `dispatch_kernel`).
// ADR-060: a generic-`INLINE_BYTES` `&'static` term slice cannot be
// returned by a generic `const fn` nor stored in a plain const via rvalue
// static promotion (the promoted array's type depends on the const-generic
// parameter). Mirror the verb fix: hold the body arena as an associated
// const on a const-generic zero-sized holder type so the
// `&'static [Term<'static, INLINE_BYTES>]` slice is well-formed for any
// consuming model's foundation-derived inline carrier width.
let body_arena_holder = Ident::new(
&format!("__AxisBody_{}", to_screaming_snake(&trait_name.to_string())),
trait_name.span(),
);
let (body_arena_const, body_arena_expr): (proc_macro2::TokenStream, proc_macro2::TokenStream) =
if let Some(closure) = body_clause {
// The closure must have exactly one input named `input`.
if closure.inputs.len() != 1 {
let err = syn::Error::new_spanned(
&closure,
"ADR-055 body clause: closure must have exactly one input named `input`",
);
return err.to_compile_error().into();
}
let input_pat = &closure.inputs[0];
let input_ident: Ident = match input_pat {
syn::Pat::Ident(pi) => pi.ident.clone(),
other => {
let err = syn::Error::new_spanned(
other,
"ADR-055 body clause: closure input must be a bare identifier `input`",
);
return err.to_compile_error().into();
}
};
// Lower the closure body. We accept either a block body or an
// expression body; emit_term_for_block handles blocks, while a
// bare-expression body wraps as a single tail expr.
let body_block: syn::Block = match closure.body.as_ref() {
syn::Expr::Block(eb) => eb.block.clone(),
other => {
let span = quote::ToTokens::to_token_stream(other);
let parsed: syn::Block = match syn::parse2(quote! { { #span } }) {
Ok(b) => b,
Err(e) => return e.to_compile_error().into(),
};
parsed
}
};
let mut arena: Vec<TermSpec> = Vec::new();
let mut scope = BindingScope::default();
if let Err(e) = emit_term_for_block(&body_block, &input_ident, &mut arena, &mut scope) {
return e.to_compile_error().into();
}
let has_verb_splices = arena
.iter()
.any(|s| matches!(s, TermSpec::VerbSplice { .. }));
let arena_expr = if has_verb_splices {
render_const_fn_arena_builder(&arena, "e! { INLINE_BYTES })
} else {
let term_specs = render_arena(&arena);
quote! { &[ #( #term_specs ),* ] }
};
(
quote! {
#[doc(hidden)]
#[allow(non_camel_case_types)]
struct #body_arena_holder<const INLINE_BYTES: usize>;
#[allow(dead_code)]
impl<const INLINE_BYTES: usize> #body_arena_holder<INLINE_BYTES> {
const TERMS: &'static [::uor_foundation::enforcement::Term<'static, INLINE_BYTES>] =
#arena_expr;
}
},
quote! { #body_arena_holder::<INLINE_BYTES>::TERMS },
)
} else {
// No body clause — primitive-fast-path interpretation.
(quote! {}, quote! { &[] })
};
let expansion = quote! {
#trait_decl
#(#kernel_consts)*
// ADR-055 body-arena const (emitted when a `body = …;` clause is
// present; absent otherwise — companion-macro uses the empty-arena
// primitive-fast-path interpretation).
#body_arena_const
/// Wiki ADR-030 companion macro: instantiate `AxisExtension`
/// for a concrete struct implementing this axis trait. The
/// macro emits an `impl AxisExtension for <StructIdent>` block
/// that delegates `dispatch_kernel` to the axis-trait methods
/// per `KERNEL_*` id. The orphan-rule-conformant per-struct
/// impl mechanism replacing the blanket
/// `impl<T: <axis>> AxisExtension for T` (which would violate
/// Rust's orphan rule from any crate that does not define
/// `AxisExtension`).
#[macro_export]
macro_rules! #companion_macro_ident {
// Non-generic form: simple struct ident.
($struct_ident:ident) => {
// ADR-055: SubstrateTermBody supertrait. The body_arena
// resolves to the `BODY_ARENA_<AXIS>` const if the axis
// declaration carried a `body = …;` clause, otherwise to
// the empty slice (primitive-fast-path interpretation
// where dispatch_kernel is byte-output-equivalent).
impl ::uor_foundation::pipeline::__sdk_seal::Sealed for $struct_ident {}
impl<const INLINE_BYTES: usize> ::uor_foundation::pipeline::SubstrateTermBody<INLINE_BYTES> for $struct_ident {
fn body_arena() -> &'static [::uor_foundation::enforcement::Term<'static, INLINE_BYTES>] {
#body_arena_expr
}
}
impl<const INLINE_BYTES: usize, const FP_MAX: usize> ::uor_foundation::pipeline::AxisExtension<INLINE_BYTES, FP_MAX> for $struct_ident {
const AXIS_ADDRESS: &'static str =
<$struct_ident as #trait_name>::AXIS_ADDRESS;
const MAX_OUTPUT_BYTES: usize =
<$struct_ident as #trait_name>::MAX_OUTPUT_BYTES;
fn dispatch_kernel(
kernel_id: u32,
input: &[u8],
out: &mut [u8],
) -> ::core::result::Result<
usize,
::uor_foundation::enforcement::ShapeViolation,
> {
match kernel_id {
#(#dispatch_arms)*
_ => Err(::uor_foundation::enforcement::ShapeViolation {
shape_iri:
"https://uor.foundation/axis/AxisExtensionShape",
constraint_iri:
"https://uor.foundation/axis/AxisExtensionShape/kernelId",
property_iri:
"https://uor.foundation/axis/kernelId",
expected_range:
"https://uor.foundation/axis/RecognisedKernelId",
min_count: 0,
max_count: 0,
kind: ::uor_foundation::ViolationKind::ValueCheck,
}),
}
}
}
};
// ADR-052 @generic form: parametric Layer-3 axis implementations.
// Accepts the implementing type plus generic parameter list and
// optional where-clauses, emitting the `AxisExtension` impl with
// the same kernel-id-dispatch surface.
//
// Examples:
// axis_extension_impl_for_x!(@generic MyImpl<T>, [T], where [T: Bound]);
// axis_extension_impl_for_x!(@generic Wrap<T, const N: usize>, [T, const N: usize]);
//
// The first repeating group is the generic parameter list as
// it would appear after `impl<...>`. The optional `where [...]`
// group carries any predicates.
(@generic $struct_ty:ty, [$($generic_params:tt)*] $(, where [$($where_clauses:tt)*])?) => {
impl<$($generic_params)*> ::uor_foundation::pipeline::__sdk_seal::Sealed for $struct_ty
$(where $($where_clauses)*)?
{}
impl<const INLINE_BYTES: usize, $($generic_params)*> ::uor_foundation::pipeline::SubstrateTermBody<INLINE_BYTES> for $struct_ty
$(where $($where_clauses)*)?
{
fn body_arena() -> &'static [::uor_foundation::enforcement::Term<'static, INLINE_BYTES>] {
#body_arena_expr
}
}
impl<const INLINE_BYTES: usize, const FP_MAX: usize, $($generic_params)*> ::uor_foundation::pipeline::AxisExtension<INLINE_BYTES, FP_MAX> for $struct_ty
$(where $($where_clauses)*)?
{
const AXIS_ADDRESS: &'static str =
<$struct_ty as #trait_name>::AXIS_ADDRESS;
const MAX_OUTPUT_BYTES: usize =
<$struct_ty as #trait_name>::MAX_OUTPUT_BYTES;
fn dispatch_kernel(
kernel_id: u32,
input: &[u8],
out: &mut [u8],
) -> ::core::result::Result<
usize,
::uor_foundation::enforcement::ShapeViolation,
> {
match kernel_id {
#(#dispatch_arms_generic)*
_ => Err(::uor_foundation::enforcement::ShapeViolation {
shape_iri:
"https://uor.foundation/axis/AxisExtensionShape",
constraint_iri:
"https://uor.foundation/axis/AxisExtensionShape/kernelId",
property_iri:
"https://uor.foundation/axis/kernelId",
expected_range:
"https://uor.foundation/axis/RecognisedKernelId",
min_count: 0,
max_count: 0,
kind: ::uor_foundation::ViolationKind::ValueCheck,
}),
}
}
}
};
}
};
expansion.into()
}
// =====================================================================
// `resolver!` — wiki ADR-036 ResolverTuple declaration macro.
//
// Application authors declare ResolverTuple impls through this macro
// paralleling `axis!` per ADR-030. The macro recognizes eight canonical
// field names — one per `ResolverCategory` variant — and emits the
// `ResolverTuple` impl, the per-category accessor methods, the
// `Has<Category>Resolver<H>` satisfactions, and the seal.
//
// Form:
//
// ```text
// resolver! {
// pub struct MyApplicationResolvers<H: ::uor_foundation::enforcement::Hasher> {
// nerve: MyNerveResolver<H>,
// chain_complex: MyChainComplexResolver<H>,
// // ... only the fields the application's verbs require;
// // missing categories default to foundation's Null impls
// // (which propagate RESOLVER_ABSENT through Term::Try).
// }
// }
// ```
//
// Recognised field names (each maps to one `ResolverCategory` + one
// resolver trait):
// - nerve → NerveResolver<H>
// - chain_complex → ChainComplexResolver<H>
// - homology_groups → HomologyGroupResolver<H>
// - cochain_complex → CochainComplexResolver<H>
// - cohomology_groups → CohomologyGroupResolver<H>
// - postnikov → PostnikovResolver<H>
// - homotopy_groups → HomotopyGroupResolver<H>
// - k_invariants → KInvariantResolver<H>
//
// Unrecognised field names fail with a closure-violation error at
// proc-macro expansion citing the recognised field-name set.
struct ResolverInput {
struct_vis: syn::Visibility,
struct_name: Ident,
hasher_param: Ident,
fields: Vec<(Ident, syn::Type)>,
/// ADR-057: optional shape-registry marker type. When the application's
/// `resolver!` declaration carries a `shape_registry: MyRegistry` clause,
/// the emitted `ResolverTuple` impl sets `type ShapeRegistry = MyRegistry`
/// — ψ_1's `NerveResolver` consults `R::REGISTRY` plus foundation's
/// built-in registry when expanding `ConstraintRef::Recurse`. Defaults
/// to `EmptyShapeRegistry` (foundation built-in registry only) when the
/// clause is absent.
shape_registry: Option<syn::Type>,
}
impl Parse for ResolverInput {
fn parse(input: ParseStream) -> Result<Self> {
let struct_vis: syn::Visibility = input.parse()?;
input.parse::<Token![struct]>()?;
let struct_name: Ident = input.parse()?;
// Parse the generic Hasher parameter `<H: ::uor_foundation::enforcement::Hasher>`
// — we only need the parameter's identifier (H or whatever name)
// for emitting the impls. The bound is enforced by the trait
// definitions in foundation.
input.parse::<Token![<]>()?;
let hasher_param: Ident = input.parse()?;
// Skip past the trait bound (`:` followed by a path).
if input.peek(Token![:]) {
input.parse::<Token![:]>()?;
let _: syn::Type = input.parse()?;
}
input.parse::<Token![>]>()?;
let body;
syn::braced!(body in input);
let mut fields: Vec<(Ident, syn::Type)> = Vec::new();
let mut shape_registry: Option<syn::Type> = None;
while !body.is_empty() {
// `pub` is admitted but optional — discard.
if body.peek(Token![pub]) {
let _: syn::Visibility = body.parse()?;
}
let field_name: Ident = body.parse()?;
body.parse::<Token![:]>()?;
let field_ty: syn::Type = body.parse()?;
// ADR-057: the reserved `shape_registry` clause names the
// application's ShapeRegistryProvider marker type; it is NOT
// a resolver-category field.
if field_name == "shape_registry" {
if shape_registry.is_some() {
return Err(syn::Error::new_spanned(
&field_name,
"`resolver!` shape_registry clause specified twice",
));
}
shape_registry = Some(field_ty);
} else {
fields.push((field_name, field_ty));
}
if body.peek(Token![,]) {
body.parse::<Token![,]>()?;
}
}
Ok(Self {
struct_vis,
struct_name,
hasher_param,
fields,
shape_registry,
})
}
}
const RESOLVER_FIELD_TABLE: &[(&str, &str, &str, &str, &str)] = &[
// (field_name, ResolverCategory, ResolverTrait, MarkerTrait, accessor_method)
(
"nerve",
"Nerve",
"NerveResolver",
"HasNerveResolver",
"nerve_resolver",
),
(
"chain_complex",
"ChainComplex",
"ChainComplexResolver",
"HasChainComplexResolver",
"chain_complex_resolver",
),
(
"homology_groups",
"HomologyGroup",
"HomologyGroupResolver",
"HasHomologyGroupResolver",
"homology_group_resolver",
),
(
"cochain_complex",
"CochainComplex",
"CochainComplexResolver",
"HasCochainComplexResolver",
"cochain_complex_resolver",
),
(
"cohomology_groups",
"CohomologyGroup",
"CohomologyGroupResolver",
"HasCohomologyGroupResolver",
"cohomology_group_resolver",
),
(
"postnikov",
"Postnikov",
"PostnikovResolver",
"HasPostnikovResolver",
"postnikov_resolver",
),
(
"homotopy_groups",
"HomotopyGroup",
"HomotopyGroupResolver",
"HasHomotopyGroupResolver",
"homotopy_group_resolver",
),
(
"k_invariants",
"KInvariant",
"KInvariantResolver",
"HasKInvariantResolver",
"k_invariant_resolver",
),
];
/// `resolver!` — wiki ADR-036 ResolverTuple declaration macro.
///
/// Declares a sealed `ResolverTuple` impl from a struct-bodied field
/// list. Each field name MUST be one of the eight canonical resolver
/// categories; the field type is the application-author's resolver
/// trait impl for that category (parameterized by the model's Hasher).
///
/// The macro emits all eight `Has<Category>Resolver<H>` impls so the
/// resulting struct satisfies `run_route`'s where-clause unconditionally.
/// Declared fields delegate to the user's resolver value; undeclared
/// categories delegate to `NullResolverTuple`, whose `resolve` returns
/// the `RESOLVER_ABSENT` shape violation (recoverable through
/// `Term::Try`'s default-propagation handler per ADR-022 D3 G9).
#[proc_macro]
pub fn resolver(input: TokenStream) -> TokenStream {
let parsed = parse_macro_input!(input as ResolverInput);
let ResolverInput {
struct_vis,
struct_name,
hasher_param,
fields,
shape_registry,
} = parsed;
// Validate field names against the canonical table.
let recognised: Vec<&str> = RESOLVER_FIELD_TABLE.iter().map(|t| t.0).collect();
for (name, _) in &fields {
let name_str = name.to_string();
if !recognised.contains(&name_str.as_str()) {
let recognised_csv = recognised.join(", ");
return syn::Error::new_spanned(
name,
format!(
"closure violation: `resolver!` field `{name_str}` is not a recognised resolver category. Recognised: {recognised_csv}"
),
)
.to_compile_error()
.into();
}
}
// Build the struct fields token stream.
let struct_fields: Vec<proc_macro2::TokenStream> = fields
.iter()
.map(|(name, ty)| quote::quote! { pub #name: #ty, })
.collect();
// Build the CATEGORIES const array.
let category_idents: Vec<proc_macro2::TokenStream> = fields
.iter()
.map(|(name, _)| {
// Field name was validated above against RESOLVER_FIELD_TABLE,
// so `find` is guaranteed to return Some. Fall back to the
// first entry on the impossible None branch to avoid `.expect`.
let entry = RESOLVER_FIELD_TABLE
.iter()
.find(|t| t.0 == name.to_string().as_str())
.unwrap_or(&RESOLVER_FIELD_TABLE[0]);
let cat = syn::Ident::new(entry.1, name.span());
quote::quote! { ::uor_foundation::pipeline::ResolverCategory::#cat }
})
.collect();
let arity = fields.len();
// ADR-036: emit ALL 8 Has<Category>Resolver<H> impls so user-declared
// ResolverTuple structs satisfy `run_route`'s where-clause regardless
// of which categories the application chose to populate. For each
// category:
// - declared field: delegate to `&self.<field_name>`
// - undeclared: delegate to `&NullResolverTuple` (foundation's
// Null impls satisfy every resolver trait for any
// `H: Hasher`, emitting RESOLVER_ABSENT at resolve
// time per ADR-022 D3 G9).
let has_impls: Vec<proc_macro2::TokenStream> = RESOLVER_FIELD_TABLE
.iter()
.map(|entry| {
let cat_field = entry.0;
let resolver_trait = syn::Ident::new(entry.2, struct_name.span());
let marker = syn::Ident::new(entry.3, struct_name.span());
let accessor = syn::Ident::new(entry.4, struct_name.span());
if let Some((field_name, field_ty)) = fields
.iter()
.find(|(n, _)| *n == cat_field)
{
// Declared category: where-clause asserts the user's
// field type impls the resolver trait, and the accessor
// returns a borrow of that field. ADR-060: blanket over the
// carrier inline width `INLINE_BYTES` so the tuple satisfies
// any model's `run_route` regardless of its `HostBounds`.
quote::quote! {
impl<const INLINE_BYTES: usize, #hasher_param: ::uor_foundation::enforcement::Hasher>
::uor_foundation::pipeline::#marker<INLINE_BYTES, #hasher_param>
for #struct_name<#hasher_param>
where
#field_ty: ::uor_foundation::pipeline::#resolver_trait<INLINE_BYTES, #hasher_param>,
{
fn #accessor(&self) -> &dyn ::uor_foundation::pipeline::#resolver_trait<INLINE_BYTES, #hasher_param> {
&self.#field_name
}
}
}
} else {
// Undeclared category: accessor returns a static borrow
// of `NullResolverTuple` (unit-struct const-promotion).
// `NullResolverTuple` already impls every resolver trait
// for any `H: Hasher` and `INLINE_BYTES` (foundation,
// ADR-036 + ADR-060), so the `&dyn` coercion is direct.
quote::quote! {
impl<const INLINE_BYTES: usize, #hasher_param: ::uor_foundation::enforcement::Hasher>
::uor_foundation::pipeline::#marker<INLINE_BYTES, #hasher_param>
for #struct_name<#hasher_param>
{
fn #accessor(&self) -> &dyn ::uor_foundation::pipeline::#resolver_trait<INLINE_BYTES, #hasher_param> {
&::uor_foundation::pipeline::NullResolverTuple
}
}
}
}
})
.collect();
// Build a `Default::default()`-per-field initializer list so the
// macro-emitted `Default` impl can construct the tuple struct without
// referencing user types directly. The Default impl carries explicit
// `where #ty: Default` bounds for each declared field, so field types
// that aren't `Default` simply make the impl uninstantiable (the
// user supplies `fn resolvers() -> R` in `prism_model!` instead).
let default_field_inits: Vec<proc_macro2::TokenStream> = fields
.iter()
.map(|(name, _)| quote::quote! { #name: ::core::default::Default::default(), })
.collect();
let default_where_clauses: Vec<proc_macro2::TokenStream> = fields
.iter()
.map(|(_, ty)| quote::quote! { #ty: ::core::default::Default, })
.collect();
// ADR-057: resolve the ShapeRegistry associated type — either the
// user's `shape_registry: MyRegistry` clause, or foundation's
// EmptyShapeRegistry default.
let shape_registry_ty: proc_macro2::TokenStream = match shape_registry {
Some(ty) => quote::quote! { #ty },
None => quote::quote! {
::uor_foundation::pipeline::shape_iri_registry::EmptyShapeRegistry
},
};
let expansion = quote::quote! {
#struct_vis struct #struct_name<#hasher_param: ::uor_foundation::enforcement::Hasher> {
#(#struct_fields)*
#[doc(hidden)]
pub _phantom: ::core::marker::PhantomData<#hasher_param>,
}
impl<#hasher_param: ::uor_foundation::enforcement::Hasher>
::uor_foundation::pipeline::__sdk_seal::Sealed
for #struct_name<#hasher_param> {}
impl<#hasher_param: ::uor_foundation::enforcement::Hasher>
::uor_foundation::pipeline::ResolverTuple
for #struct_name<#hasher_param>
{
const ARITY: usize = #arity;
const CATEGORIES: &'static [::uor_foundation::pipeline::ResolverCategory] =
&[#(#category_idents),*];
// ADR-057: ψ_1's NerveResolver consults this registry when
// expanding ConstraintRef::Recurse. Defaults to foundation's
// EmptyShapeRegistry when the application's `resolver!`
// declaration omits the `shape_registry: MyRegistry` clause.
type ShapeRegistry = #shape_registry_ty;
}
// ADR-036 + prism_model!-default-construction interop: emit
// `Default` so the macro-emitted `forward` body can call
// `<R as Default>::default()` when the user does not supply an
// explicit `fn resolvers() -> R` clause. Each declared field
// type appears in the `where`-clause; fields that don't impl
// `Default` make this impl uninstantiable at use-site (the
// application supplies the explicit clause instead).
impl<#hasher_param: ::uor_foundation::enforcement::Hasher>
::core::default::Default
for #struct_name<#hasher_param>
where
#(#default_where_clauses)*
{
fn default() -> Self {
Self {
#(#default_field_inits)*
_phantom: ::core::marker::PhantomData,
}
}
}
#(#has_impls)*
};
expansion.into()
}