ingraph-derive 0.1.0

The attribute and derive macros for ingraph: the words a record, node, key, filter and vocabulary declaration is written in.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
#![deny(missing_docs)]
// The docs.rs badge half: `doc_cfg` derives the "Available on crate feature `x` only" banner from
// the `cfg` a gated item already carries. This crate declares NO features, so it derives nothing
// today — the attribute is here because the knob that turns it on is, and the two belong together:
// `docsrs` is set by the `rustdoc-args` in `[package.metadata.docs.rs]` below and by nothing else,
// so a root that never named `doc_cfg` would leave that cfg dangling. Nightly-only, hence the
// `cfg_attr`; every stable build compiles a crate that has never heard of `docsrs`.
#![cfg_attr(docsrs, feature(doc_cfg))]
//! The macros for [`ingraph`](https://docs.rs/ingraph).
//!
//! These expand a declaration into the framework faces a record must implement — `Transformer`,
//! the per-backend record impls and the query bindings. They generate **framework** faces only:
//! domain validation, constructor invariants and the error enums that mirror them belong to the
//! application's own types.
//!
//! **Today they expand the key TYPES and the binding that ties them to the record.** [`Record`]
//! emits `*Key`, `*Lineage`, `impl Transformer for <Record>` and the `Identifiable` supertrait it
//! cannot be written without — on the record and on the `*Key` both, the two types carrying the same
//! id column. The rest of the trait layer is still moving, and an expansion naming a half-settled
//! trait would owe every consumer a revision the moment it settled — so the other impls wait. Those
//! two are not among them: their faces are the expansion's own output and the record it sits on, so
//! they name nothing that could settle differently.
//!
//! # THE FORM IS AN ATTRIBUTE, because these macros rewrite the item they sit on
//!
//! A derive is handed a copy of the declaration and may only APPEND. These need to change it — a
//! derived index carries an identity it does not mint, as one field whose TYPE is a projection, and
//! that field has to be in the struct rather than beside it — so the whole family is attribute
//! macros and the declaration's own options are the attribute's ARGUMENTS:
//!
//! ```ignore
//! #[ingraph::record(sqlite, lineage(fields(media_id)))]
//! pub struct VideoTrack { … }
//! ```
//!
//! The second thing the form buys is the VISIBILITY CONVENTION: a field written with no visibility
//! is stamped `pub(crate)` by the macro, and an author's explicit visibility is preserved, so the
//! rule stops being the author's pen. See [`host`] for the whole of what an echo changes and the
//! much longer list of what it carries verbatim.
//!
//! # ONE NODE HOLDS ONE STORAGE, so the macro IS the storage declaration
//!
//! [`operator`] is the node family's base — it subscribes, it computes, it emits, and it owns no
//! storage — and every other node macro is it plus exactly one store: [`record`] holds rows in the
//! databases its store words name, [`aggregate`] holds rows a declared FOLD over one upstream's
//! rows fills, and [`fulltext`], [`vector`] and [`blob`] each hold documents derived from another
//! node's messages. So there is no word on a declaration that says which storage it has; the
//! attribute's own name is that word, which is one layer fewer and one contradiction fewer.
//!
//! The family splits again one level down, and the axis is the KEY rather than the store. A record,
//! an aggregate and an operator MINT an id — an aggregate's from the group columns it projects; the
//! three derived indexes mint none and carry their upstream's key in a field this crate injects.
//! That is the second thing the attribute form buys, and the reason the three could not arrive
//! before `upstream(…)` did.
//!
//! The two halves of the law are enforced in the two places they can be. The block a node may write
//! is checked HERE, against the macro it was written under, and every other storage block is
//! refused by a message naming the declaration that takes it. That a node does not take a SECOND
//! macro cannot be checked here at all — two macro expansions cannot see each other — so each
//! storage macro mints the same marker item in the declaring scope and two of them are `E0428` at
//! the offending type. `tests/storages/` reads the collision back.
//!
//! # THE RECORD FAMILY IS A LADDER, and each word names what its rung HAS
//!
//! | tier | word | has | lacks |
//! |---|---|---|---|
//! | field fragment | [`fields`] | shared fields, declared once, inherited by holders | identity, rows, wire root |
//! | entity | [`entity`] | id · key · lineage · accessors · filter and comparison faces · a wire face | rows |
//! | record | [`record`] | everything above **plus the storage essence** — rows, in the databases it names | — |
//!
//! [`fields`] is beside the node family rather than in it: a fragment is HELD, so it is not a node
//! at all — no identity, no storage, no wire root, and therefore no marker and no place in the
//! one-storage law above. The word used to be `entity`, and the tier's own doc confessed the
//! mismatch in as many words (*no stable identity is what the tier means*) while `entity` means an
//! identity-bearing thing everywhere else in this framework — the entity binding, a hit's `entity`
//! field, `TypedId`'s entity marker. So the word moved up to the rung it always described.
//!
//! [`record`] and [`entity`] differ in the STORAGE ESSENCE and in nothing else, which is why a
//! record names its stores BARE at the head — `#[ingraph::record(sqlite, postgres)]` — rather than
//! inside a wrapper. An optional axis gets a block (`graphql(…)`); an essence never wraps. A record
//! naming no store is refused and told the two exits, because a record IS rows.
//!
//! Every expansion may use only `ingraph`'s public API, so a hand-written declaration and a
//! generated one are the same program. The design is recorded in `docs/` (not published).
//!
//! # AN EXPANSION ASSUMES THE FRAMEWORK'S TIERS ARE IN PLACE
//!
//! `ingraph` is cut into tiers — a vocabulary core, then `engine`, then `runtime`, then `derive` —
//! and what these macros write reaches into all of them. A declaration's expansion names
//! `__private::drive`, `__private::source`, `__private::operator`, `__private::resource` and
//! `__private::retrieve`, and it names them as ABSOLUTE paths carrying no `#[cfg]`, because a
//! `#[cfg(feature = …)]` written inside an expansion asks whether the DECLARING crate has a feature
//! by that name rather than whether `ingraph` was built with one.
//!
//! So the assumption is not a convention this crate could relax — it is what makes an emitted path
//! resolve at all, and `ingraph`'s own feature table states it as `derive = […, "runtime"]`. A
//! consumer taking the attributes as `ingraph::record` inherits the tiers with the word.
//!
//! A consumer taking them as `ingraph_derive::record` — which is this crate's own fixture corpus,
//! and the form a test uses when the MACRO rather than the re-export is its subject — is outside
//! that implication and names `runtime` on its own `ingraph` dependency. Without it an expansion is
//! `E0433` at the first shelf path it writes, which is a resolution failure rather than a missing
//! impl.
//!
//! Below the derives sits a small PARSING LAYER the whole crate shares — [`errors`] for reporting
//! every violation rather than the first, [`attribute`] for the `#[ingraph(…)]` grammar's
//! structure, [`value`] for typed option values, [`column`] for what an emitted column may be
//! called. None of it knows what a record is; `Record` is its first consumer, and the derives
//! that follow are why it is separate.
//!
//! The crate is a SHELL: [`parse`] turns the compiler's tokens into an
//! [`RecordModel`](ingraph_codegen::model::RecordModel) and checks every rule, and
//! `ingraph-codegen` turns that model back into tokens. Neither half needs the other's machinery,
//! which is what lets a manifest reach the same emitter later.

use ingraph_codegen::{
  error::{ErrorModel, ErrorRoad},
  model::RecordModel,
};

mod aggregate;
mod alias;
mod attribute;
mod column;
mod construct;
mod delegate;
mod r#enum;
mod error;
mod errors;
mod fields;
mod flags;
mod graph;
mod host;
mod id;
mod index;
mod interface;
mod journal;
mod members;
mod mutation;
mod newtype;
mod parse;
mod remote;
mod resource;
mod search;
mod source;
mod standalone;
mod suggest;
mod tower;
mod union;
mod value;
mod wire;

#[cfg(test)]
mod fed;
#[cfg(test)]
mod indexed_tests;
#[cfg(test)]
mod locate_absence_tests;
#[cfg(test)]
mod locate_full_form_tests;
#[cfg(test)]
mod locate_required_tests;
#[cfg(test)]
mod locate_tests;
#[cfg(test)]
mod near_miss_tests;
#[cfg(test)]
mod notified;
#[cfg(test)]
mod page_kind_tests;
#[cfg(test)]
mod page_name_tests;
#[cfg(test)]
mod plural_tests;
#[cfg(test)]
mod skip_tests;
#[cfg(test)]
mod sortable_reseat_tests;
#[cfg(test)]
mod sortable_tests;
#[cfg(test)]
mod tests;

/// Declare a RECORD — an entity holding rows, in the databases its STORE WORDS name.
///
/// # Attributes
///
/// The FIELD markers:
///
/// - `#[ingraph(id)]` on exactly one field — the record's own identity, and the key's last column.
/// - `#[ingraph(copy)]` on any field — its type is cheap enough to hand back by value.
/// - `#[ingraph(key(rename = "…"))]` / `#[ingraph(lineage(rename = "…"))]` — what this field's
///   column is called in that ONE emitted type. Scoped, because the key's columns become the
///   record table's and the lineage's become the degraded table's, and two tables may name a
///   column differently. A bare `rename` is refused; so is a scope that has no column for the
///   field.
///
/// One attribute may carry several: `#[ingraph(id, copy)]`. None may be repeated.
///
/// The macro's ARGUMENTS are one block per emitted type, options inside:
///
/// - `lineage(fields(a, b, …), rename = "Name")` — the fields holding the path from the root, in
///   ROOT-FIRST order, and what the emitted type is called. Omit the whole block for a root.
/// - `key(rename = "Name")` — the key type's options. It has no `fields`: `key = lineage ⊕ id` is
///   a law, not something a declaration restates.
/// - `implements(<Interface>, …)` — the INTERFACES this record is a member of. It is the AGREEMENT
///   half of a membership: an interface's own declaration names its members and cannot prove one
///   consented, the two derives being unable to see each other, so this word emits
///   `impl Implements<Interface>` and the interface's expansion asserts it. A member-side column
///   rename — `implements(<Interface>(<field> = <column>))` — is recognised and refused: what reads
///   one is the interface's row equation, which needs the column as an ident.
/// - `locate(<word> = "path::To::Family", …)` — the ARTIFACT FAMILIES this record answers an
///   address for. `derived(…)`'s reverse-container sibling and its mirror image: a reverse position
///   names a record that points BACK through a `ref`, and an artifact position names an
///   `#[ingraph::blob]` node DERIVED FROM this one's messages. The LEFT side is the author's own
///   domain word — `thumb`, `cover`, `poster` — and it is the name the wire field takes; the right
///   is the path to the family's TYPE, which is where its slot, its store and how its addresses end
///   all live. The word is on THIS record because the field lands on THIS record's output object,
///   and a second `#[Object]` block written by the family's own macro is `E0119` three times over.
///   A position's FULL FORM — `<word>(family = "path::To::Family", data, required)` — carries the
///   two words the shorthand has nowhere to put: `data`, which ASKS for a second field holding the
///   bytes inline (the family's own `data` PERMITS them), and `required`, the author's signature
///   that publishes the address as `BlobLocation!` rather than `BlobLocation`. The ask takes the
///   same signature at its own grain — `data(rename = "…", required)` — and each word promotes only
///   its own field. Both are one-way: nullable is what not writing one means, and it is the default
///   because an artifact is written asynchronously after the entity exists.
/// - `crate = "path::to::ingraph"` — TOP-LEVEL, since it governs every emission rather than one
///   type. Where `ingraph` itself lives, for a re-export shim or a renamed dependency. Defaults to
///   `::ingraph`.
///
/// A `rename` is a string parsed into an identifier — the same shape as `crate`'s string parsed
/// into a path — which is what keeps a raw identifier spellable. Without one, a type takes the
/// suffix convention: `<Record>Key` and `<Record>Lineage`.
///
/// There is no flat shorthand: `lineage(a, b)` is refused. Two grammars would mean two parse
/// paths, two error surfaces, and a real reading ambiguity the day a struct has a field called
/// `fields`.
///
/// Unmarked fields — data, forward `Option<_>` FKs, `Vec<_>` reverse lookups — are ignored
/// entirely. Lineage is never inferred from a field's name: `video_id` is a PARENT on a video's
/// track and a CHILD on the media, and only the declaration knows which.
///
/// # A record's storage is its STORE WORDS, bare at the head, and nothing else
///
/// `#[ingraph::record(sqlite, postgres(schema = "public"))]`. They sat inside a `persist(…)` wrapper
/// and they do not any more, and the principle is what moved them: storage is a record's ESSENCE —
/// a record IS rows, which is the whole of what separates it from an [`entity`] — and an essence
/// sits bare where an OPTIONAL axis takes a block. `graphql(…)` is optional and keeps its
/// parentheses. Each store word's own entries are unchanged and still inside it; the unwrap took one
/// layer off the outside and moved nothing in.
///
/// A record naming NO store is refused, and the refusal names both exits: name one, or declare it an
/// [`entity`], which is this same declaration without the rows.
///
/// ONE NODE HOLDS ONE STORAGE, so the MACRO IS the storage declaration: `Record` declares rows, and
/// an index over those rows or a family of artifacts beside them is a second storage and therefore a
/// node of its own — a `Fulltext`, `Vector` or `Blob` derive on a type that subscribes to this record
/// and shares its key, carrying no `id` because the key is not its to mint.
///
/// So `fulltext(…)`, `vector(…)` and `blob(…)` are refused, at the block and at the field marker
/// alike, and each refusal is the MIGRATION: it names the macro the declaration belongs to and
/// carries what the block carried — a full-text conversion renders a field into one engine's
/// document, `element` and `filter` describe embeddings rather than rows, and an `extension` is part
/// of the address a blob node's key renders. Every one of those describes the other node, which is
/// why none of them travels alone.
///
/// A `Vec<u8>` COLUMN is none of this and stays exactly where it was: `#[ingraph(bytes)]` is a value
/// in this record's own row, one word away from the marker that left.
///
/// # A record's data fields ARE its row, and `skip` is the way out
///
/// Participation used to be a per-field marker — a field wearing `persist` became a column and a
/// field without one did not — and it is the DEFAULT now. A record IS rows; its data fields are the
/// row unless they declare otherwise, which is what `#[ingraph(skip)]` says. Identity is unskippable
/// on both axes, so a record's `id` and every lineage step are columns by construction.
///
/// `persist(…)` survives on a field as what it always ALSO was: the REFINEMENT. `rename = "…"`,
/// `sortable`, and each database's own `type`, `from`, `into`, `indexed`, `unique`, `copy`, `edge`
/// and `flatten` all keep their seats. What is gone is the bare word, which would now say
/// nothing — and it is refused rather than ignored, because silence and a word that means silence
/// are the same declaration and one of them costs the next reader a lookup.
///
/// The LABEL follows the same posture. It is an override where meanings multiply — `Vec<u8>` as
/// bytes or as a list, a set against a sequence — and a column that writes none is read through
/// `<T as DefaultMarker>::Marker`, the inference that keeps the common case free of annotation. A
/// type with no row there is `E0277` NAMING that type; a type NO dialect can hold is ENGINE-RESIDENT
/// and wears `skip`, which `Carrier`'s own refusal says in as many words.
///
/// # The names a statement MINTS are the declaration's too — `alias(…)`, per database
///
/// A nested relation renames its row source per level, so the engine mints one name per depth beside
/// each row's address. Both halves of that mint are a database block's to move:
///
/// ```ignore
/// #[ingraph::record(
///   sqlite(alias(prefix = "__mine", depth = 16)),   // each db independent
///   postgres(alias(depth = 12)),                    // defaults are `__ig` and 8
/// )]
/// ```
///
/// PER DATABASE, because the emitted table already is: `ALIASES` rides one `SqlQuery<Db>` impl, so a
/// record stored in two databases carries two of them. The user story is per database as well — one
/// deployment's schema already holds real tables under `__ig`, and the others do not, so the override
/// belongs on that database and nowhere else.
///
/// `prefix` must lead `__`, because the prefix is FENCED as well as minted in: every declared column
/// and table name inside it stops being spellable, and a bare word would confiscate a namespace this
/// schema's own author is using. The fence holds the UNION of every declared prefix PLUS `__ig`
/// wherever any database still defaults — fields are the DOMAIN's, and a column collides in whichever
/// table would have minted over it. A record that overrode every one of its databases has handed
/// `__ig*` back.
///
/// `depth` is the alias table's LENGTH, so eight is a DEFAULT rather than a wall: a filter nesting
/// deeper says so once and the engine's refusal — which reports the array's own length — moves with
/// it. `depth = 0` is refused, an alias array with no depths aliasing nothing.
///
/// The progress ledger has no block either, for a different reason: there is nothing left for one to
/// say. It would name DATABASES alone, and it lives where the row write does — its control tables
/// live in that engine's pool — so its hosts are the databases the store words already name. Existence
/// is derived too: a ledger certifies the unit's close, which every stored record has. Writing
/// `progress(…)` is refused by that reason.
///
/// # A collection has no null state
///
/// `list(…)` and `set(…)` are the two words that put a field in a COLLECTION POSITION, and a
/// collection has no null state: an `Option` around one declares the
/// COLLECTION, and empty and absent are ONE state in both directions. So such a field resolves its
/// marker, its filter and its comparison exactly as the same field declared bare would — no null
/// test on its wire face, and no `Nullable` wrapper anywhere below it. *Is it empty* is asked as
/// `count: { eq: 0 }`, which is a question every backend answers alike. polarsync's schema settles
/// the same question the same way, translating an `Option<Vec<T>>` field to `Vec<T>`.
///
/// It is a ruling about what is DECLARABLE rather than a convenience. Storage keeps one observable
/// for a collection holding nothing — an edge table with no rows, an array column with no elements —
/// where the Rust type spells two, and a distinction the storage cannot keep must not be spellable
/// as though it could. Under the two-state reading the null test rendered against the PARENT table,
/// which has no such column; under this one there is no null test to render.
///
/// The normalisation the ruling implies — an empty collection written as absent, an absent one read
/// back as empty — belongs to the write and read paths, and rides the storage and query eras with
/// the rest of them.
///
/// **The ruling holds for a column naming NO word, and the two paths reach it differently** — which
/// is where it has to be decided rather than a duplication. A macro holds tokens, so `Option<Vec<u8>>`
/// and `Option<Vec<Tag>>` are one shape here and only a declaration can say which is a collection:
/// the WORD is what this layer can read, so the word is what this layer routes. A column naming none
/// is routed one layer down instead, by its TYPE — `ingraph`'s blanket over `Option<T>` asks
/// `Marker::UnderOption` what an `Option` of the inferred reading is, and the FAMILY answers. A
/// collection answers with itself, so an unmarked `Option<Vec<Tag>>` resolves as the bare `Vec<Tag>`
/// beside it does; a `Vec<u8>` is a blob and a blob is a value that can be absent, so it keeps the
/// null test.
///
/// Neither path can reach the other's answer, and a column that takes both — a word over a type whose
/// inference agrees — resolves alike either way.
///
/// The `Option` is taken off the type the marker is applied TO, so an alias hiding it
/// (`type MaybeTags = Option<Vec<String>>`) is refused at the declaration — `MaybeTags:
/// ListFilterMarker` is unsatisfied — rather than quietly resolving to the wrapped filter. An alias
/// carrying no word is not refused: the inference reads the TYPE, and an alias is transparent there.
///
/// # Expansion
///
/// `Foo` with lineage `(a, b)` and id `i` expands to a flat `FooKey { a, b, i }` and a
/// `FooLineage { a, b }`, each deriving `Debug`, `Clone`, `PartialEq`, `Eq` and `Hash`. A root
/// record gets its `FooKey` alone — no `FooLineage` type exists for an empty path.
///
/// Both types are exactly as visible as `Foo` — a private record's key stays private rather than
/// leaking into its crate's public API — and both are fully documented, so a crate that denies
/// `missing_docs` is not handed a type it cannot edit to satisfy the lint.
///
/// The RECORD gets an inherent impl too — an accessor family for every field it declares, and
/// mutators for the ones that do not bear identity. Its `#[ingraph(id)]` field and every lineage
/// step are set at construction, so they get getters only. There is **no generated constructor**:
/// a real aggregate has twenty-odd fields, and the application hand-writes a validating one the
/// macro cannot replicate.
///
/// A field is handed out by the shape of its written type — `Vec<T>` as `&[T]` under an `x_slice`
/// name, `Option<T>` as `Option<&T>`, anything else as `&T`. (Recognised syntactically: a type
/// alias for either takes the plain borrow.)
///
/// The emitted key types' FIELDS are private, and each gets one inherent impl holding a positional
/// `const fn new` that takes the columns in key order, then one family per column:
///
/// | column | accessors | mutators |
/// |---|---|---|
/// | plain | `const fn x_ref(&self) -> &T` | `fn set_x(&mut self, T) -> &mut Self` · `fn with_x(mut self, T) -> Self` |
/// | `#[ingraph(copy)]` | the same `x_ref`, **plus** `const fn x(&self) -> T` | the same pair, both `const` |
///
/// `with_*` is `#[must_use]`: it returns the change rather than applying it. There is no builder
/// and no `Default` — a key has no invariants to guard, and a default key is a nil address.
///
/// The marker is ADDITIVE: it adds `x()` and renames nothing, so turning it on or off never breaks
/// a caller that was borrowing through `x_ref()`.
///
/// Each emitted type also gets `From<Record>`, which moves its columns out, and `From<&Record>`,
/// which clones them — two so the cost is visible at the call site.
///
/// The impls sit inside one anonymous `const _: () = { … };` per record, which changes nothing
/// about reaching them; the structs stay at top level. The FRAMEWORK traits an expansion writes are
/// the SETTLED ones — the entity binding on every record, each stored database's comparison
/// lowering, and the crossing from a declaration's filter where it has one; a trait still moving is
/// not named.
///
/// A column's name — the field's own, or its scoped rename — may not take the framework's
/// `__name__` shape, which is reserved for the columns the framework adds to a table.
///
/// Nor may two columns of ONE emitted type resolve to one METHOD name. A column reaches an
/// accessor or a mutator through a derived shape, so `x` beside a `copy` `set_x` gives that type
/// two `set_x`, and a `copy` column called `new` gives an emitted key a second constructor. Both
/// are duplicate definitions inside the expansion, at a span the declaration cannot edit, so they
/// are refused here instead — with the column named. Near misses are not refused: `new_thing`,
/// `set` and `x_reference` derive nothing anything else derives, and an unmarked `new` reaches
/// `new_ref` rather than the constructor.
///
/// The record must be a concrete struct with named fields. Generic records are refused: a key
/// column's type is read straight off the declaration, and a type parameter has none until it is
/// substituted.
///
/// ```ignore
/// #[ingraph::record(
///   sqlite,
///   lineage(fields(media_id, video_id), rename = "TrackScope"),
///   key(rename = "TrackAddress"),
/// )]
/// pub struct VideoTrack {
///   #[ingraph(id)]
///   id: Uuid7,
///   #[ingraph(copy, lineage(rename = "media"))]
///   media_id: Uuid7,
///   #[ingraph(key(rename = "video"))]
///   video_id: Uuid7,
///   bit_rate: u64,
/// }
/// // => pub struct TrackAddress { media_id: Uuid7, video: Uuid7, id: Uuid7 }
/// //    with new(media_id, video, id),
/// //         media_id() -> Uuid7 · media_id_ref() -> &Uuid7 · const set_media_id · const with_media_id
/// //         video_ref() -> &Uuid7 · set_video · with_video
/// //         id_ref() -> &Uuid7 · set_id · with_id
/// //    and From<VideoTrack> / From<&VideoTrack>
/// // => pub struct TrackScope   { media: Uuid7, video_id: Uuid7 }   (the same, without the id)
/// ```
///
/// # `remote = "path::To::Type"` — the WRAPPER mode
///
/// The one word in this grammar that changes what the DECLARATION IS rather than adding a fact
/// beside it. Under it the fields written below are a MANIFEST — the shape of a type another crate
/// owns, restated so this framework can read it — and the item the compiler sees is replaced:
///
/// ```ignore
/// #[ingraph::record(remote = "upstream::Tick", sqlite)]
/// #[derive(Debug, Clone, PartialEq, Eq)]
/// pub struct Tick {
///   #[ingraph(id)]
///   id: i64,
///   #[ingraph(copy)]
///   depth: u16,
/// }
/// // => #[repr(transparent)] pub struct Tick(upstream::Tick);
/// ```
///
/// The orphan rule is why it exists: a type another crate owns cannot be given this framework's
/// faces where it is declared, and a wrapper is the position where it can. The same word is
/// admitted on [`entity`], which is the rung to take for a type with no rows behind it.
///
/// **Every face is unchanged.** A manifest column carries a name, a type, a projection and its
/// markers exactly as a declared one does, so the key, the lineage, the row, the filter, the
/// comparison, the order-by and the wire face are the ones written above — including this record's
/// store words, `key(…)`, `lineage(…)` and every field marker. No new vocabulary is added.
///
/// **What moves is two seams.** A column is READ through the remote's own accessor, crossed by
/// `Into`; and a row is RAISED through the remote's own constructor. So the declaration is a claim
/// about that type's API, and every part of it is discharged by the compiler at the manifest entry
/// that made it — no accessor is `E0599` at the field, an unreachable type is `E0277` at the field
/// carrying this device's own sentence, and an identity column handed back by value is `E0308`
/// there.
///
/// **What is emitted beside the faces:** `AsRef`/`AsMut`, `Deref`/`DerefMut` and
/// `Borrow`/`BorrowMut` over the wrapped type — all of them `&self.0`, which is why
/// `#[repr(transparent)]` is the macro's own and a hand-written `#[repr(…)]` is refused — `From` in
/// both directions, and one reader per manifest field. `Deref` is the method inheritance: every
/// method the wrapped type has is reachable through it, with nothing to keep in step.
///
/// **Readers are by value for data and by reference for identity**, and the asymmetry is forced:
/// `Identifiable::id_ref` hands an id back BORROWED, so an identity column has to be reachable as a
/// reference. There are no mutators — a remote's fields are its own — and no `const` reader, a
/// foreign accessor not being this macro's to declare `const`.
///
/// **The hydration builder** is `Remote::new(<the required seats>).with_<optional>(…)`, the split
/// being `#[ingraph(optional)]`'s: that word already says a column has an empty state, which is
/// what an options type's optional seat is. A remote that keeps no such family names its own raise
/// instead — `sqlite(into = "path::to::fn")` replaces the generated body outright, and the read
/// side is unaffected because accessors are all it needs.
///
/// **Two things to know before writing one.** The attribute must sit ABOVE any `#[derive(…)]`: a
/// derive written first expands against the manifest, and its impls then name fields the rewrite
/// deleted. And a STORED wrapper needs the bridge in BOTH directions, where an entity needs one —
/// the write leg crosses a column out and the raise crosses it back in.
///
/// **Refusals of its own:** a hand-written `#[repr(…)]`; a manifest field carrying any attribute
/// but a doc comment, which migrates to that field's reader; `cfg`/`cfg_attr` on a manifest field,
/// refused with its reason until the models a field's generated family is built from carry a seat
/// for a condition; the word twice; the word on an [`operator`], which publishes no address to
/// wrap; and the word beside a fan-in, whose ancestry is a field this macro mints and a wrapper has
/// no room for.
#[proc_macro_attribute]
pub fn record(
  args: proc_macro::TokenStream,
  item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
  node(args, item, ingraph_codegen::model::NodeKind::Record)
}

/// Declare an OPERATOR — a graph node that subscribes, computes, emits, and owns NO storage.
///
/// An operator subscribes, computes and emits. It is the BASE of the node family and every storage
/// derive is it plus one store, which is why this one is spelled by what it does not have: no
/// a store word, and none of the three blocks an index or an artifact family would take.
///
/// ```ignore
/// #[ingraph::operator(lineage(fields(media_id)))]
/// pub struct SpeakerTurn {
///   #[ingraph(id)]
///   id: Uuid7,
///   #[ingraph(copy)]
///   media_id: Uuid7,
///   speaker: String,
/// }
/// ```
///
/// # What it shares with [`Record`], and where it stops
///
/// Everything about IDENTITY, verbatim: `lineage(fields(…), rename = "…")`, `key(rename = "…")`,
/// the `id` and `copy` field markers, the scoped renames, the `*Key` and `*Lineage` types with
/// their accessor families, the entity binding and `implements(…)`. A node's key is a node's key
/// whether or not anything stores it, and an operator's downstream extends it exactly as a
/// record's does.
///
/// What stops at the storage line stops for one reason: an operator has no rows. So a store word
/// is refused — naming `Record` as the declaration a node whose messages land in a database takes
/// — and with the rows go the row types, the comparisons, the order-by and the wire face, none of
/// which this expansion writes because a wire field with no stored column cannot be populated by a
/// read. `fulltext(…)`, `vector(…)` and `blob(…)` are refused here for the reason they are refused
/// on a record: each is a second node's declaration, and the MACRO IS the storage declaration.
///
/// The MARKER a storage node mints is the other half of that law, and an operator mints none: with
/// nothing to hold, it has no second storage to make unspellable.
///
/// # `subscribe = "path::To::Upstream"` — the edge
///
/// The node whose messages drive this one, spelled as a type path in a STRING, which is this
/// grammar's rule for every type it names. It is not stringly typed: the macro resolves nothing,
/// because the upstream is another declaration's and two derives cannot see each other. The path is
/// EMITTED under a bound that says what a subscribe target has to be, and the compiler resolves it
/// there — so a path naming nothing is `E0412` and a path naming something that is not a node is
/// `E0277`, both landing at the string the author wrote.
///
/// One entry names ONE upstream, which is the short form. A node that draws from several writes the
/// CONTAINER instead, and both spellings on one node are refused: a node has one fan-in.
///
/// # `subscribe(upstream(…), …)` — the fan-in
///
/// ```ignore
/// #[ingraph::operator(
///   subscribe(
///     upstream(node = "media::Frame", key),            // THE keyed group
///     upstream(node = "asr::Segment", key),
///     upstream(node = "media::Scene"),                 // an independent flow
///     upstream(node = "vision::Detector", out = "Boxes"),
///   ),
/// )]
/// ```
///
/// Three words per entry. `node = "…"` is the edge, spelled as the short form spells it. `key` says
/// this upstream is JOINED by key before the body sees it — any number of entries carry it and they
/// are ONE group, because `key` joins the group rather than opening one. `out = "<Variant>"` says
/// which product of a multi-product upstream this edge carries, and is QUOTED: it REFERS to an arm
/// of that upstream's own vocabulary, and this grammar writes every reference in a string.
///
/// What the container BUYS is a type: `<Node>In`, one variant per flow — `Paired(…)` carrying the
/// whole keyed group, and one per independent source, named by the upstream's own last segment or
/// by the product where `out = "…"` named one. Two edges that would take one name are refused at the
/// declaration. A container with ONE straight entry emits no type at all, because one upstream is
/// one message and an enum around it would be a wrapper with one arm.
///
/// The PAIRING RUNTIME is not built. `Paired` names the group and the driver's intake does not yet
/// assemble one, which is stated on the emitted type itself.
///
/// # `emits = "A"` / `emits = ["A", "B"]` — the products
///
/// SELF-DECLARED, because two derives cannot see each other: a node's downstream cannot tell it
/// what it produces, and a subscription is a CONNECTION rather than a declaration. Naming several
/// emits the sum `<Node>Out`, the vocabulary `<Node>OutKind` identifying its arms, and
/// `<Node>Downstream` — one out-edge slot per product, whose emptiness IS the connection state a
/// body reads through `emitter.wants(<Node>OutKind::A)`.
///
/// Omitting the word says the product is the declared struct, which is what this crate's edges have
/// always moved. Naming ONE names that one instead. Either way the node states it in a row a
/// downstream's `In` projects through, so an edge's type is the upstream's word rather than a guess.
///
/// # `stream` — the OTHER PAIR, for a fan-out that grows with the input
///
/// ```ignore
/// #[ingraph::operator(stream, subscribe(upstream(node = "media::File")), emits = ["Packet"])]
/// pub struct Demux { … }
/// ```
///
/// A bare word, and the ONE word this face costs. A declaration that does not write it wears the
/// BUFFERED compute pair — `Operator` / `AsyncOperator`, an `accept` per delivery whose every
/// emission is held in an `Emitter` until the call returns — and this buys the STREAMING one:
/// `StreamOperator` / `AsyncStreamOperator`, one `run` per delivery that streams its outputs through
/// a bounded `Feed` for that delivery's whole life.
///
/// The choice is a question about the FAN-OUT and never about a body's size or its cost. A fan-out
/// BOUNDED in the input — one, a handful, dozens — is the buffered pair; one that GROWS with the
/// input's length — a container demuxed to packets, a 2 GB log chunked into windows — is this one,
/// because millions of emissions held inside ONE call is an out-of-memory abort rather than the
/// dead-letter the failure lane funds. `StreamOperator`'s own docs carry the law in full.
///
/// ## It MULTIPLIES with `async` rather than replacing it, and there is no mode word of its own
///
/// `stream` picks the KIND and `async` picks which HALF of it, so the cells are spelled by the two
/// words a declaration already has:
///
/// | words | the face the body wears |
/// |---|---|
/// | *(none)* | `Operator` |
/// | `async` | `AsyncOperator` |
/// | `stream` | `StreamOperator` |
/// | `stream, async` | `AsyncStreamOperator` |
/// | `autonomous` | `AutonomousOperator` |
/// | `autonomous, async` | `AsyncAutonomousOperator` |
///
/// `autonomous` is the section below and it is `stream`'s own axis rather than a third one: a
/// declaration wears exactly ONE kind, so the two are refused together.
///
/// A stream-specific mode word was refused for the reason every second spelling in this grammar is:
/// the mode vocabulary already exists, and two words on one axis are two authorities for one fact.
/// There is deliberately no `dispatch` word beside `stream` either — a stream-faced delivery is
/// SELF-CONTAINED by the face's own definition, so what the lane does per delivery is DERIVED from
/// the face rather than declared.
///
/// ## What the word buys, and what stays a runtime value
///
/// The expansion states the FACE as a bound, exactly as `async` does: a `stream` declaration whose
/// type carries `Operator` instead is `E0277` with the caret on the word, rather than a mount three
/// expansions away complaining about a trait the author never mentioned. And it states the FACT —
/// `Declared::Pair`, seated at `Streaming` — which is what puts the node at `Blueprint::stream` and
/// `Wiring::lane` rather than at `Blueprint::node` and `Wiring::resident`.
///
/// What the word does NOT carry is the lane's SEATS: how many deliveries the node holds at once, how
/// deep each delivery's feed is cut, and which memory probe a feed policy reads. Those are
/// `StreamOptions` at the launch, because a `FeedPolicy` is a framework-open trait object and an
/// attribute cannot name a value.
///
/// `emits = […]`, `out = "…"`, `subscribe(…)` and the identity words are UNCHANGED beside it: the
/// products a stream node fans out are the same `<Node>Out` / `<Node>OutKind` / `<Node>Downstream`
/// family every other node's are, pruned by the same `Wanted` the buffered face reads.
///
/// ## Its own refusals
///
/// The word twice; the word carrying a value or a block; the word on any declaration but an
/// `operator`, because every other kind publishes an address and the storing ones land rows through
/// a write lane the stream lane does not carry; and the word beside `poll(…)`, which is the buffered
/// pair's — a tick is one call against the node's own value, which the driver LENDS for that call,
/// and a stream-faced node's bodies are the lane's warm set, each owned by a delivery's run for that
/// delivery's whole life.
///
/// # `autonomous` — THE THIRD KIND, for a node that has to own its own loop
///
/// ```ignore
/// #[ingraph::operator(autonomous, subscribe(upstream(node = "media::Packet")), emits = ["Frame"])]
/// pub struct Decode { … }
/// ```
///
/// A bare word, `stream`'s own axis, and the whole of what it buys is that the NODE runs the loop:
/// `fn run(self, ctx: Context, upstreams: Upstreams<In>, downstream: Downstream<Out>) -> Result<Fin,
/// Error>`, once, for the node's whole life. Select order, arm priority, intake gating, batching,
/// ack timing and internal workers are all inside that call.
///
/// ## Which kind a body is, in one sentence each
///
/// | the body | its word | the sentence |
/// |---|---|---|
/// | bounded fan-out, a simple serial unit | *(none)* | the framework drives every part of it |
/// | one delivery is one whole life where the per-delivery parallelism AND the fate bookkeeping are the FRAMEWORK's | `stream` | a demux: the lane holds the warm set, the admission bound and the dead-letter |
/// | the node takes the wheel and KEEPS THE BOOKS | `autonomous` | a decoder, a resampler, a conform, a heavy embedder |
///
/// The three are PEERS. What sends a body to the third row is needing something the first row's
/// protocol has no place for — reading one upstream before another, refusing to read one at all
/// this pass, holding an ack until a worker has flushed — and `Operator`'s protocol was not widened
/// to fit them, on the count that decides it: 105 `accept` bodies in this tree.
///
/// ## `self` BY VALUE, and the lifecycle that follows from it
///
/// `run` takes the value rather than borrowing it, which is `Source::run`'s shape and its reason:
/// there is nothing after it. The dividend is the PROLOGUE — a body that owns `self` can take
/// itself apart INTO the workers it spawns, where a `&mut self` body could only clone or lock.
///
/// The phases divide with no ambiguity, and `AutonomousOperator`'s own docs carry the table:
/// CONSTRUCTION is pure data (no thread, no channel — a built-and-unignited node holds nothing
/// live, so dropping one in its slot is a no-op); the mount holds the value in its slot and MOVES
/// it onto the hosting thread at ignition; STARTUP is `run`'s prologue; TEARDOWN is `run`'s
/// epilogue and is explicit — close the in-queues, let the workers drain their session tails, join
/// them, then answer the `Fin` — with `Drop` as the idempotent backstop that keeps a panic-unwind
/// join from deadlocking. `Err` drains the same way before it is dead-lettered, and a respawn is a
/// factory rebuild rather than a reuse of the husk.
///
/// ## What the word buys, and what stays inside `run`
///
/// The expansion states the FACE as a bound, exactly as `stream` does: an `autonomous` declaration
/// whose type carries `Operator` instead is `E0277` with the caret on the word. And it states the
/// FACT — `Declared::Pair`, seated at `Autonomous` — which is what puts the node at
/// `Blueprint::autonomous` and `Wiring::autonomous`, and what makes a `#[ingraph::graph]` root
/// mount one through the same ONE line per field it already emitted.
///
/// What the word does NOT carry is anything about the node's own machinery. How many workers it
/// keeps, how it routes among them, how deep its own queues are cut: all of it is inside `run`,
/// because the framework knows WHAT nodes exist and HOW they connect and nothing else.
///
/// ## Its own refusals
///
/// The word twice; the word carrying a value or a block; the word on any declaration but an
/// `operator`, for `stream`'s reason one kind over — an autonomous mount carries no write lane; and
/// the word beside `stream`, because the two are values of ONE axis and a declaration wears exactly
/// one kind.
///
/// # `poll(<name>, every = "10m")` — the node's OWN clock
///
/// ```ignore
/// #[ingraph::operator(
///   subscribe(upstream(node = "media::Frame")),
///   poll(orphans, every = "10m", light, async(inline)),                       // reap fast
///   poll(compaction, cron = "0 3 * * *", tz = "America/New_York", light, async(inline)),
///                                                                 // compact at three
/// )]
/// ```
///
/// BESIDE the container and never inside it, because a poll source is not an upstream: a tick is a
/// WAKE. It moves no message, it enters no `In` enum, and what the node does with it is read
/// through the handles it already holds. That is what makes a reaper, a compactor and a
/// stuck-watermark healer ordinary declared nodes rather than a side channel beside the graph.
///
/// The name is MINTED and therefore bare — it refers to nothing, and it exists so a body can tell
/// one clock's tick from another's. What it buys is `<Node>Due`, one variant per entry: a tick
/// arrives carrying a POSITION, the emitted vocabulary translates the position into the word the
/// declaration wrote, and reordering the entries therefore changes no body. The third of the
/// rename-proof identity types, beside `<Node>In` and `<Node>Out`.
///
/// Exactly ONE of `every = "…"` and `cron = "…"` per entry. `every` is an interval in the
/// framework's one duration grammar, and it must be positive — a poll that fires as fast as the
/// machine allows is a spin, refused by name. `cron` is the classic five fields, checked AT
/// EXPANSION with the offending string quoted; it is wall-clock, so it reads in the system's zone
/// unless `tz = "<IANA>"` names another. `tz` beside `every` is refused: an interval counts elapsed
/// time and never asks what o'clock it is.
///
/// # `block` · `spawn` · `rayon` · `async(inline)` · `async(spawn)` — WHERE the tick runs
///
/// MANDATORY on every entry, with no default. A role is DECLARED rather than inferred, and this is
/// the campaign's own law applied to execution: what a tick costs the driver is the difference
/// between a body it awaits, a body it blocks on, and a body it hands to an executor, and none of
/// the three is the obvious one to assume for a declaration that did not say. `async(inline)` is
/// what every entry did before the word existed.
///
/// The two INLINE words run the body where the driver is and carry its answer back to the taps; the
/// three DETACHED ones hand it over and answer *dispatched*, so nothing about the outcome is
/// claimed. `spawn` and `rayon` name the two SHIPPED blocking executors and `async(spawn)` names
/// whichever `AsyncSpawn` the deployment installed — all three are seams, so a third-party pool is
/// named at `<Node>Polling::new` and costs no vocabulary word here.
///
/// A detached word on a `light` entry is refused: its body would be the node's own value, which the
/// driver lends per tick and cannot give away.
///
/// `concurrent`, bare, lifts the AT-MOST-ONE-IN-FLIGHT default that `spawn` and `rayon` carry —
/// threads are expensive and an unbounded pile-up is the failure mode a default has to stand
/// against. A tick skipped by that default is not silent: it becomes `Observation::Lapped` at info.
/// The word on an inline mode or on `async(spawn)` is a teaching refusal.
///
/// # `handler = "app::PromScraper"` · `light` — WHO runs the tick
///
/// MANDATORY on every entry, exactly one of the two, and there is no default for the mode word's
/// reason: who runs a tick is DECLARED rather than inferred. The older spelling — neither word,
/// meaning the sweep method — is gone, because a declaration that answers *who runs this* by saying
/// nothing answers it only for a reader who already knows the grammar.
///
/// `handler` is refer-quoted, as `write = "…"` is, and the mode word decides which trait the
/// mount's bound demands: `AsyncTick` for the async words, `Tick` for the sync ones, so a wrong
/// mount is `E0277` at the declaration. `light` is BARE, because it refers to nothing — it names
/// the road this framework already owns, the node's own `<Node>Sweeps` method on the operator the
/// driver lends for the call.
///
/// It is the PRESENCE SPLIT's only input. An entry that mounted routes to that citizen and has no
/// `<Node>Sweeps` method; a `light` entry is one. A node whose every clock mounted a citizen emits
/// no sweep trait at all — and a node with clocks always emits `<Node>Polling`, sealed and empty
/// where nothing was granted and nothing mounted.
///
/// A node may MIX the two freely, and the anchor law is what a mixed node reads: `<Node>Sweeps`
/// carries ONE `Info` and ONE `Error` for the whole node, an inline citizen is bound to that same
/// pair, and where every clock mounted, the FIRST inline citizen anchors it instead (all-detached
/// answers `()` and `Infallible`). So a mixed node's `light` methods speak the CITIZEN's pair, and
/// the idiom is a node-wide vocabulary on the anchor:
///
/// ```ignore
/// enum IndexerInfo { Scraped { rows: usize }, Vacuumed { freed: u64 } }
/// ```
///
/// A poll inbound carries NO ack, structurally — an `ack(…)` word inside `poll(…)` is a named
/// refusal. There is no producer window to release and no cursor to advance, because a tick is not
/// data; the next tick over an idempotent scan is the retry, the lifecycle taps are the
/// observation, and the clock is the throttle. A polling node that PUBLISHES keeps the whole ack
/// protocol as a sender.
///
/// # `upstream(…)` at the TOP level is a different question
///
/// FUSION — several upstreams jointly making one output, one of them designated the key parent, so
/// this node's lineage mirrors that parent's key. The words look like the container's and the
/// question is not: those say how messages ARRIVE, and these say where the identity COMES FROM. An
/// operator whose every field is read out of ONE upstream message is neither: it is a derived index,
/// and the macro for one is [`fulltext`], [`vector`] or [`blob`].
///
/// # `teardown` — the goodbye, opted into
///
/// A bare word, on any node's own attribute. A value a launch constructs is torn down by [`Drop`],
/// which closes a pool, releases a handle and needs nothing said about it — so the word is for the
/// values whose goodbye has to be AWAITED: a flush that must reach a store, a device released
/// politely, a lock removed from a table somebody else will read.
///
/// It carries nothing, because what to say is the `AsyncTeardown` impl's. What the word buys HERE is
/// that the impl is demanded at the declaration: the expansion states the bound, so a type that
/// opted in without one is `E0277` at its own name rather than a launch that starts and then has
/// nothing to say at the end. The chain itself is the launch's — the enrolled goodbyes are said
/// after every party has settled, last enrolled first, and a refusal never interrupts the next one.
///
/// # `attributed` — the root projection, opted into
///
/// A bare word, on any node's own attribute, and on an axis of its own: `stream`, `autonomous` and
/// `async` say what a body IS, and this says what the framework does with what the body EMITS. So
/// it composes with all of them and is refused beside none.
///
/// Without it a node's observations are COUNTER-GRADE — a lifecycle tap sees every station with no
/// content root attached, which is the only thing a node emitting a `String` or a `u64` could
/// honestly offer. With it the launch installs the framework's own `RootProjection<Out>` on this
/// node, and its observations become keyable by `(root, node)`: the root is the emitted output's
/// key FIRST column, read through the `Attributes` impl that output's own declaration emitted
/// beside it.
///
/// It carries nothing, because the projection is that impl rather than anything written here. What
/// the word buys is the SEAT — `Declared::Attribution` — which is the only road the fact has: a
/// graph root's expansion writes one line per field and sees a node's output as a type it can name
/// and cannot test, so whether that output is a declared record has to be stated by the party that
/// knows. An output NO record declared has no such impl, and the mount is where that is refused, by
/// `E0277` naming the payload.
///
/// An attribution that carries STATE — a journal writer, a queue, a live handle — is not this
/// word's road: it is a VALUE, no attribute can name one, and it is attached at the launch through
/// [`Resident::attributing`](ingraph::Resident::attributing) instead.
///
/// # `options = "path::To::Knobs"` — what a deployment's section for this node deserializes into
///
/// A referring word, so it is written QUOTED like every other in this grammar: it names a type this
/// declaration did not mint. ABSENT means `()` — a node with no knobs, which is most of them, writes
/// nothing — and the author's [`AsyncConstructor`](trait@ingraph::AsyncConstructor) still OWNS the
/// type either way. The two are pinned equal by an emitted equation, so a declaration whose word and
/// whose constructor disagree is refused where the launch is written rather than deep inside a walk.
///
/// What it buys is the ROOT's spine: the emitted options can NAME the path a declaration wrote
/// instead of projecting `<Node as AsyncConstructor>::Options`, which put a compile-time demand on
/// every node in a catalog just to spell the type of one section.
///
/// It is on EVERY rung rather than this one — [`entity`], [`record`], [`fields`] and the derived
/// indexes take it in the same words — and it is documented here because an operator is the node
/// family's base and a reader looking for a node's knobs looks at the base first.
///
/// # There is no `receipt = "…"` here — the word is the MESSAGE's
///
/// It used to be. The seat shipped keyed on the CONSUMER — *this node hands back a `SceneId`* — and
/// the subject was wrong: a receipt answers the item that was GIVEN, so every seat on the far end of
/// one edge answers the same question, and two seats over one message could each declare the
/// answer's type and disagree about a question neither of them asked.
///
/// So the word lives on the declarations that MINT a message — [`entity`], [`record`],
/// [`aggregate`] — and an operator writing it is refused by name, with the sentence pointing at
/// those three. An operator computes: it publishes no address, and what goes on its out-edge is its
/// `Operator::Out` rather than itself, so there is no operator value on any wire for a producer to
/// be parked on. See [`entity`], where the word is documented.
///
/// What an operator DOES with a receipt is state one: `Emitter::receipt_of::<Message>(id)` names the
/// message it was delivered, and `Emitter::receipt` takes any value at all for a seat answering with
/// something its message did not declare.
///
/// # The `id` an operator still carries
///
/// Mandatory and singular, exactly as a record's, and the edge does not relax it here. The ruling —
/// *id absent on a subscriber means the upstream's key* — is spent by the DERIVED INDEXES, where the
/// key is carried in a field the macro injects; an operator computes its own fields and keeps its
/// own identity, so `subscribe` alone buys no relaxation. What a node with no `id` would be is
/// [`fulltext`]'s tier, and the whole of it is written there.
#[proc_macro_attribute]
pub fn operator(
  args: proc_macro::TokenStream,
  item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
  node(args, item, ingraph_codegen::model::NodeKind::Operator)
}

/// Mount a JOURNAL — the canonical record of how far each content ROOT got through each node.
///
/// ```ignore
/// #[ingraph::journal(root = "MediaId", sqlite)]
/// pub struct VideoJournal;
/// ```
///
/// A journal of FINAL STATES, keyed `(root, node)`, each entry replaced in place — not an append
/// log. That is the organ's whole semantics, and it is worth stating before anything else because
/// the word invites the other reading: a journal in the everyday sense ACCUMULATES, and this one
/// does not. What is kept is where a root GOT TO through a node, one entry per pair, and the next
/// observation about that pair overwrites the entry rather than adding to a history.
///
/// # The host is a MARKER, and what it mounts is an ORDINARY RECORD
///
/// The declaration is a unit struct whose NAME is the only thing in it the author chooses. What
/// replaces it is a four-column record — an attribute macro owns the item it sits on, which is what
/// makes a one-line mount possible at all — parsed by the same pass [`record`] uses, under the same
/// kind. So the mounted type has the `*Key` type, the accessor family, the per-database row, the
/// comparison lowering, the order-by vocabulary and the keyset cursor every declared record has,
/// **because it is one**: run state stays queryable exactly as anything else a declaration stores.
///
/// | column | type | why |
/// |---|---|---|
/// | `root` | the type `root = "…"` named | one journal table per ROOT FAMILY, and the root is that family |
/// | `node` | `String` | `NodeName`'s storable face |
/// | `station` | `String` | `Station`'s, the framework's own stable word for where a node got to |
/// | `at` | `Timestamp` | the framework's own instant — feature-free, and stored on every backend |
///
/// `root` is the lineage and `node` is the id, so `key = lineage ⊕ id` spells `(root, node)` with
/// nothing declared for it — and the keyed replace that makes an entry the LAST STATE is the
/// ordinary write of that key. Nothing about the journal needed a key of its own.
///
/// The expansion also writes `impl JournalRow<Root>`, which is the SAME trait the hand path
/// implements by hand. `of` maps the four things the framework knows onto the four columns; the
/// `SystemTime` it is handed crosses into `Timestamp` through the fallible conversion, and a
/// `SystemTime` outside that type's ±9999-year range PANICS rather than being rounded — a journal
/// row is durable and is read as *when the node got there*, so a substituted instant would record a
/// moment that never happened.
///
/// # THE HAND PATH REMAINS, and every refusal here points at it
///
/// This word is SUGAR over `JournalRow`, never a replacement. A deployment that wants its own
/// columns — a rendered failure, a refusal's content, a timestamp of its own type — declares an
/// ordinary [`record`] and implements the trait on it, exactly as before, and the two paths are one
/// seam to every writer the framework has.
///
/// # Attributes
///
/// The macro's ARGUMENTS, and there are three:
///
/// - `root = "<Type>"`, **required** — the chain root this journal is keyed by, spelled as a type in
///   a string, which is this grammar's rule for every type it names. Nothing here resolves it: the
///   type is EMITTED, so a path naming nothing is `E0412` at the string the author wrote, and a type
///   no backend can store is the STORABILITY AUDIT's own refusal at the declaration — a root column
///   is an ordinary key column and is judged as one.
/// - the STORE WORDS — where the rows land, passed through to [`record`]'s own grammar VERBATIM.
///   Every one of them means what it means there: the database blocks, `table = "…"`,
///   `rename = "…"` and `alias(…)`, with their refusals. Omit them and the mount lands one rung
///   down, on [`entity`]: the same four columns, the same `(root, node)` key and the same
///   `JournalRow` impl, with no table anywhere — which is the pure-compute journal a deployment
///   lands through a lane of its own.
/// - `crate = "path::to::ingraph"` — where `ingraph` lives, exactly as [`record`]'s. Spent twice
///   here: the row contract names the framework's trait, and the `at` column is declared as the
///   framework's instant.
///
/// A FIELD takes none, there being no field to write.
///
/// # Refusals
///
/// The declaration's SHAPE is the marker: a struct with fields, a tuple struct, an enum, a union and
/// any generic parameter. The field refusal is the teaching one — custom columns are what the hand
/// path is for, and the message says so rather than reporting a shape error.
///
/// A missing `root`. And every other word, by name and in two families. The record's own SHAPE words
/// — `lineage(…)`, `key(…)`, `graphql(…)`, `implements(…)`, `subscribe`, `upstream(…)` — would each
/// decide something CANONICAL has already decided, so each refusal names what decided it and points
/// at the hand path. `fulltext(…)`, `vector(…)` and `blob(…)` are refused for the one-storage law's
/// reason, exactly as a record refuses them: a journal holds rows, and an index over those rows is a
/// node of its own.
#[proc_macro_attribute]
pub fn journal(
  args: proc_macro::TokenStream,
  item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
  let input = syn::parse_macro_input!(item as syn::DeriveInput);
  let arguments = host::options(args.into());
  // THE HOST IS EMITTED WHETHER OR NOT THE DECLARATION IS ACCEPTED, for `node`'s reason — but the
  // host is not the same item in the two cases. Accepted, it is the four-column record the word
  // mounts; REFUSED, it is the author's own marker struct, echoed back unchanged. A refusal may have
  // named no root at all, so there is no column list to mint, and a guess would put fields of an
  // invented type in the author's struct beside the message telling them the struct is wrong.
  match journal::parse(&input, &arguments) {
    Ok(journal) => {
      let host = host::echo(&journal.host);
      let expansion = journal.model.emit();
      quote::quote!(#host #expansion).into()
    }
    Err(refused) => {
      let host = host::echo(&input);
      let refusal = refused.to_compile_error();
      quote::quote!(#host #refusal).into()
    }
  }
}

/// Declare an ENTITY — an identity-bearing node with a wire face and NO rows.
///
/// ```ignore
/// #[ingraph::entity(lineage(fields(media_id)), graphql(async_graphql))]
/// pub struct Keyframe {
///   #[ingraph(id, copy)]
///   id: u32,
///   #[ingraph(copy)]
///   media_id: i64,
///   #[ingraph(skip)]
///   clip: Embedding<f32, 4, Clip>,
/// }
/// ```
///
/// # The LADDER's middle rung
///
/// | tier | word | has | lacks |
/// |---|---|---|---|
/// | field fragment | [`fields`] | shared fields, inherited by holders | identity, rows, wire root |
/// | **entity** | **this** | id · key · lineage · accessors · a wire face · election-projectable | rows |
/// | record | [`record`] | everything above **plus rows** | — |
///
/// It shares EVERYTHING about identity with [`record`], verbatim: `lineage(fields(…), rename = "…")`,
/// `key(rename = "…")`, the `id` and `copy` field markers, the scoped renames, the `*Key` and
/// `*Lineage` types with their accessor families, the entity binding, `implements(…)` and every edge
/// word. What stops at the storage line stops for one reason — an entity has no rows — so a store
/// word is refused, naming [`record`] as the declaration a node whose messages land in a database
/// takes, and with the rows go the row types, the per-database comparisons, the order-by and the
/// query face.
///
/// This is not a new code path. It is the rowless path 22 declarations were already on with no word
/// for it: a `record` that wrote no storage block compiled, emitted its key family and its wire face
/// and stored nothing. That shape now has its own macro, and [`record`] refuses to be it.
///
/// # It is DRESSABLE, and that is the whole of what separates it from [`operator`]
///
/// `graphql(…)` is admitted here and refused on an operator. A dressed entity publishes its ADDRESS,
/// which is what a search declaration over it projects through — a hit's key is
/// `<<<Upstream as Transformer>::Graphql as Graphql>::Output as GraphqlOutput>::Key`, and an
/// undressed upstream binds `Graphql = ()`, for which `Graphql` is not implemented at all. So the
/// KEYS tier of every election over an entity stands on this word.
///
/// What the block may NOT do here is publish a FIELD. A read populates a wire field from a stored
/// column, so a field wearing `graphql` on a rowless declaration is refused by name and told the
/// exit: make it a [`record`]. The block itself still pays for itself — the address is what it
/// publishes.
///
/// # The two-clock wall, and the `keys` word downstream
///
/// A dressed election over an entity mounts the KEYS tier ALONE. The hydrated tier projects
/// `<Upstream as Hydrates>::Db`, which only a record with a queryable row implements, so a search
/// declaration whose upstream is an entity wears `keys` — see [`vector`] and [`fulltext`]. Without
/// the word the demand is written and the compiler answers `E0277` at `upstream(node = "…")`, carrying
/// `Hydrates`' own sentence and both exits.
///
/// # Refusals
///
/// A store word (`sqlite`, `postgres`, `mysql`, `mongo`) and `table = "…"` beside them, each naming
/// [`record`]. A per-field storage word — the `persist(…)` refining block, and `skip`, which is the
/// answer to a question only a record asks. `fulltext(…)`, `vector(…)` and `blob(…)`, for the
/// one-storage law's reason: each is a second node's declaration. And the declaration's own shape,
/// exactly as [`record`]'s.
///
/// # `receipt = "media::SceneId"` — WHAT AN ACKED GIVE OF THIS MESSAGE IS ANSWERED WITH
///
/// ```ignore
/// #[ingraph::entity(receipt = "media::SceneId")]
/// pub struct SceneOpen { /* … */ }
/// ```
///
/// A producer that gave one of these through `Feed::give_acked` is parked on its consumer's answer,
/// and what it is usually parked for is a DURABLE IDENTITY: a seat upserts the row, the natural key
/// it matched keeps the id it already had, and only the seat knows what that id is. The value rides
/// back on the ack, and this word is where the two ends of that ack learn to name the same type.
///
/// **The word is the MESSAGE's and not the consumer's**, which is the ruling this rung is the home
/// of. A receipt answers the item that was GIVEN: one message asks one question, and every seat on
/// the far end of that edge answers the same one. Keyed on the consumer — which is where the seat
/// shipped — two seats over one message each declared the answer's type and could disagree; keyed
/// here there is one declaration and nothing to keep in step. [`record`] and [`aggregate`] take the
/// word on the same terms, being an entity with rows and a record whose rows are a fold; every other
/// kind is refused by name, with the sentence pointing back at these three.
///
/// Refer-quoted, as `options = "…"` and `subscribe = "…"` are: it names a type this declaration did
/// not mint, so nothing here resolves it and the path is emitted verbatim — a path naming nothing is
/// the compiler's refusal AT THE STRING, because `LitStr::parse` respanned the tokens onto the
/// literal. Written once; twice is refused by name.
///
/// ## What it buys, and it is one impl
///
/// `impl Receipts for <Message> { type Receipt = <path>; }`, and with it a producer read that names
/// NOTHING: `feed.give_acked(open)?.receipt()` projects through the impl, because `Acked<M>` carries
/// the message it was opened with. The consumer's own door still names the message —
/// `Emitter::receipt_of::<SceneOpen>(id)` — because an `Emitter<Out>` is typed at what a node
/// produces and carries no trace of what it was handed; a body handing it another type is `E0308` on
/// its own line, where before the two ends met at runtime as `Unreceipted::Mismatched`, on the
/// producer's thread, one edge from the body that caused it.
///
/// ## Silence costs NOTHING, which is why the seat is a sibling
///
/// A message that writes no word gets no impl, no seat and no bound. That is the whole reason
/// `Receipts` is a trait beside everything rather than a member of anything: associated-type defaults
/// are unstable (`E0658`), so a member could not be defaulted, and an undefaulted one would make
/// every declaration in this tree write a line to say it is waited on by nobody.
///
/// Hand-writing the impl is equally legal and equally complete — two roads, one seat — and it is the
/// road a GENERIC message has to take: a message carrying a parameter of its own, whose receipt is
/// that parameter, has no concrete path a quoted word could name and says
/// `impl<S> Receipts for SceneOpen<S> { type Receipt = S; }` instead.
///
/// # `remote = "path::To::Type"` — the WRAPPER mode
///
/// Admitted here on exactly [`record`]'s terms, and this is the rung to take for a type with VALUE
/// semantics: `#[ingraph::entity(remote = "…")]` restates a foreign type's shape as a manifest and
/// replaces the item with `#[repr(transparent)] struct X(Remote);`. The whole mode is documented on
/// [`record`], which is where the two seams and the hydration builder are written; what differs
/// here is only what always differs between the rungs — an entity has no rows, so it has no raise,
/// and the bridge is needed in the READING direction alone.
#[proc_macro_attribute]
pub fn entity(
  args: proc_macro::TokenStream,
  item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
  node(args, item, ingraph_codegen::model::NodeKind::Entity)
}

/// Declare an AGGREGATE — a record whose rows are a declared FOLD over one upstream's rows, one row
/// per group, recomputed WHOLE on every trigger.
///
/// ```ignore
/// #[ingraph::aggregate(
///   upstream(node = "demux::Track"),
///   group(codec = "codec"),
///   measure(count = counting),
///   poll(recount, every = "10m", light),
///   sqlite,
/// )]
/// pub struct CodecCensus {
///   #[ingraph(group)]   codec: Codec,
///   #[ingraph(measure)] count: u64,
/// }
/// ```
///
/// # IT MOUNTS A RECORD, and the row it mounts is the one the declaration wrote
///
/// The columns are the author's, the KEY is the group projection — `key = lineage ⊕ id` over the
/// group columns, minted rather than declared — and the store words, the clock and `graphql(…)` are
/// carried to the RECORD pass verbatim. So an aggregate has the `*Key` type, the per-database rows,
/// the `find_<db>` and `upsert_<db>` doors, the order-by vocabulary, the cursor and the `<Node>Due`
/// clock vocabulary that every declared record has, because it IS one.
///
/// Beside them the expansion writes the one thing a record cannot say: `fold(rows: &[Upstream]) ->
/// Vec<Self>`, one row per group, with each measure's citizen called statically. A trigger's body is
/// then the three calls the two nodes already published — read the upstream's table, fold, upsert
/// each answer — and the keyed replace is what makes running it on every tick safe.
///
/// # It consumes the upstream's TABLE, not its messages
///
/// At-least-once delivery plus keyed replace is what makes this framework's writes safe, and it
/// makes DUPLICATES normal operation: a fan-out clones per edge, a rewind re-delivers the unacked
/// tail, a retry re-sends. No app-visible message id exists to dedup on, so an incremental
/// `count += 1` cannot inherit that safety. A trigger therefore reads the upstream's rows, groups
/// them, folds each group and upserts one row per group — immune to duplicates by construction,
/// self-healing on every tick, and deletion-correct for free.
///
/// # The three parts, and the two words SQL has no room for
///
/// | word | it is | notes |
/// |---|---|---|
/// | `upstream(node = "…")` | the `FROM` | the EDGE alone; a projection here is refused pointing at `group(…)` |
/// | `group(<field> = "<upstream field>")` | the `GROUP BY` | also the projection, and the columns the key is minted from |
/// | `measure(<field> = <fold>)` | the aggregate functions | a shipped fold BARE, your own QUOTED as its type path |
/// | `poll(…)` | the clock | MANDATORY — the trigger is the only thing that writes the rows |
/// | the STORE WORDS, bare | where the rows land | a record's own words, carried to the record pass |
/// | `graphql(…)` | the wire face | optional, and it publishes through the record path |
///
/// # Every field wears EXACTLY ONE role
///
/// `#[ingraph(group)]` says this column keys the folded row; `#[ingraph(measure)]` says a fold fills
/// it. A field wearing neither has no place in the row; a field wearing both would be part of the
/// key that decides which rows it is folded from. Each word is also its head block's, one word at
/// two grains — and the two halves are checked AGAINST each other, so a head and a field that
/// disagree are refused rather than resolved by precedence.
///
/// # Refusals
///
/// A missing `upstream(…)`, a second one (multi-upstream folding wants a by-key intake this
/// framework has not built), a projection entry inside it, a missing or empty `group(…)` or
/// `measure(…)`, one field named twice in either, an entry naming a field this declaration does not
/// have, an entry whose field wears the OTHER role, a marked field no entry names, a missing
/// `poll(…)`, a bare word inside `measure(…)` that names no shipped fold, `#[ingraph(id)]` (the key
/// is the group columns), the other kinds' election markers, the record words this grammar decides
/// for itself (`lineage`, `key`, `subscribe`), the retired `persist(…)` wrapper, the three other
/// storage words, and the declaration's own shape: a non-struct, a positional or unit struct, any
/// generic parameter, and a struct with no field.
#[proc_macro_attribute]
pub fn aggregate(
  args: proc_macro::TokenStream,
  item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
  let input = syn::parse_macro_input!(item as syn::DeriveInput);
  let arguments = host::options(args.into());
  // THE HOST IS EMITTED WHETHER OR NOT THE DECLARATION IS ACCEPTED, for [`node`]'s reason. It is the
  // AUTHOR's item either way, unlike [`journal`]'s: this word mints no column, so the declaration
  // the compiler sees and the one the record pass reads differ in their `#[ingraph(…)]` markers
  // alone — and the echo strips every one of those.
  let host = host::echo(&input);
  let expansion = aggregate::parse(&input, &arguments)
    .and_then(|model| aggregate::mount(&input, model))
    .map_or_else(
      |refused| refused.to_compile_error(),
      |mounted| mounted.emit(),
    );
  quote::quote!(#host #expansion).into()
}

/// Declare a FIELD FRAGMENT — a group of fields several declarations hold, written once.
///
/// ```ignore
/// #[ingraph::fields(record, entity, graphql)]
/// pub struct Dimensions {
///   #[ingraph(copy)]
///   width: u32,
///   #[ingraph(copy)]
///   height: u32,
/// }
/// ```
///
/// # A fragment is HELD, and every absence follows from that
///
/// It is the ladder's bottom rung — 公用字段抽取 — and it is not a node. A holder declares one as an
/// ordinary field, its columns land in the holder's row, and its wire presence is a fragment of the
/// holder's object. So this derive is FAMILY-LESS, and none of the absences is an era rule waiting
/// to lift:
///
/// | absent | because |
/// |---|---|
/// | `Identifiable` | it bears no id — that is what the tier MEANS |
/// | `Transformer` | that face is a key and the two address types beside it |
/// | `Graphql` | a wire face is a queryable ROOT, and a fragment is a fragment |
/// | every storage | its columns are the HOLDER's row |
///
/// A group of fields that does bear an identity is an [`entity`], and one that holds rows besides is
/// a [`record`]. Both refusals name both rungs, so a migrating author reads which one they wanted.
///
/// # The word was `entity`, and the rename is the ladder's
///
/// The tier's own doc said *no stable identity is what the tier means* while `entity` names an
/// identity-bearing thing everywhere else in this framework. The code moved WHOLE; only the word
/// changed, and `entity` now names the rung it always described.
///
/// # ACTIVATION, which is required
///
/// A fragment is HELD, so what it has to ANSWER is whatever the holding kind asks — and the kinds
/// ask different things. Three words say who asks, and a declaration that writes none of them is a
/// named refusal:
///
/// | word | activates |
/// |---|---|
/// | `record[(<db>, …)]` | the STORAGE faces — the width, the bind, the read, the keyset, the comparison |
/// | `entity` | the READ faces — the predicate and the two marker rows a holder resolves a slot through |
/// | `graphql[(…)]` | the WIRE face — the object, its crossing, and the filter's input-object registration |
///
/// The first two are HOST KINDS, and a record activates the read faces too — its own filter being
/// that same predicate. The third is not a host kind: it says the declaration has a face a client can
/// reach at all. There is no shorthand for both host kinds; write both. The accessor family is the
/// tier's own and is emitted either way.
///
/// `record(sqlite, postgres)` is the record head's own store words one namespace in: it names the
/// dialects this fragment is BUILT for and claims no table, the table being the holder's. `entity`
/// is BARE — entity-hosting has nothing to configure yet, and `entity(…)` says so by name.
/// `graphql(rename = "…", filter(rename = "…"))` names the OBJECT and the BASE the filter's input
/// objects compose off — `filter(rename = "Dim")` publishing `DimFilter` beside `DimColumnFilter`,
/// per the twin law.
///
/// # Attributes
///
/// On the struct, beside the three activations:
///
/// - `crate = "path::to::ingraph"` — where `ingraph` lives, exactly as [`record`]'s. Present
///   because the expansion spends it: a `Vec<_>` field is handed back through `project::Repeated`
///   and an `Option<_>` through `project::Optional`.
/// - `remote = "path::To::Type"` — the FOREIGN TYPE this fragment wraps. See *The rewrite mode*
///   below.
/// - `builder(…)` — the wrapped type's construction protocol, which the storage face's hydration
///   spends.
/// - `cursor[(…)]` — this fragment is a paging position in its own declared order. It needs
///   `record`: both halves of what spends the assertion need rows to walk.
///
/// Every block a node writes — `key(…)`, `lineage(…)`, a store word, `table`, `fulltext(…)`,
/// `vector(…)`, `blob(…)` — is refused BY NAME, each message saying what a fragment has instead.
///
/// On a field: the three projection words (`copy`, `repeated`, `optional`), `builder(…)`, the
/// host-kind namespace `record(…)` and the wire face's own `graphql(rename = "…")`. What a field
/// says to a host kind goes INSIDE that kind's namespace, which is what keeps one ident from meaning
/// two things at two seats — `record(skip)`, `record(skip(default = "…"))`, `record(flatten)` and
/// the per-dialect claims are the record field seat's own words, letter for letter one level in.
/// The labels and the wire legs are still declared ONCE here and inherited by every holder; what
/// reads that inheritance has not arrived, so those are a named refuse-until rather than a fact
/// parsed into a model nothing spends. `id` is refused separately and permanently, by the tier's own
/// definition.
///
/// A field's `#[cfg]` is SERVED, family-wide: it takes the accessor, the segment, the bind, the read,
/// the filter seat and the place on the wire face, all together. Two things it cannot reach are
/// refused by name — a `where` predicate takes no attribute, and a `cursor` fragment's key is every
/// declared field, so a member that could vanish would page by a different key.
///
/// # The rewrite mode
///
/// ```ignore
/// #[ingraph::fields(record, entity, remote = "mediaframe::Dimensions")]
/// pub struct Dimensions {
///   /// The width in pixels.
///   width: u32,
///   height: u32,
/// }
/// ```
///
/// The fields written above are a MANIFEST — the shape of a type another crate owns, restated so
/// this framework can read it — and the item the compiler sees is
/// `#[repr(transparent)] pub struct Dimensions(mediaframe::Dimensions);`. The orphan rule is why
/// the mode exists: a type another crate owns cannot be given this framework's faces where it is
/// declared, and a wrapper is the position where it can.
///
/// `fields` is the FOURTH declaration to take the word and the first with NO IDENTITY SEAT. Each
/// manifest field gets ONE reader — `width(&self) -> u32`, reading `self.0.width()` and crossing it
/// by `Into` — with the field's own doc comments migrated onto it, since the rewrite deletes the
/// field that held them. There are no mutators (a remote's fields are its own), no `const` reader
/// (a foreign accessor is not this macro's to declare `const`), and no borrow reader anywhere: a
/// record's rewrite borrows its id column because this framework's identity seats borrow, and a
/// fragment has no id.
///
/// Beside the readers come `Deref`, `DerefMut`, `AsRef`, `AsMut`, `Borrow`, `BorrowMut` and `From`
/// in both directions, so the wrapper is usable where the wrapped type was and inherits its methods.
/// The macro OWNS the `#[repr(…)]`; an author's own is refused. Every other item attribute —
/// `#[derive(…)]`, `#[cfg]`, doc comments — is forwarded onto the wrapper verbatim.
///
/// # What it emits
///
/// One inherent impl: the accessor family for every field, and the mutator pair beside each. A
/// record withholds the mutators from the fields that bear identity; a fragment has no such field,
/// which is why every one of its fields takes both.
///
/// Beside it are the FACES the activations asked for — the column width, the bind, the read, the
/// keyset, the comparison, the predicate, and the fragment's own output object with the predicate's
/// input face. There is still no constructor, no `Default`, no identity, no storage of its own and
/// no queryable root: what a fragment answers are questions its holder was already asking.
///
/// # Refusals
///
/// The declaration's SHAPE is the fragment, so each part of it is checked here rather than left to
/// fail inside the expansion: a non-struct, a positional or unit struct, any generic parameter, and
/// a struct with no field at all — the tier exists to declare fields a holder inherits, so a
/// declaration with none has nothing to inherit. Two more are about the EMISSION: a field whose
/// name takes the framework's `__name__` shape, and two fields reaching one method name.
#[proc_macro_attribute]
pub fn fields(
  args: proc_macro::TokenStream,
  item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
  let input = syn::parse_macro_input!(item as syn::DeriveInput);
  let arguments = host::options(args.into());
  let parsed = fields::parse(&input, &arguments);
  // A REWRITE replaces the item outright — see [`host::transparent`] — and only an ACCEPTED one
  // does. A refusal echoes the author's own struct back unchanged, for the reason [`node`] carries:
  // the wrapper is built from a path the refusal may be about, and emitting a wrapper over a type
  // that resolves to nothing would bury the sentence that named the real mistake.
  let host = match parsed.as_ref().ok() {
    Some(model) if model.remote.is_some() => {
      host::transparent(&input, model.remote.as_ref().expect("a rewrite's own path"))
    }
    _ => host::echo(&input),
  };
  let expansion = parsed.as_ref().map_or_else(
    syn::Error::to_compile_error,
    ingraph_codegen::fields::FieldsModel::emit,
  );
  quote::quote!(#host #expansion).into()
}

/// Declare a FULL-TEXT INDEX over another node's messages — an operator holding one document per
/// message it saw, searchable by text.
///
/// ```ignore
/// #[ingraph::fulltext(upstream(node = "asr::Segment", title = "speaker", body = "text"))]
/// pub struct SearchDocument {
///   #[ingraph(searchable)]
///   title: String,
///   #[ingraph(searchable)]
///   body: String,
/// }
/// // => pub(crate) __ig_key__: <asr::Segment as Transformer>::Key, injected into the struct
/// //    with new(__ig_key__, title, body) · key_ref() · title_ref() · body_ref() · the mutators
/// //    and impl Transformer / Identifiable, every member of both projected from the upstream
/// ```
///
/// # Its key is not its to mint, and that is what the tier MEANS
///
/// A document is one upstream message INDEXED, so it is addressed by that message's key. There is
/// no `#[ingraph(id)]` field — one is refused by name — no `*Key` type and no `*Lineage` type; the
/// expansion injects ONE field carrying `<Upstream as Transformer>::Key` and answers both address
/// members through it. Re-keying the upstream therefore re-keys every index over it, and a drift is
/// a compile error rather than a convention.
///
/// The injected field is why this is an attribute macro. A derive is handed a copy and may only
/// append; a field that is not in the source cannot exist under one.
///
/// # `upstream(…)` is the edge AND the projection
///
/// - `node = "path::To::Upstream"` — the upstream, as a type path in a string, which is this
///   grammar's rule for every type it names. Nothing here resolves it: the path is EMITTED, so a
///   path naming nothing is `E0412` and a path naming something that is not a node is `E0277`, both
///   at the string the author wrote.
/// - `<this declaration's field> = "<the upstream's field>"` — one per field, and EVERY field needs
///   one. The emission writes a per-field audit whose body is a direct field read, so a field the
///   upstream does not have is `E0609`, one it will not show is `E0616` and one whose type does not
///   match is `E0308` — each at the authored string.
///
/// A DIRECT field read rather than an accessor call: a record's accessor is spelled four ways
/// depending on the projection its own declaration asked for, and this expansion cannot see which.
/// The field name is the one spelling that does not vary — and the `pub(crate)` stamp is what makes
/// reading it legal from the module the index was declared in.
///
/// # Attributes
///
/// On the declaration: `upstream(…)`, `dedup(…)`, `crate = "…"`, `graphql(<backend>)` — which
/// backends dress this declaration's fusion family — and `rename`, which names the RUST types it
/// mints. Every OTHER block a record writes names something a node with no rows and no id of its own
/// does not have, and each is refused by name. `fulltext(…)` is refused too, and for good: the
/// engines are per FIELD, because a slot is one field in one engine, so a block at the head could
/// only name them for the whole declaration.
///
/// The two naming words are two AXES and never cross. `rename = "ShotSearch"` re-bases the whole
/// minted Rust family and `rename(<piece> = "…")` names an individual mint; inside the backend
/// block, `prefix = "…"` re-stems that BACKEND's SDL family and `options`/`question`/`engine` name
/// one face each with a `rename` row. A skin never renames Rust and a bone never appears in a
/// schema.
///
/// The two WORDS carry the vocabulary law: **`rename` names ONE thing verbatim, `prefix` re-stems a
/// FAMILY.** The skin base is pure stem — `prefix = "clips"` mints `ClipsFuseOptions` and its
/// siblings, and no emitted type is called `clips` — so that seat takes the second word, and every
/// seat naming a real type outright keeps the first.
///
/// # The wire face is the WORD's, and the Rust surface is not
///
/// Without `graphql(…)` this declaration still emits everything a program can call: the doors, the
/// packages, the evidence, the selector and the `Fusable` binding. What the word adds is one
/// backend's WIRE IMPLS over those same types — a backend-only search pipeline needs no block at
/// all, and a schema needs one word.
///
/// On a field, the three projection words (`copy`, `repeated`, `optional`) and `searchable`.
///
/// # `#[ingraph(searchable)]` — MANDATORY, and repeatable
///
/// It says a field is what this index SEARCHES. Presence elects; absence leaves the field ordinary
/// payload — stored, hydrated, and matched by nothing. At least one field must wear it: a
/// declaration marking none is refused by name, an index that searches nothing being an index over
/// no subject.
///
/// It dissolves the posture that preceded it, which was *every projection is searched, so there is
/// no WHICH to answer*. There is a WHICH, it is declared, and a document may now carry the columns
/// it wants hydrated beside the ones it wants matched.
///
/// # `keys` — the UPSTREAM's rung, and the tier pair it decides
///
/// A dressed election answers each road twice: the KEYS tier hands back addresses and touches no
/// store, the HYDRATED tier hands back the upstream's whole entities and reads them out of one. The
/// hydrated pair projects `<Upstream as Hydrates>::Db`, whose impl only a [`record`] with a
/// queryable row emits — so which tiers a declaration can mount is decided by which RUNG of the
/// record ladder its upstream sits on, and never by anything this declaration could choose.
///
/// A RECORD upstream mounts both, unconditionally and with no word to write: rows are a record's
/// essence, so storage is guaranteed and hydration can never miss. An [`entity`] upstream mounts the
/// keys tier, and this bare word is where it says so — the pure-engine deployment's honest home, a
/// search surface over a node whose messages land in no database anywhere.
///
/// Written with no word, an entity upstream still emits the hydrated demand and the compiler answers
/// `E0277` at `upstream(node = "…")` carrying `Hydrates`' own sentence, which names both exits:
/// persist the upstream, or wear the word. Nothing here guesses — a macro narrowing the surface to
/// whatever happens to compile would be this crate deciding a deployment's storage posture.
///
/// # THE SEAT LAW: **a seat may sit EMPTY, and a written word must point at something MINTED**
///
/// Every name seat in this grammar is optional, and silence costs nothing — an unwritten seat is a
/// capability nobody has asked for yet, and most declarations write none of them. What is refused is
/// a word that reaches no emitted name: `hydrated(rename = "…")` on a declaration wearing `keys`,
/// `keys(rename = "…")` on a FANNED election that publishes one leaderboard and no per-store road,
/// `engines(rename = "…")` where there is one leg and so no per-leg product, and
/// `key(input(rename = "…"))` on a ROOT record, whose address crosses inward as its id and mints no
/// argument object.
///
/// The distinction is what makes this a law rather than a strictness: an empty seat is a promise
/// nobody made, and a written word that silently does nothing is an author's belief the schema does
/// not share. Each refusal names the WORD, what it would have named, and the shape that publishes
/// none of it — so both repairs are visible, the word being one of them.
///
/// # Refusals
///
/// A second `upstream(…)`, which is the multi-upstream shape and a round of its own. A missing one, a
/// `upstream(…)` with no `node`, an entry naming a field this declaration does not have, a field no
/// entry names, and the LIST form `field = ["a", "b"]` — which the ruled grammar has and whose
/// combining rule it does not. `subscribe = "…"`, by name, as the spelling that projects nothing.
/// A field called `node`, which collides with the upstream entry. A declaration marking nothing
/// `searchable`, and a field marked `knn`, which is the `vector` kind's. And the declaration's own
/// shape: a non-struct, a positional or unit struct, any generic parameter, and a struct with no
/// field.
#[proc_macro_attribute]
pub fn fulltext(
  args: proc_macro::TokenStream,
  item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
  derived(args, item, ingraph_codegen::model::NodeKind::Fulltext)
}

/// Declare an EMBEDDING INDEX over another node's messages — an operator holding one document per
/// message it saw, searchable by nearness.
///
/// ```ignore
/// #[ingraph::vector(upstream(node = "video::Keyframe", image = "image_embedding", caption = "caption_embedding"))]
/// pub struct KeyframeEmbedding {
///   #[ingraph(knn)]
///   image: Embedding<f32, 768>,
///   #[ingraph(knn)]
///   caption: Embedding<f32, 768>,
/// }
/// ```
///
/// Everything about the tier is [`fulltext`]'s, verbatim: the injected key, the per-field audit, the
/// grammar and its refusals — `graphql(<backend>)` and `rename` among them. What differs is the
/// ENGINE the documents are written to, which is named on the FIELD beside its election because a
/// slot is one field in one engine, and the one word this kind adds.
///
/// # `#[ingraph(knn)]` — MANDATORY, and repeatable
///
/// A field's TYPE states its shape, and *this is what a knn runs over* is a ROLE, so the role is
/// declared — on the field, which is the thing that has it. At least one field must wear the marker;
/// mark several to elect several, and each election becomes a VECTOR COLUMN of this declaration's
/// ONE slot, with a `retrieve_keys_by_<field>` / `retrieve_by_<field>` pair of its own. An
/// embedding-typed field wearing no marker is ordinary payload — stored, hydrated, and reached by no
/// knn.
///
/// The QUESTION ROAD is a [`tower`]'s, and the marker's `ask` word retired on 2026-08-19. A road
/// from what a person typed to what a column can be asked with is declared once, as a tower, and
/// reached either by hand — walk it and hand the coordinates to `retrieve_keys_by_<field>` — or by
/// a [`search`] recipe's `tower(<arm>(type = "…"))` arm. The word that used to live here erased
/// every hop's refusal into one boxed name; a tower's own `<Tower>Error` names the step AND carries
/// that step's error type, which is what the move bought.
///
/// # `knn(searchable(tower = "…"))` — the SUGAR, and the two entries the block holds
///
/// `knn(…)` takes `semantics(<kind> = "…")`, which decides how this election's answer is scored,
/// and `searchable(tower = "path::to::Tower")`, which names the tower a question is walked
/// through to reach this column.
///
/// The second word is PURE SUGAR: it expands to the one-member `#[ingraph::search]` recipe an
/// author would otherwise type — `{Index}{Field}Search`, a shared seat whose type is the tower's own
/// `<Tower as SearchTower>::Question`, one `shared` arm, and this declaration's `graphql(…)` block
/// passed through, so the wire fields `{index}{field}Search` and `{index}{field}SearchKeys` land
/// wherever a hand-written recipe's would. Nothing underneath knows which of the two it expanded
/// from.
///
/// It is the shortest road and not the widest one. A weight, a floor, a second member or a second
/// seat is a recipe's word, so the moment one is wanted the answer is to write the recipe — which is
/// what the refusal inside `searchable(…)` says.
///
/// The word is the full-text election marker's own spelling, in a second position. It means one
/// thing in both — *a question can reach this column* — and what it takes is the difference: nothing
/// where a question is already text, a tower where the column holds coordinates.
///
/// A field marked `searchable` is refused here by name — that is the `fulltext` kind's marker — and
/// so is a field marked `knn` whose type holds no coordinates, at the TYPE its author wrote.
///
/// # `keys` — the UPSTREAM's rung
///
/// [`fulltext`]'s word, verbatim and for its reason: an [`entity`] upstream holds no rows, so the
/// hydrated half of each road has no store to read out of and is not mounted. See there for the
/// whole of it, and for what a declaration that omits the word over an entity upstream is refused
/// with.
#[proc_macro_attribute]
pub fn vector(
  args: proc_macro::TokenStream,
  item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
  derived(args, item, ingraph_codegen::model::NodeKind::Vector)
}

/// Declare an ARTIFACT FAMILY derived from another node's messages — an operator holding one stored
/// object per message it saw.
///
/// ```ignore
/// #[ingraph::blob(upstream(node = "video::Keyframe", payload = "pixels"))]
/// pub struct Thumbnail {
///   #[ingraph(repeated)]
///   payload: Vec<u8>,
/// }
/// ```
///
/// Everything about the tier is [`fulltext`]'s, verbatim, EXCEPT what a family with no query surface
/// cannot spend. The store is named at the HEAD — `fs`, `s3` — because this kind elects nothing and
/// its slot is `(declaration × engine)`; beside it ride `extension`, which ends the address this
/// node's carried key renders into directories, `data`, which permits the bytes to travel, and
/// `slot = "…"`, which names the corpus the objects are stored under (default:
/// `snake_case(<declaration name>)`).
///
/// `rename` and `graphql(…)` are REFUSED here, each with its measurement rather than as a wait: this
/// kind lands no type in the declaring scope for a rename to move, and it mints no wire type for a
/// backend to dress — its address and its bytes are fields of a RECORD's output object, put there by
/// that record's `locate(…)`.
#[proc_macro_attribute]
pub fn blob(
  args: proc_macro::TokenStream,
  item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
  derived(args, item, ingraph_codegen::model::NodeKind::Blob)
}

/// The one body every DERIVED-INDEX macro has: parse under this kind, echo the host carrying the key
/// the model minted, then emit.
///
/// The order is the difference from [`node`] and [`equip`], and it is forced: the injected field's
/// TYPE is `<Upstream as Transformer>::Key`, so the host cannot be written until the upstream has
/// been read out of the declaration.
///
/// A REFUSED declaration is echoed WITHOUT the field, and the rule is the honest one rather than a
/// best effort. The field exists to carry a key from an upstream, and a declaration that was refused
/// may have named no upstream at all; a guess would put a field of some invented type in the
/// author's struct beside the message telling them the struct is wrong. What does not change is that
/// the host is emitted either way — an attribute macro replaces the item it sits on, so a refusal
/// that emitted only the error would delete the type and bury its own message under every mention of
/// it.
fn derived(
  args: proc_macro::TokenStream,
  item: proc_macro::TokenStream,
  kind: ingraph_codegen::model::NodeKind,
) -> proc_macro::TokenStream {
  let input = syn::parse_macro_input!(item as syn::DeriveInput);
  let options = host::options(args.into());
  let parsed = index::parse(&input, &options, kind);
  let host = match &parsed {
    Ok(model) => host::echo_carrying(&input, model.carried_key()),
    Err(_) => host::echo(&input),
  };
  let expansion = parsed.as_ref().map_or_else(
    syn::Error::to_compile_error,
    ingraph_codegen::index::IndexModel::emit,
  );
  // THE SUGAR'S ITEMS RIDE BESIDE THE INDEX'S OWN, and they are the recipe macro's own expansion of
  // a declaration this crate wrote instead of the author. Nothing here decides anything a
  // hand-written `#[ingraph::search]` does not — see `search::sugar`, where the whole of it is.
  let forged = parsed
    .as_ref()
    .map(search::sugar::recipes)
    .unwrap_or_default();
  quote::quote!(#host #expansion #forged).into()
}

/// Declare a SHAREABLE RESOURCE — a type several units may hold at once.
///
/// ```ignore
/// #[ingraph::resource]
/// pub struct Egemma {
///   model: EgemmaModel,
/// }
///
/// impl ingraph::AsyncResource for Egemma {
///   type Options = EgemmaOptions;
///   type Error = LoadError;
///
///   async fn build(_ctx: &Resources, options: EgemmaOptions) -> Result<Self, LoadError> { … }
/// }
/// ```
///
/// # Sharing is a DOUBLE opt-in, and this word is the first half
///
/// A unit field written as the plain type is EXCLUSIVE: the unit owns it, the framework knows
/// nothing about it, and a `!Send` value is legal there because a resident constructs its operator
/// on the engine that runs it and never migrates it. That is the default and it is unchanged.
///
/// Sharing needs both parties to say so. This word is the RESOURCE AUTHOR's half — *this type is
/// meant to be held by several units* — and `model: Shared<Egemma>` on a unit is the MEMBER's. The
/// string label a share once needed is dead: the type is the rendezvous.
///
/// # Three layers, three authors — and this macro is the middle one
///
/// | layer | written by | what it says |
/// |---|---|---|
/// | `AsyncResource` | the AUTHOR, by hand | how to build one, and that it crosses threads |
/// | this macro | the DECLARATION | the type is a citizen of the walk |
/// | `Plan::validate` | the DEPLOYMENT | every demanded resource was declared |
///
/// The contract is hand-implemented because only the author knows how to load a model — `type
/// Options` is the author's own shape, and `build` is `async` because loading one is I/O and
/// compute.
///
/// # RESOURCES ARE THE ENGINES, and kind is said once — here
///
/// A resource is where a deployment's engines live, so the declaration takes one optional BUILTIN
/// KIND WORD: `#[ingraph::resource(tantivy)] pub struct Ft;` names one of the framework's own
/// engines, and the expansion writes everything the foreign author writes by hand — the declaration
/// re-emitted CARRYING the engine it mints, the `AsyncResource` impl that opens it, and the engine's
/// base and faces delegating to it.
///
/// The vocabulary is CLOSED and each word rides its engine's cargo feature. It is short on purpose:
/// a word is a promise that this crate can write the whole binding, which it can only keep for an
/// engine it SHIPS. The OPEN half of the axis is the bare form, which is where every other engine
/// there is enters — hand-written impls, and no vocabulary to be admitted to.
///
/// # Attributes
///
/// On the declaration:
///
/// - `crate = "path::to::ingraph"` — where `ingraph` lives, exactly as [`record`]'s. Present because
///   the expansion spends it: the citizenship impl names the framework's own trait.
/// - one BUILTIN KIND WORD — `tantivy` today. Bare; how an engine is TUNED reaches it through the
///   `[resources.…]` section its mount names, not through this attribute.
/// - `async` — the MODE WORD, and the FOREIGN form's alone: it names which of an engine's two face
///   pairs this resource's hand-written impls are. A bare declaration is on the BLOCKING face, which
///   is the default nobody writes, and the same lexicon `source(async)`, `handler(async)` and
///   `operator(async)` are written in.
///
/// A kind word and `async` together are REFUSED: a builtin carries its own mode — tantivy is a
/// synchronous engine and no word can make it otherwise — so a second opinion beside it could only
/// disagree.
///
/// Every word that would describe HOW a foreign one is built belongs to the `AsyncResource` impl, and
/// every word that would describe where its options come from belongs to the launch — so this
/// grammar has neither, and an unknown entry is refused by a message saying which of the two it is
/// looking for.
///
/// # What it emits
///
/// | item | condition |
/// |---|---|
/// | `impl DeclaredResource for <Type>`, carrying `const SYNC` — the citizenship the walk enumerates, and the mode the declaration recorded | always |
/// | the declaration CARRYING the engine the word mints | a kind word |
/// | `impl AsyncResource` — `Options` and `Error` projected off the engine's store, `build` its open | a kind word |
/// | the engine's BASE (`FulltextEngine`) — eight seats and the address lifecycle, delegating | a kind word |
/// | the engine's two faces IN ITS OWN MODE (`FulltextRead` / `FulltextWrite`), delegating | a kind word |
/// | `SLOT` and `connection()`, the two doors onto the minted engine | a kind word |
///
/// No face of the OTHER mode is emitted, and the absence is the honesty rather than an omission: the
/// kind word carries the mode knowledge, so an `AsyncFulltextRead` beside a blocking engine would be
/// this macro claiming a posture the engine does not have.
///
/// The FOREIGN form emits the citizenship and nothing else. There is no accessor family, and the
/// absence is the tier rather than an omission: a resource is reached through `Shared<R>`, which
/// derefs to the type, so what a member can do with one is whatever the author's own inherent impl
/// offers. Emitting accessors would put this crate's naming convention on a surface that is somebody
/// else's — which is exactly why a kind word gets two doors and a foreign declaration gets none: the
/// macro minted that engine, so naming its doors is this crate naming its own.
///
/// # Refusals
///
/// The DECLARATION's shape is checked here. A generic parameter is refused, for the reason
/// [`ingraph`]'s is — the emission registers ONE type as a citizen, and a parameter is not a type
/// until it is substituted. Under the FOREIGN form a tuple struct, a unit struct and an enum are all
/// admitted, because nothing in that expansion reads a field or a variant; under a KIND WORD the
/// declaration must hold nothing of its own, because the expansion is what puts the engine there.
///
/// An unknown kind word is refused by a message listing the ones this build knows, and a kind word
/// whose engine the `ingraph` dependency did not compile is refused by a `compile_error!` naming the
/// feature to add.
///
/// The CONTRACT is checked by the emission, where the compiler can see it: a declaration with no
/// `AsyncResource` impl is `E0277` at the declaration, and so is one whose type is not `Send + Sync` —
/// the supertraits being the sharing teeth, biting at the earliest site there is rather than at
/// whichever unit reached for the type first.
///
/// A demanded resource that nobody DECLARED is neither: `AsyncResource` is hand-implemented, so a type
/// can satisfy `Shared`'s bound without having joined the walk, and only a plan holds both the
/// declared set and the demands. That one is a START-UP refusal, naming the resource and the node.
#[proc_macro_attribute]
pub fn resource(
  args: proc_macro::TokenStream,
  item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
  let input = syn::parse_macro_input!(item as syn::DeriveInput);
  let arguments = host::options(args.into());
  let plain = host::echo(&input);
  // It does NOT reach `equip`, and the one thing it needs that the four there do not is the whole
  // difference: a kind word re-writes the host, so the declaration is emitted in two forms and which
  // of them survives is a cargo gate's answer rather than this crate's.
  match resource::parse(&input, &arguments) {
    Ok(model) => {
      let carrying = model
        .carried_engine()
        .map_or_else(|| plain.clone(), |field| host::echo_carrying(&input, field));
      model.expand(&plain, &carrying).into()
    }
    // THE HOST IS EMITTED ANYWAY, for the reason every macro in this family states: an attribute
    // macro replaces the item it sits on, so a refusal that emitted only the error would delete the
    // type and bury its own message under every mention of it. The AUTHOR'S OWN host, never a
    // carrying one — a refused declaration may be refused precisely for the shape an injection
    // needs.
    Err(error) => {
      let refusal = error.to_compile_error();
      quote::quote!(#plain #refusal).into()
    }
  }
}

/// Declare a SOURCE's COMMAND FACE — the vocabulary an application can say to one running origin.
///
/// A mutation node is a struct whose FIELDS are exchanges: one field is one thing an app can say,
/// its TYPE says what is sent and what comes back, and the words beside it say who runs it and how
/// it fails.
///
/// ```ignore
/// #[ingraph::mutation(graphql(async_graphql))]
/// pub struct WatchOps {
///   #[ingraph(rename = "addWatch",
///             handler(path = "crate::watch::add", async,
///                     context(resource("crate::Catalog")),
///                     error(type = "crate::AddWatchError", code = "ADD_FAILED")))]
///   add: (AddWatch, AddResponse),
///
///   #[ingraph(handler(path = "crate::watch::remove",
///                     error(message = "that watch is not ours", code = "NOT_OURS")))]
///   remove: (RemoveWatch, RemoveResponse),
///
///   #[ingraph(handler = "crate::watch::reindex")]   // the plain form
///   reindex: (Reindex, ()),                          // and the exchange that cannot fail
/// }
/// ```
///
/// A source mounts it with `mutation(node = "WatchOps")` on its own declaration and names it in its
/// `type Mutation` seat; `run` then receives `Control<WatchOpsCommand>` and matches on what was said.
///
/// # THE HANDLER IS DECLARED HERE, and never on the source
///
/// The ruling that shaped this word: *don't make the user write handlers on the source side — the
/// codegen can assemble them*. So behaviour is declared per FIELD, on the node, and the expansion is
/// what wires it up. The consequence is worth stating, because it removed a whole layer: with one
/// handler per field there is no way to answer the wrong command, so the runtime check that used to
/// look for that mismatch — and the vocabulary it needed — does not exist. The arm is unwritable
/// rather than guarded.
///
/// # THREE SIGNATURES, and the `error(…)` word picks which one
///
/// | `error(…)` | the handler's signature |
/// |---|---|
/// | `error(type = "E")` | `fn(…, req: Request) -> Result<Response, E>` |
/// | `error(message = "…")` | `fn(…, req: Request) -> Result<Response, ()>` |
/// | *omitted* | `fn(…, req: Request) -> Response` — no `Result` at all |
///
/// A CANNED failure's words live in the declaration: the message and the code are fixed at the word,
/// so the body reports only the POSITION it failed at, which is what `Err(())` is. A RICH one's words
/// live in the value. `async` on the handler makes each of the three a future; `context(…)` puts the
/// granted resources in front of the request, in the order they were written.
///
/// A `pub` canned handler earns `clippy::result_unit_err`, whose usual advice does not apply here —
/// an error type would be carrying words nothing renders — so such a handler is the one place an
/// `#[expect(clippy::result_unit_err, reason = "…")]` is the right answer.
///
/// A signature that does not match is `E0308`/`E0277` **at the handler path word**, which is the
/// token the author has to change: the emission binds the call to the exact type the words chose, at
/// that word's own span.
///
/// # THE WIRE FACE, and what a resolver does
///
/// `graphql(async_graphql)` publishes ONE ROOT FIELD PER EXCHANGE on a minted `<Node>Mutations`
/// unit, which a root folds. Each resolver:
///
/// 1. finds the source's command line — `ctx.data::<Commands<<Node as MutationNode>::Command>>()` —
///    FIRST, so a schema that never mounted this node refuses with nothing done;
/// 2. takes the granted resources out of `ctx.data::<Shared<R>>()`, in declaration order;
/// 3. calls the handler at its declared signature, awaiting it where the `async` word said to;
/// 4. renders a failure under the heading its declaration wrote — `"CODE: message"`, or the
///    sentence alone where no `code` was written;
/// 5. **forwards on success and only on success**, one way, as the command variant this node
///    minted. A change that failed has no living application, so nothing is sent — and a source that
///    has died answers `UNREACHABLE_SOURCE`, which is the one wire code that says the effect
///    HAPPENED and nothing applied it.
///
/// An exchange whose response is `()` publishes `Boolean!` and answers `true`.
///
/// An application installs the line the resolvers read with
/// `Schema::build(…).data(commands).data(Shared::new(catalog))`, the command type being its own key.
///
/// # Attributes
///
/// On the declaration:
///
/// - `graphql(async_graphql)` — the wires this node is dressed for.
/// - `crate = "path::to::ingraph"` — where `ingraph` lives, exactly as [`record`]'s.
///
/// On a field, exactly two words — `rename` is the SKIN and `handler` is the BEHAVIOUR:
///
/// - `rename = "…"` — the word the wire publishes this exchange under.
/// - `handler = "path::to::fn"` — the plain form, for an exchange whose signature has nothing else
///   to say.
/// - `handler(path = "…" [, async] [, context(resource("…"), …)] [, error({type = "…" ⊻ message =
///   "…"} [, code = "…"])])` — the same word with the rest of the signature written out. `error`
///   lives INSIDE the block because the block IS the signature, and a failure with no handler to
///   belong to is a failure nothing renders.
///
/// # What it emits
///
/// | item | content |
/// |---|---|
/// | the author's host, echoed | unchanged but for the markers this macro consumed, with an annotated `#[allow(dead_code)]` over it |
/// | `<Node>Command` | one arm per field, carrying `<FieldTy as Mutation>::Request` |
/// | `impl MutationNode for <Node>` | the row a source's `Mutation` seat resolves through |
/// | `impl DeclaredMutation for <Node>` | the DECLARATION RECORD — `ALL_SYNC`, and one `Exchange` row per field carrying its handler path, its face, its grants, its rename and its failure |
/// | `<Node>Response` / `<Node>Error` | the assembled face's return vocabulary — one arm per exchange, and one per exchange that declared a FAILURE |
/// | `<Node>::handle_<node>` | the ASSEMBLED FACE: the node's total capability, in one function |
/// | `<Node>Mutations` and its `#[Object]` | only with a `graphql(…)` word — the unit a root folds, and one resolver per exchange |
///
/// The command arm's payload is a PROJECTION rather than a written type, which makes the emission
/// its own assert: a field whose type is not an exchange is `E0277` at the field, naming `Mutation`.
///
/// The record exists for the reason `Declared`'s does — two expansions cannot read each other's
/// tokens, so a source's own expansion reads this declaration through
/// `<WatchOps as DeclaredMutation>::…` and never through anything this macro wrote for itself.
///
/// The host's `#[allow(dead_code)]` is a ruling rather than a workaround: a node is a VOCABULARY and
/// not data, so nothing constructs one, and the lint would fire inside an expansion its author
/// cannot edit about a shape this macro asked them to write. The attribute carries its own reason.
///
/// # THE ASSEMBLED FACE, and the OR law that decides its mode
///
/// `handle_<node>` is the node's TOTAL CAPABILITY in one function: the grants its exchanges were
/// granted between them, a `<Node>Command`, and a `Result<<Node>Response, <Node>Error>`. It is
/// emitted whether or not the declaration wore a wire word, because it is the node's Rust surface
/// and a schema is the binding's.
///
/// **Its mode is the OR of its handlers'** — every handler blocking assembles a `fn`, and one
/// awaited handler makes the whole face an `async fn`. So a deployment controlling a wholly
/// synchronous node needs no runtime to say anything to it.
///
/// The WIRE does not come through it: a schema publishes one root field per exchange and calls that
/// exchange's own handler, which is what makes *answering the wrong command* unwritable. What the
/// face serves is every OTHER caller — a first-party transport, a test, the source-side party
/// holding a command off its own `Control` line.
///
/// Two consequences worth knowing before writing a declaration:
///
/// - **every handler path RESOLVES at the declaration.** The face calls them, so a node whose
///   `handler = "…"` names nothing is `E0425` where it is declared rather than wherever a binding
///   would first have called it.
/// - **a declared `error(type = "…")` must render.** Its arm of `<Node>Error` writes the `code`
///   heading and then lets the value say the rest, exactly as the wire's own renderer does — so a
///   rich failure owes a `Display` and nothing else. A failure whose own `Display` ALREADY carries
///   a heading should be declared WITHOUT a `code` word: two headings on one message is two
///   vocabularies with nothing telling a reader which is which.
///
/// # A REQUEST IS `Clone`, and only where a `graphql(…)` word is written
///
/// The wire's resolver forwards what was ASKED FOR to the living application and the handler takes
/// that same request BY VALUE, so it clones before calling. The bound therefore falls on every
/// request type of a node dressed for a wire, and on none of a node that is not — the assembled face
/// forwards nothing and clones nothing.
///
/// It costs a declaration almost nothing: a request is a wire input object, a bag of owned decoded
/// values with no borrow in it, and `Clone` is the nature of such a thing. The alternatives were
/// handing the handler a `&Request` (which contradicts the signature the three tiers are cast to)
/// and forwarding the RESPONSE (which contradicts what a command is — the living application
/// applies what was asked for). Both were rejected; the reasoning is on the wire emitter's module.
///
/// # Refusals
///
/// | written | refused because |
/// |---|---|
/// | a field with no `handler` | an exchange nobody runs is a command with no behaviour |
/// | `error(type = "…", message = "…")` | the two shapes are one word, and both leaves the return type undecided |
/// | `error(code = "…")` alone | a code is a HEADING, and this one heads nothing |
/// | `error()` | a field that can fail says how; one that cannot omits the word |
/// | `rename = Word` | the word names a SCHEMA field, and a schema name is not a Rust identifier |
/// | `context(…)` holding anything but `resource("…")` | a handler's context is the resources it was granted, and nothing else reaches one that way |
/// | a tuple struct, a unit struct or an enum | a field's NAME is the command's name, the arm it mints and the word the wire publishes |
/// | a generic parameter | the expansion mints ONE vocabulary for ONE type |
#[proc_macro_attribute]
pub fn mutation(
  args: proc_macro::TokenStream,
  item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
  equipped(args, item, host::echo_vocabulary, |input, arguments| {
    mutation::parse(input, arguments).as_ref().map_or_else(
      syn::Error::to_compile_error,
      ingraph_codegen::mutation::MutationModel::emit,
    )
  })
}

/// Declare an ORIGIN — and hold its `mutation` word and its `type Mutation` seat to each other.
///
/// ```ignore
/// #[ingraph::source(async, mutation(node = "WatchOps"))]
/// pub struct Watch { roots: Vec<PathBuf> }
///
/// impl AsyncSource for Watch {
///   type Options = WatchOptions;
///   type Yield = Change;
///   type Mutation = WatchOps;                 // the word above, as a TYPE
///   type Error = WatchError;
///   async fn build(ctx: &Resources, options: WatchOptions) -> Result<Self, Self::Error> { … }
///   async fn run(self, ctx: Context, feed: Feed<Change>, control: Control<WatchOpsCommand>)
///     -> Result<Fin, Self::Error> { … }
/// }
/// ```
///
/// # THE DOUBLE ENTRY, which is the whole of what this word emits
///
/// A source's command face is written twice — once as a WORD, which is what a declaration says, and
/// once as a TYPE, which is what a [`Control`](../ingraph/struct.Control.html) line resolves through
/// — and neither spelling can be dropped: an attribute macro cannot write somebody else's `impl`,
/// and an `impl` is not a declaration. So this expansion writes the JOIN between them, and the join
/// is checked in BOTH directions:
///
/// | written | what happens |
/// |---|---|
/// | the word and the matching seat | it compiles |
/// | the word, and a seat naming something else (`()` included) | `E0271` at the WORD |
/// | no word, and a seat naming a node | `E0271` at the DECLARATION |
/// | no word, and `type Mutation = ()` | it compiles |
///
/// The third row is what a single-entry design would have lost: a source that mounted a node and
/// forgot to say so would publish no wire face, and a missing word looks exactly like a source
/// nobody controls.
///
/// # ONE command face per source
///
/// `mutation(…)` may be written at most once. A second one is refused with the sentence that names
/// the day it arrives — more words go in the NODE, and the mount widens when two vocabularies truly
/// diverge — because the wire face is per-FIELD, so N nodes and one node with N fields are the same
/// schema and the same author experience.
///
/// # Attributes
///
/// - `async` — this origin's body is awaited, so the bound names
///   [`AsyncSource`](../ingraph/trait.AsyncSource.html). Without it the bound names
///   [`Source`](../ingraph/trait.Source.html), the blocking face, per the dual-mode law's
///   word-selects-face rule.
/// - `mutation(node = "path::to::Node")` — the mutation node whose fields are this origin's command
///   vocabulary. Omitted for an origin nobody controls, whose seat is `()`.
/// - `crate = "path::to::ingraph"` — where `ingraph` lives, exactly as [`record`]'s.
///
/// # What it emits
///
/// | item | content |
/// |---|---|
/// | the author's host, echoed | unchanged but for the markers this macro consumed |
/// | one anonymous `const` | the double entry — a bound over the declared type naming the mounted node, spent at the word |
/// | `impl DeclaredOrigin` | the RECORD a launch walk mounts it through — its face as a TYPE, and the node it controls as a word |
///
/// And nothing else. No command enum, no `MutationNode` row, no resolver: those are the NODE's own
/// declaration's, and this one has never seen its tokens.
///
/// # THE RECORD is what makes a mount declaration-driven
///
/// A launch walk that mounts an origin sees a TYPE and nothing else, so the record is how the
/// `async` word reaches it: `type Mode` selects the driver, and one door then serves both faces —
/// `Blueprint::origin::<Watch>("watch")` enters the arrangement and
/// `Ignition::origin_declared::<Watch>(…)` puts it on an engine, neither of them naming a face. An
/// origin that publishes to nobody is refused before anything ignites, by the pure-leaf rule that
/// was already there.
///
/// It is a PUBLIC seam: a hand-written origin writes the impl in three lines and is mounted the same
/// way. Nothing here is obliged to have come through this macro.
///
/// # ONE OPTIONS SEAT, and it is the face's own
///
/// The `type Options` above is what a deployment's `[watch]` section holds, and
/// `Creation::origin` is what hands it to `build`. There is no second seat to keep in step: an
/// origin used to be constructed through
/// [`AsyncConstructor`](../ingraph/trait.AsyncConstructor.html) because `build` signed a
/// `Context` the create stage has not got, and the window moved to
/// [`Resources`](../ingraph/struct.Resources.html) so the face's own door could be the one the
/// framework calls.
///
/// # Refusals
///
/// | written | refused because |
/// |---|---|
/// | a second `mutation(…)` | one command face per source — the mount widens the day two vocabularies diverge |
/// | `mutation`, `mutation()` or a block with no `node` | an origin nobody controls omits the word; one that is controlled names the node |
/// | `mutation(node = Node)` | the word names a TYPE this declaration cannot resolve, so it is quoted |
/// | a second `async` | one origin wears one face |
/// | a generic parameter | the expansion states ONE bound over ONE origin |
#[proc_macro_attribute]
pub fn source(
  args: proc_macro::TokenStream,
  item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
  equip(args, item, |input, arguments| {
    source::parse(input, arguments).as_ref().map_or_else(
      syn::Error::to_compile_error,
      ingraph_codegen::source::SourceModel::emit,
    )
  })
}

/// Declare a QUESTION PIPELINE — the steps between what a person asked and what an index can be
/// asked with.
///
/// ```ignore
/// #[ingraph::tower(question(type = "String"))]
/// pub struct ClipText {
///   #[ingraph(answer = "Vec<String>")]     tokenize: Tokenize,
///   #[ingraph(answer = "Vec<f32>", async)] encode:   ClipTextTower,
/// }
/// ```
///
/// # FIELDS ARE STEPS
///
/// A field's NAME is the step's name and its TYPE is the server that runs it, in the order the
/// fields are written. Nothing here mints a name and nothing overrides one — one name serves the
/// steps struct, the tower's options, the arm of the refusal sum and the schema row alike.
///
/// # THE TWO OVERRIDE WORDS ARE OMISSIBLE
///
/// A server may declare, ONCE, what it is canonically asked and what it canonically answers:
///
/// ```ignore
/// impl DefaultServe for Tokenize {
///   type Question = String;
///   type Answer = Vec<String>;
/// }
///
/// #[ingraph::tower]                 // asked what `Tokenize` is canonically asked
/// pub struct Words {
///   tokenize: Tokenize,             // answers what `Tokenize` canonically answers
/// }
/// ```
///
/// The tower's `question(type = "…")` and a step's `answer = "…"` are OVERRIDE words: written, they
/// name the type here; omitted, the step's own canonical line is projected in their place. The two
/// are independent, so a tower may write one and omit the other, and a tower may write the word on
/// the steps that need it and omit it on the steps that do not.
///
/// A step whose type has no canonical line to read an omitted word off is `E0277` at that step's
/// field, and `DefaultServe`'s own note names both roads back. Selection never comes from inference:
/// `DefaultServe` takes no parameter, so a step answering several kinds of question is exactly as
/// unambiguous omitted as written.
///
/// # THE HEAD PIN — `answer = "…"` at the TOWER, which decides nothing
///
/// ```ignore
/// #[ingraph::tower(answer = "Vec<f32>")]      // ← what this tower is FOR, said at its head
/// pub struct ClipText {
///   tokenize: Tokenize,
///   encode:   Encode,
/// }
/// ```
///
/// A tower answers what its LAST STEP answers, and this word cannot make it answer anything else. It
/// is a DOUBLE ENTRY rather than a third override: the word writes an INTENT down, the chain DERIVES
/// an answer, and the expansion demands that the two agree. A tower whose last step moved is `E0271`
/// **with the caret on the type the word named**, and the note beside it points at the step's own
/// `answer` — so one refusal names both halves.
///
/// It is OPTIONAL and costs an omitting declaration nothing — no bound, no obligation, not one token
/// of expansion. What writing it buys is WHERE a drift is reported: a chain whose end moved is
/// caught anyway, by whatever bound named the answer it expected, but that refusal lands wherever
/// the tower was BOUND and this one lands at the tower. Both spellings are taken, exactly as the
/// question's are: `answer = "…"` and `answer(type = "…")`.
///
/// # THE CHAIN IS DERIVED, and it is a compile-time theorem
///
/// One question is written and one answer per step; every question after the first IS the answer
/// before it, and the last step's answer is the tower's. So an author never states an adjacency,
/// and what the expansion does is DEMAND each hop:
///
/// ```ignore
/// impl SearchTower for ClipText
/// where
///   Tokenize:      Serves<String, Vec<String>>,
///   ClipTextTower: AsyncServes<Vec<String>, Vec<f32>>,
/// { … }
/// ```
///
/// A step that does not serve the question it is handed is `E0277` **at the impl, with the caret on
/// that step's own field**. `cargo check` green is the chain proven connected.
///
/// # `async` PER STEP, which is what makes a MIXED tower expressible
///
/// A bare step demands the blocking face; `#[ingraph(async)]` demands the awaited one. So a
/// blocking tokenizer feeding an awaited encoder is one tower. Words CHOOSE and bounds PROVE:
/// nothing here checks that a step's body is really awaited, and a word that lied names a face the
/// type does not wear, which is the same `E0277` on the same field.
///
/// # THE WALK, and the OR law over its steps
///
/// Beside the impl, one inherent function:
///
/// ```ignore
/// ClipText::walk(question, &mut tokenize, &mut encode, options).await
/// ```
///
/// The question first, then one `&mut` borrow per step in declaration order, then the tower's own
/// options seat. Its FACE is the OR of the steps' — every step blocking walks in a blocking
/// function, one awaited step makes the whole walk awaited — which is the mutation node's assembled
/// face one layer over. Steps are parameters rather than `&mut self` so a deployment may hold them
/// anywhere; a caller holding the struct passes disjoint field borrows.
///
/// The walk takes the DECLARATION's visibility, and the steps take this family's own convention: a
/// field written with no visibility is stamped `pub(crate)`. A tower meant to be walked from
/// outside its crate therefore writes `pub` on the steps a caller has to borrow — the same
/// one-directional rule every node macro carries, stated here because this is the family whose
/// fields a CALLER names.
///
/// A `pub` tower also publishes its steps' TYPES, and that is a hard error rather than a lint: the
/// refusal sum below takes the declaration's visibility and its arms name the step types, so a
/// `pub` tower over a private step is `E0446`. Declare the tower at the visibility its steps have.
///
/// Every hop is served under `None`, so each step runs at its own floor.
///
/// # THE REFUSAL SUM
///
/// Beside the walk, one enum: `<Tower>Error`, an arm per step named after the step's own field and
/// carrying that step's own error — `ClipTextError::Tokenize(<Tokenize as Serves<…>>::Error)`. A
/// projection rather than an erasure, so a step keeps the error type it declared and a caller that
/// matched an arm holds it. `Display` names the step that refused; `source` reaches the cause, which
/// is the ONE demand this makes of a step's error and lands at that step's field.
///
/// # Refusals
///
/// | written | refused because |
/// |---|---|
/// | `question` naming no type | a word that decided nothing; OMITTING it is the canonical road |
/// | `answer` at the tower naming no type | the same, for the head pin: omit it where the tower's answer is simply its chain's |
/// | a second `question` or a second head `answer` | one tower has one of each end, and the sugar and the full form fill one seat |
/// | a struct with no field | a tower's fields ARE its steps |
/// | a tuple struct, a unit struct | a step's name is its field's, and a positional field has none |
/// | an enum or a union | variants are a choice between things rather than a chain of them |
/// | a generic parameter | the expansion states ONE chain over ONE declaration |
/// | `async` carrying anything | it names a face; the body is the step author's |
/// | `arm(…)` / `chain(…)` | the RETIRED inline form — bindings live at the search recipe now |
/// | `name = "…"` on a step | the retired form's word; the field already is the name |
/// | `options` on a step | the seat is the SERVER's own `Serve::Options`, declared once by the type |
/// | `expand` naming no type | the framework ships no expander, so there is no bare word to mean |
/// | `route = <router>` | the crossing names TWO things; the sugar holds one half of an equality |
/// | `route(…)` naming no `router` or no `slot` | both halves of a wiring, or neither |
/// | a bare `router` this framework does not ship | MINT BARE, REFER QUOTED — the escape is a quoted path |
/// | both fan words on one step | a step opens ONE segment; the two stages are two steps |
/// | a second `expand`, or a second `route`, in one tower | one widening family and one lane fan, which is what the fold has a law for |
/// | `route` before `expand` | ② runs before ④; a widening after a routing would widen a probe |
/// | `async` beside a fan word | a segment's field holds the SEGMENT'S SEAT; a seat has no `serve` call for a face to be about |
///
/// # THE AMENDMENT, and what a fan-carrying tower walks
///
/// A tower may contain FANNING SEGMENTS — expansion × lane routing — and every fan folds before the
/// tower's mouth, so the outer contract stays 1 → 1. The two words that open one are `expand` and
/// `route`, and the walk they emit is:
///
/// ```text
/// [ the steps before the fan ]  ─▶ ② widen ─▶ for each ARM: ④ route ─▶ for each LANE: [ the tail ]
///                                                                             │
///                                          ONE ranked answer ◀── the fold ◀────┘
/// ```
///
/// **A FAN STEP'S FIELD HOLDS THE SEGMENT'S SEAT**, which is fields-are-steps at the two positions
/// where the thing mounted is not a server: a widening step holds an `Expansion<Q>` and a crossing
/// step holds a `LaneFan<Router>`, both assembled by the deployment — the declaration's `expand`
/// word names the expander the deployment DEFAULTS to and its `route` word names the wiring the
/// compiler checks. So neither position is a `Serves` hop, a widening has no arm in the refusal sum
/// (it cannot fail), and a crossing's arm carries the fan's own `FanError`.
///
/// **THE WALK OF A WIDENING TOWER IS AWAITED**, whatever its steps say: the expand seam's call face
/// is the awaited one, and a blocking expander reaches it through the lift bridge.
///
/// **THE ANSWER IS THE FUSED LIST** — `Vec<Fused<Root, Evidence>>`, one value, the two parameters
/// projected off the tail's own answer through `RankedStream`. The two fold laws are structural: a
/// cell's coefficient is `arm × lane` MULTIPLIED at the only door into a cell, and one question's
/// expansion family is ONE WITNESS, deduplicated on full `(root, evidence)` identity with the better
/// rank surviving.
///
/// **A tower that opens no segment is untouched by all of it** and expands exactly as it did before
/// the amendment, token for token.
#[proc_macro_attribute]
pub fn tower(
  args: proc_macro::TokenStream,
  item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
  equip(args, item, |input, arguments| {
    tower::parse(input, arguments)
      .as_ref()
      .map_or_else(syn::Error::to_compile_error, |model| {
        ingraph_codegen::tower::TowerModel::emit(model)
      })
  })
}

/// Declare a SEARCH RECIPE — the members one question is asked across, and the towers that turn it
/// into what each of them can be asked with.
///
/// ```ignore
/// #[ingraph::search(shared(text(type = "String")), dedup(hash), limit = 20)]
/// pub struct TravelSearch {
///   #[ingraph(weight = 1.0, depth = 50, tower(zh(type = "crate::ZhQuery", shared)))]
///   subs: Subs,
///   #[ingraph(weight = 2.0, depth = 100,
///     tower(text(type = "crate::ClipText", shared, floor = "crate::floors::SEM_TEXT")),
///     tower(image(type = "crate::ClipImage", shared)))]
///   shots: Shots,
/// }
/// ```
///
/// # FIELDS ARE MEMBERS
///
/// A field's NAME is the member's name and its TYPE is the index it reads, in the order they are
/// written. So a recipe LISTS what it fuses, and every door it mints has exactly that arity —
/// nothing here counts words to decide how many members there are, and nothing trims one away.
///
/// SEVERAL RECIPES over one set of members are ordinary rather than a special case: two
/// declarations naming the same fields at different weights are two semantic wire names, and
/// neither knows about the other.
///
/// # WHAT IT MINTS — the fusion unit, at module scope
///
/// ```text
/// TravelSearchSubsTowerOptions   { zh }                      one member's bound towers
/// TravelSearchShotsTowerOptions  { text, image }
/// TravelSearchFuseOptions        { fusion, subs, shots, subs_towers, shots_towers }
/// TravelSearchFuseQuestion       { question, subs, shots }
/// TravelSearchFusedEvidence<…>   one variant per member, holding THAT member's own evidence
/// TravelSearchFusedError<…>      one variant per member, holding THAT member's own refusal
/// TravelSearch::fuse(…)          the door
/// impl DeclaredSearch for TravelSearch
/// ```
///
/// This is #290's machinery, which a GRAPH ROOT minted until the ONE HOME move: the same packages,
/// the same reciprocal-rank fold, the same nested evidence. What did not come with it is the
/// word-count door law and the modality trims — a recipe LISTS its members, so there is one door of
/// exactly this arity and nothing for a trim to select. The root keeps `fuse` as its INDEX TIER word
/// and mints no fused door at all.
///
/// The DECLARED numbers are what a request that named none runs: `weight` is the coefficient an
/// unconfigured member takes in the fold, and `depth` is the ceiling its own ask is capped at. The
/// declared `limit` rides `DeclaredSearch::LIMIT` rather than the door, which takes the caller's
/// budget — the framework's own answer to *how many* is a codegen constant that becomes an SDL
/// literal, and no door, seam or fold reads it.
///
/// # THE MEMBER WORDS — declared defaults, and the tier they sit in
///
/// `weight = 1.0` is this word's first declaration-side home: it is the member's coefficient in the
/// fold, and an omitting member takes the multiplicative identity. `depth = N` is how deep that
/// member's route is asked. `floor = "…"` is the const its read is floored at.
///
/// Every one of them is a PREFERENCE and every one is omissible. The order that resolves them is
/// request > this recipe > the election's own field > its container > the framework's own number, so
/// an omitted word is a recipe letting the declaration below it answer rather than a recipe with an
/// opinion it did not write down.
///
/// # `tower(<arm>(…))` — a member's ARMS
///
/// An arm binds one tower to one member and is named by the word that opens it. That name is the
/// variant it mints in the member's own question, and it is also the seat it may read: two MEMBERS
/// may each carry an arm called `text`, which is what lets one broadcast reach both; one member may
/// not carry two.
///
/// The tower is named as a TYPE PATH and nothing about it is read here. What it is asked, what it
/// answers, whether its walk is awaited and what its steps seat are all resolved through
/// `SearchTower` and `DeclaredTower`, where the compiler can see them.
///
/// # `shared` — ONE QUESTION, asked once
///
/// The head's `shared(<seat>(type = "…"))` declares the seats a caller fills once for the whole
/// recipe; an arm's own `shared` says it reads one. A seat feeds the arms that share its NAME, and a
/// recipe declaring exactly one seat feeds every `shared` arm from it — the sole-default law the
/// resource axis already states. An arm that writes no `shared` is asked its own question.
///
/// The word also chooses HOW the seat crosses into that arm's question: bare `shared` demands the
/// total conversion, `shared(try)` the fallible one, and `shared(with = "…")` /
/// `shared(try_with = "…")` name a function of the author's — hooks beat traits, an application that
/// owns neither type being unable to write the impl at all.
///
/// # THE FLOORS ARE CONSTS, and a per-leg one has no home here
///
/// `floor = "path::to::CONST"` at either grain, never a literal: a floor is a value in the ENGINE's
/// own currency, which is an open type this framework never sees, so there is nothing here for a
/// number to be parsed into.
///
/// A member's LEGS are its own declaration's — their names, their engines and their currencies are
/// written there — so `floor(…)` naming one is refused. A recipe floors what it can name; a leg
/// floor is a request's, where the leg is already addressed.
///
/// # Refusals
///
/// | written | refused because |
/// |---|---|
/// | a seat, an arm, or any word declared twice | one seat is one question, one arm is one tower, one word is one value |
/// | `shared(…)` twice at the head | two blocks would be two places for one seat to be named |
/// | a seat or an arm naming no type | a word that decided nothing; a member that binds none writes no `tower(…)` |
/// | `shared` on an arm the recipe has no seat for | the broadcast is the head's, and an unmatched arm has no sole seat to fall back to |
/// | two arms of one name on one member | an arm's name is the variant it mints in that member's question |
/// | a struct with no field | a recipe's fields ARE its members |
/// | a tuple struct, a unit struct | a member's name is its field's, and a positional field has none |
/// | an enum or a union | variants are a choice between things rather than a list of them |
/// | a generic parameter | the expansion binds ONE set of members over ONE declaration |
/// | `floor` as a literal | an open currency owes no parsing |
/// | `floor(…)` as a block | the two-clock wall: a recipe cannot name a member's interior legs |
/// | `weight` as an integer, or as a string | a coefficient is a plain decimal, one shape for one number |
/// | `weight` with no finite value | it MULTIPLIES every term, so an infinity makes the fold's order an accident |
/// | `depth` at the head | it is a member's number; the head's is `limit` |
/// | `limit = 0` / `depth = 0` | an answer with no rows is what a caller who wants nothing does not ask for |
/// | a `dedup` word this framework has no join for | the mechanism vocabulary is the framework's |
#[proc_macro_attribute]
pub fn search(
  args: proc_macro::TokenStream,
  item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
  equip(args, item, |input, arguments| {
    search::parse(input, arguments).as_ref().map_or_else(
      syn::Error::to_compile_error,
      ingraph_codegen::search::SearchModel::emit,
    )
  })
}

/// Dress an application's own failure type to RENDER — a declared exchange's error, given a code and
/// a sentence.
///
/// ```ignore
/// #[ingraph::mutation_error]
/// pub enum WatchError {
///   #[ingraph(code = "NOT_A_DIRECTORY", error = "`{0}` is not a directory")]
///   NotADirectory(PathBuf),
///   #[ingraph(code = "ALREADY_WATCHED", error = "{root} is already watched, as watch {id}")]
///   AlreadyWatched { root: String, id: u64 },
/// }
/// ```
///
/// # A CONVENIENCE AND NOT A SEAM
///
/// A hand-written error is exactly as legal. Nothing in this framework asks a failure type for more
/// than a [`Display`](core::fmt::Display) — that is all `error(type = "…")`'s rendering spends, and
/// all the assembled face's error sum spends — so an error that implements it by hand, or through
/// somebody else's derive, is a first-class declared failure. What this word buys is the CODE
/// DISCIPLINE, which nothing checks for a hand-written one.
///
/// # Attributes, per VARIANT, and neither is optional
///
/// - `code = "SCREAMING_SNAKE_CASE"` — what a client MATCHES ON, and the head of everything this
///   variant renders as.
/// - `error = "…"` — what a person READS. A format string over the variant's own fields: `{0}` and
///   `{}` by position, `{name}` by name, `{{` for a literal brace.
///
/// # What it emits
///
/// | item | content |
/// |---|---|
/// | the author's enum, echoed | unchanged but for the markers this macro consumed |
/// | `impl Display` | `"CODE: message"`, one arm per variant, from one literal apiece |
/// | `impl core::error::Error` | the defaulted `source`, this macro having no way to know which field is a cause |
/// | `<Error>::code` | the word this variant is recognised by |
///
/// The declaration is otherwise untouched: its arms, its payloads, its derives, its visibility.
///
/// # THE ENUM OWES A `Debug`, and it is the author's to write
///
/// [`core::error::Error`] has `Debug` as a supertrait, so a declaration wears `#[derive(Debug)]` —
/// or an impl of its own. Nothing here emits one, and the omission is the point: a `Debug` this
/// macro wrote would collide with the derive most error types already carry (`E0119`), and choosing
/// between them by scanning attributes would make the emission depend on which way an author
/// happened to spell it. What an author sees if they forget is rustc naming `Debug` under
/// *required by a bound in `Error`*, at the enum.
///
/// A field the template RENDERS owes a [`Display`](core::fmt::Display); one it never names owes
/// nothing at all, being bound as `_`.
///
/// # THE CODE HEADS THE MESSAGE, so a declaration does not head it again
///
/// An exchange declaring `error(type = "…", code = "…")` puts its own heading in front of whatever
/// the value renders as. An error minted here already carries one, so such an exchange writes
/// `error(type = "…")` and NO `code` word — two headings on one message is two vocabularies with
/// nothing telling a reader which is which.
///
/// # Refusals
///
/// | written | refused because |
/// |---|---|
/// | a variant with no `code` | the code is what a client matches on, and a variant without one is a refusal it cannot tell from its neighbour |
/// | a variant with no `error` | a code with no message under it says nothing to a person |
/// | `code = "notScreaming"` | a code is a machine-read constant, in GraphQL's own convention for one |
/// | two variants under one `code` | a vocabulary is a contract only while it is injective |
/// | a `code` that is one of the framework's own | a client matching it is asking about a refusal this framework raises |
/// | `{name}` naming no field, or `{7}` past the last one | the template reads the variant's own fields |
/// | a struct or a union | an error's VARIANTS are the ways it can fail |
/// | a generic parameter | the expansion writes ONE `Display` over ONE type |
/// | any argument on the attribute itself | every word is written on a variant |
#[proc_macro_attribute]
pub fn mutation_error(
  args: proc_macro::TokenStream,
  item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
  equip(args, item, |input, arguments| {
    error::parse(input, arguments, ErrorRoad::Mutation)
      .as_ref()
      .map_or_else(syn::Error::to_compile_error, ErrorModel::emit)
  })
}

/// [`mutation_error`] for the READ path — the same skeleton, over an author's own query failure.
///
/// ```ignore
/// #[ingraph::query_error]
/// pub enum LookupError {
///   #[ingraph(code = "NO_SUCH_SHELF", error = "there is no shelf called `{0}`")]
///   NoSuchShelf(String),
/// }
/// ```
///
/// # TWO WORDS FOR ONE EMISSION, and that is deliberate
///
/// The items are identical, and deduplicating the two macros into one would delete the only thing a
/// declaration says by choosing between them: which half of the line this failure belongs to. A
/// reader of `#[ingraph::query_error]` knows they are looking at something a read path can raise
/// without going to find out. And the day the two roads want different faces — a `ToErrorCode` row
/// on one of them, a wire attachment on the other — the word is already written and no declaration
/// has to change.
///
/// Every attribute, every emitted item and every refusal is [`mutation_error`]'s; see it for all of
/// them.
#[proc_macro_attribute]
pub fn query_error(
  args: proc_macro::TokenStream,
  item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
  equip(args, item, |input, arguments| {
    error::parse(input, arguments, ErrorRoad::Query)
      .as_ref()
      .map_or_else(syn::Error::to_compile_error, ErrorModel::emit)
  })
}

/// The one body every macro that EQUIPS a declaration has: echo the host, parse, then emit.
///
/// The words that reach it — the source, the tower, the search recipe, the two error roads, the
/// interface, the graph root and the mutation node — equip something the author wrote and mint no
/// field, so what varies between them is only which pass runs and which model emits. TWO member
/// sets left it rather than joined it: the vocabulary and the union rewrite nothing, so each is a
/// derive and neither has a host to echo. `node` is separate because it carries a
/// [`NodeKind`] the others have no use for, and `resource` is separate because a BUILTIN kind word
/// mints a field and puts the declaration behind a cargo gate: it emits the host in two forms,
/// which is one form more than this body has anywhere to put.
///
/// THE HOST IS EMITTED WHETHER OR NOT THE DECLARATION IS ACCEPTED, for the reason `node` states: an
/// attribute macro replaces the item it sits on, so a refusal that emitted only the error would
/// delete the type and bury its own message under every mention of it.
fn equip(
  args: proc_macro::TokenStream,
  item: proc_macro::TokenStream,
  expand: impl FnOnce(&syn::DeriveInput, &[syn::Attribute]) -> proc_macro2::TokenStream,
) -> proc_macro::TokenStream {
  equipped(args, item, host::echo, expand)
}

/// [`equip`] with the ECHO handed in — for the one declaration whose host is not echoed plainly.
///
/// A mutation node's is not: it is a VOCABULARY rather than data, so nothing constructs one and
/// rustc's *never constructed* would be reported inside an expansion its author cannot edit. See
/// [`host::echo_vocabulary`], which carries the reason in the attribute it writes.
///
/// A parameter rather than a second copy of this body, because the body IS the shape: echo, parse,
/// emit, in that order, with the host emitted whether or not the declaration is accepted.
fn equipped(
  args: proc_macro::TokenStream,
  item: proc_macro::TokenStream,
  echo: fn(&syn::DeriveInput) -> proc_macro2::TokenStream,
  expand: impl FnOnce(&syn::DeriveInput, &[syn::Attribute]) -> proc_macro2::TokenStream,
) -> proc_macro::TokenStream {
  let input = syn::parse_macro_input!(item as syn::DeriveInput);
  let arguments = host::options(args.into());
  let host = echo(&input);
  let expansion = expand(&input, &arguments);
  quote::quote!(#host #expansion).into()
}

/// The one body every node macro has: echo the host, parse under this KIND, then emit.
///
/// The kind is the only thing that differs between them, which is the split's whole content — one
/// grammar, one emitter, and a word deciding which storage block the declaration may write and
/// whether the emission mints the one-storage marker.
///
/// THE HOST IS EMITTED WHETHER OR NOT THE DECLARATION IS ACCEPTED, and that is not a detail. An
/// attribute macro replaces the item it sits on, so a refusal that emitted only the error would
/// delete the type — and every mention of it elsewhere in the crate would become a second error
/// burying the first. The refusal rides beside the type it is about.
fn node(
  args: proc_macro::TokenStream,
  item: proc_macro::TokenStream,
  kind: ingraph_codegen::model::NodeKind,
) -> proc_macro::TokenStream {
  let input = syn::parse_macro_input!(item as syn::DeriveInput);
  let options = host::options(args.into());
  let parsed = parse::parse(&input, &options, kind);
  // A FAN-IN carries its ancestry in a field the emitter mints, for `derived`'s reason one tier
  // over: which columns a row's ancestry has depends on which upstream produced it, so there is no
  // set of columns for the declaration to write. A refused declaration is echoed WITHOUT it, and
  // for the same honest reason — the field's type is the lineage the parse would have named.
  // A REWRITE replaces the item outright — see [`host::transparent`] — and only an ACCEPTED one
  // does. A refusal echoes the author's own struct back unchanged, for the journal's reason: the
  // wrapper is built from a path the refusal may be about, and emitting a wrapper over a type that
  // resolves to nothing would bury the sentence that named the real mistake.
  let host = match parsed.as_ref().ok() {
    Some(model) if model.remote.is_some() => {
      host::transparent(&input, model.remote.as_ref().expect("a rewrite's own path"))
    }
    accepted => match accepted.and_then(RecordModel::fanned_lineage) {
      Some(field) => host::echo_carrying(&input, field),
      None => host::echo(&input),
    },
  };
  let expansion = parsed
    .as_ref()
    .map_or_else(syn::Error::to_compile_error, RecordModel::emit);
  quote::quote!(#host #expansion).into()
}

/// Declare a FLAGS SET — a closed vocabulary of BITS a column holds a SUBSET of.
///
/// The vocabulary kind's sister, and the difference is the arity of an answer: an enum column holds
/// ONE of the names and a flags column holds any combination of them. So this word buys the
/// set-theoretic questions an enum has no way to ask — `hasAll`, `hasAny`, `hasNone`, a boolean per
/// declared flag — and the object face that publishes a value's dozen readings.
///
/// ```ignore
/// #[ingraph::flags(u32)]
/// #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
/// pub enum TrackDisposition {
///   /// The default track for its kind.
///   Default = 0x1,
///   Forced = 0x2,
///   HearingImpaired = 1 << 2,
/// }
/// ```
///
/// # THIS WORD GOES ABOVE THE DERIVES
///
/// rustc expands the topmost attribute on an item first, and `derive` takes its turn in that order.
/// A derive written ABOVE this word expands against the MANIFEST — the enum that is about to stop
/// existing — and lands an impl matching on `TrackDisposition::Default`, a variant the expansion
/// replaced with a const. Written below, the derives are forwarded onto the type `bitflags!` mints
/// and expand against it.
///
/// The hazard cannot be detected here: a derive that already expanded is gone from the item's
/// attributes by the time this door runs, and is indistinguishable from one nobody wrote.
///
/// # An ATTRIBUTE, and a manifest that does not survive
///
/// The expansion is a `bitflags!` struct with `TrackDisposition::DEFAULT`, `::FORCED` and
/// `::HEARING_IMPAIRED` on it. The enum above is a MANIFEST: it is read for its names and values and
/// then replaced. That is why the word is an attribute rather than a derive — a derive may only
/// APPEND, and the type here is minted rather than kept — and it is why the manifest's own lints
/// never fire, since rustc never sees an enum to have an opinion about.
///
/// The manifest is an `enum` because a set of NAMES with VALUES is what an enum spells; a struct
/// body cannot hold `NAME = 0x1`, and putting the bits in the attribute would leave a bit's doc
/// comment nowhere to go.
///
/// # The bits are EXPLICIT, and that is this kind's one added refusal
///
/// A bit with no value is refused. An implicit numbering would come from a bit's POSITION, so
/// reordering the declaration — the most ordinary edit there is — would rewrite every stored row in
/// silence. The vocabulary kind can default a discriminant because a reordered enum still stores
/// what it stored; this one cannot.
///
/// A value is one bit, inside the declared width, declared once. Composite masks are refused in v1:
/// `bitflags` allows them and they would leave the per-flag fan with no single answer to *is it
/// set*.
///
/// # What it emits
///
/// | item | condition |
/// |---|---|
/// | the `bitflags!` type, carrying the author's own attributes | always |
/// | `FlagsValue`, giving the SDL name and the wire field per bit | always |
/// | `FlagsFilterMarker`, giving `FlagsFilter<Self>` | always |
/// | `DefaultMarker` / `DefaultVecMarker`, giving `FlagsMarker<Self>` | always |
/// | `CursorValue` over the BIT PATTERN, big-endian and width-checked | always |
/// | `ColumnKind` and `Assemble` | `ColumnKind` always, `Assemble` behind the SQL family |
/// | `sqlx::Type`/`Encode`/`Decode` and `Carrier` | per declared ∩ compiled-in backend |
/// | `ToGraphqlOutput` → `FlagsView<Self>`, `ToGraphqlInput` → `FlagsInput<Self>` | behind the BINDING gate |
///
/// The wire FACE is not among them, which is the biggest saving over the vocabulary kind: a flags
/// type's object and operand seats are generic in `ingraph` and read the bit table at runtime, so a
/// declaration names which seat each direction takes and the framework writes both.
///
/// # `graphql(rename = "…")` — WHAT A SCHEMA CALLS THIS SET
///
/// ```ignore
/// #[ingraph::flags(u32, graphql(rename = "TrackDisposition"))]
/// pub enum TrackDispositionFlags { Default = 0x1 }
/// ```
///
/// THREE published names come off one word — the object face takes it, the operand scalar is
/// `<it>Input` and the filter input object is `<it>Filter` — because all three are composed from the
/// single string `FlagsValue::GRAPHQL_NAME` carries. Defaults to the Rust name unraw'd.
///
/// EMISSION-ONLY: the `bitflags!` type keeps its own name, every bit keeps its `const`, and a stored
/// bit pattern has no word for this to move. A schema entity's word is not a Rust identifier, so
/// `rename = "type"` is writable here where a BIT's word is not — a bit becomes a `const` a caller
/// writes `Self::…` to reach.
///
/// # `remote = "…"` — MIRRORING a flags set another crate owns
///
/// ```ignore
/// #[ingraph::flags(u32, remote = "upstream::TrackDisposition")]
/// #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
/// pub enum TrackDisposition {
///   Default = 0x1,
///   #[ingraph(rename = "HEARING_IMPAIRED")]
///   Hi = 1 << 2,
/// }
/// ```
///
/// The declaration RESTATES the upstream's bits — names AND numbers, both — and this word adds the
/// crossing: `From` in each direction, by `from_bits_retain`, so a bit the declaration never named
/// survives the round trip rather than being truncated away. That absorption is what keeps an
/// upstream release growing a bit from breaking a build; the strict doors are unmoved, so such a bit
/// is still refused at an operand, a stored column and a cursor.
///
/// **The restatement is checked at COMPILE TIME.** Every restated bit emits
/// `const _: () = assert!(Local::X.bits() == Remote::X.bits());`, so an upstream that RENUMBERS one
/// is an error at the bit that drifted rather than a mirror that quietly means something else.
/// `#[ingraph(rename = "…")]` names the upstream `const` in this mode — a mirror's words are its
/// own, a flags column storing its bit pattern — and a `const` the upstream has not got is `E0599`
/// at the token that claimed it.
///
/// A mirror is a flags set in every other respect: the same minted type, the same stored pattern,
/// the same two seats. A declaration naming no upstream is untouched by the axis, down to the token.
///
/// **Its own teeth:** an upstream that is not a `bitflags!` set (`E0277` on `bitflags::Flags`, at
/// the `remote = "…"` token); one whose bits are carried at another width (a named `E0277` there);
/// a `rename` that is not an identifier (refused at the door). An upstream bit this declaration does
/// not restate is NOT refused — it is absorbed on purpose, and what names it is a test-time pin over
/// `<Remote as bitflags::Flags>::FLAGS`, the upstream's own table.
///
/// # Teeth
///
/// A struct or union rather than an enum; an enum with no variants; a variant carrying data;
/// generics; a bit with no value, a value of `0`, a value past the declared width, a value setting
/// more than one bit, or an expression this door cannot evaluate; two bits on one value; two bits
/// spelling one word or one wire field; a `rename` that is not a GraphQL name, at the bit or at the
/// declaration; a width the carrier table does not hold; an `#[ingraph(…)]` left on the item where
/// the attribute's own parentheses are.
///
/// What is NOT refused here is the type's own `Copy`/`Eq`/`Debug`: those are asked by the bounds the
/// rows spend, and a declaration missing one gets `E0277` naming the trait at the type — where a
/// token-level check would refuse a correct program whose `impl Copy` is hand-written.
#[proc_macro_attribute]
pub fn flags(
  args: proc_macro::TokenStream,
  item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
  let input = syn::parse_macro_input!(item as syn::DeriveInput);
  let options = host::options(args.into());
  match flags::parse(&input, &options) {
    Ok(model) => model.emit().into(),
    // THE TYPE SURVIVES A REFUSAL, for the reason `derived` states: an attribute macro replaces the
    // item it sits on, so an expansion that emitted only the error would delete the author's type
    // and bury its own message under every mention of it.
    Err(refused) => {
      let refusal = refused.to_compile_error();
      let salvaged = flags::salvage(&input, &options);
      quote::quote! { #refusal #salvaged }.into()
    }
  }
}

/// Equip a VOCABULARY — a unit-variant enum — with the WHOLE citizenship: the faces a column of it
/// needs, and the face a schema needs.
///
/// A vocabulary is a value, not a node: it owns no storage of its own, subscribes to nothing and
/// has no key. What it needs is what a COLUMN of it needs plus the words its faces spell it as, and
/// this derive writes exactly that.
///
/// ```ignore
/// #[derive(Debug, Clone, Copy, PartialEq, Eq, ingraph::Enum)]
/// #[repr(u8)]
/// pub enum Codec { H264, Vp9 }
///
/// #[ingraph::record(sqlite)]
/// pub struct Take {
///   #[ingraph(id)] id: i64,
///   #[ingraph(r#enum)] codec: Codec,   // declares, filters and compares
/// }
/// ```
///
/// # ONE DOOR, and the second one was deleted
///
/// The storage citizenship and the wire face were two words — `#[ingraph::enumeration]` and a
/// `GraphqlEnum` derive — on the reading that they are two organs a declaration should be able to
/// take one of. They are ONE word now, and each defence of the split fell on re-derivation: schema
/// presence is REACHABILITY (an enum no wire type names never enters an SDL, so a second macro was
/// never the gatekeeper), unused storage impls on a pure-wire enum are harmless, and the wire face
/// sits behind the binding gate regardless. What the split cost was a silent composition-order trap,
/// two entry points onto one model, and one set of `#[ingraph(…)]` markers read by two grammars.
///
/// # A DERIVE, and the test every word in this family is put to
///
/// Most words here are attribute macros because those words REWRITE the item they sit on — a
/// derived index carries a field the declaration did not write, a record's fields take a visibility
/// stamp. This one rewrites nothing: it adds impls beside a type, which is what a derive is for.
/// Its helper attributes are INERT rather than consumed, which is the property that makes one set of
/// variant words readable without an ordering rule.
///
/// The test is the REWRITE and not the subject, which is why [`Union`](macro@union) followed:
/// equipping a payload-carrying enum somebody else declared is the same nothing-rewritten shape, so
/// it takes the same form. An INTERFACE does not follow them, and not for want of trying — see that
/// word for what it is that differs.
///
/// # Storage is machine-facing, and the wire is not
///
/// A DECLARATION THAT SAYS NOTHING IS COMPLETE. Every database stores the DISCRIMINANT, at the
/// width the enum's own `#[repr(…)]` names (`i64` without one), and the wire shows the NAME in
/// `SCREAMING_SNAKE_CASE`. Nothing has to be written to get either: a column exists for a machine
/// and a schema exists for a person. The two meet at the FILTER — an operand crosses as the enum
/// itself — so a user's text never reaches an integer column as text.
///
/// # Attributes
///
/// On the enum, in the derive's own `#[ingraph(…)]` beside it:
///
/// - `crate = "path::to::ingraph"` — where `ingraph` lives, for a re-export shim or a renamed
///   dependency. Defaults to `::ingraph`, exactly as [`record`]'s does.
/// - `sqlite(…)`, `postgres(…)`, `mysql(…)`, `mongo(…)`, `graphql(…)` — ONE BLOCK PER FACE, each
///   naming `text` or `integer`. Every one is an OVERRIDE of that face's default, and a face left
///   undeclared keeps it.
/// - `graphql(rename = "…")` — what a SCHEMA calls this vocabulary, beside the wire face's form and
///   answering a different question. Defaults to the Rust name unraw'd; a closed vocabulary moves its
///   `enum`, an open one and a mirror move their `scalar`. EMISSION-ONLY — the Rust type, the refusal
///   type and every stored word are untouched — and legal in all four cells of the mode table, where
///   the FORM words are not. A schema entity's word is not a Rust identifier, so `rename = "type"`
///   is writable.
/// - `error(rename = "Name")` — what the emitted REFUSAL type is called. `Record`'s `key(…)` block
///   in this grammar, and for the same reason: `rename` names the type its block is about. Defaults
///   to `<Enum>ParseError`.
/// - `remote = "path::to::Upstream"` — this declaration RESTATES that vocabulary rather than being
///   one. See *The MIRROR mode* below, which is where the rest of this grammar changes meaning.
/// - `delegate(fn name(&self) -> T, …)` — the upstream methods this mirror forwards, each restated
///   as a signature. MIRRORS only. The receiver is `&self` or `&mut self`, and an entry may wear
///   `#[graphql(<backend>)]` to be PUBLISHED — see *The MIRROR mode* below.
///
/// On a variant:
///
/// - `rename = "…"` — the CANONICAL word, which every face that states none defaults from. On a
///   MIRROR it names the UPSTREAM VARIANT this one restates: there is no word of this declaration's
///   for it to move.
/// - `sqlite(rename = "…")` … `graphql(rename = "…")` — what ONE face spells it. Not on a mirror,
///   which spells every face alike.
/// - `other` — MIRRORS only, and marks the ESCAPE: the one variant carrying a word rather than
///   restating a name. Exactly one, or none.
///
/// ```ignore
/// #[derive(Debug, Clone, Copy, PartialEq, Eq, ingraph::Enum)]
/// #[ingraph(postgres(text))]
/// pub enum Grade {
///   #[ingraph(rename = "lo", postgres(rename = "LO"), graphql(rename = "LOW"))]
///   Low,
///   High,
/// }
/// ```
///
/// | form | the face holds | the default |
/// |---|---|---|
/// | `integer` | the variant's DISCRIMINANT, the declaration's own | every database |
/// | `text` | the variant's word in THAT face | the wire |
///
/// A `#[repr(…)]` is read where it decides a column: `#[repr(u8)]` is a `u8` column on SQLite and
/// MySQL and a `SMALLINT` on Postgres, which carries no unsigned type — the framework's own carrier
/// widening, restated. Only the widths that table covers may be stored, so `#[repr(u64)]` and its
/// neighbours are refused where a face would render one.
///
/// A variant with no wire rename is `SCREAMING_SNAKE_CASE` of its own name — `Vp9` is `VP9` — which
/// is GraphQL's own convention. That casing comes from the SAME function `as_graphql_str` is written
/// from, so the word a caller reads in Rust and the value a client writes in a document are one
/// string from one table.
///
/// # What it emits
///
/// | item | condition |
/// |---|---|
/// | `EnumFilterMarker`, giving `EnumFilter<Self>` | always |
/// | `DefaultMarker`, giving `EnumMarker<Self>` | always |
/// | `CursorValue`, over the canonical word | always |
/// | `VARIANTS`, `as_str`, `is_<variant>` | always |
/// | `<Enum>ParseError` and `FromStr` over the canonical word | always |
/// | `as_<face>_str` and `TryFrom<&<Face>Name>` | per TEXT face |
/// | `sqlx::Type`, `sqlx::Encode`, `sqlx::Decode`, `Carrier` | per SQL backend, GATED |
/// | `EnumType`, `InputType`, `OutputType` | behind the BINDING gate |
///
/// The storage rows are **per backend and behind that backend's gate**, so they exist for each
/// database this build compiled and nowhere else: a declaration in a build with one driver is
/// audited against that driver, and a party demanding another's row gets `E0277` where it demands
/// it. The FACE is not gated — a word names no driver — and what decides whether a face has one is
/// its FORM.
///
/// The WIRE face is behind the binding gate, so a build of `ingraph` without `async-graphql`
/// compiles that half to nothing at all. It is hand-written rather than derived, which is what keeps
/// `description: None` a fact of the emission: async-graphql's own derives call `get_rustdoc`
/// unconditionally with no key to decline it, so a derived face publishes whatever the declaration
/// happened to document, and this crate's rule is that a schema says what a declaration SAYS it
/// says. Which SCHEMA a vocabulary reaches is REACHABILITY and nothing else — a schema is walked
/// from its roots, so an enum no wire type names is absent from the SDL however many impls it
/// carries.
///
/// The FILTER's wire face is not here and needs no declaration: `EnumFilter<T>` is `ingraph`'s own
/// type, so one generic `InputType` row there serves every declared enum at once. What this door
/// mints is the half only the declaring crate can — an impl on its own type.
///
/// The method face is hand-written by this crate rather than derived from anywhere: no
/// `derive_more`, so the expansion names no foreign path and the refusal type is the vocabulary's
/// own.
///
/// The REFUSAL is also the one type this expansion puts in the DECLARING scope — everything else
/// sits inside an anonymous `const`, where it collides with nothing — which is why it alone takes a
/// name. `error(rename = "…")` is the escape when the scope already holds a `<Enum>ParseError`, and
/// it moves the TYPE and not the sentence: the message names the vocabulary either way.
///
/// **No MongoDB storage row.** `MongoCarrier` is the seam it would take, and a MongoDB vocabulary
/// writes that one impl by hand until a lane exists that can compile a generated one —
/// `mongo(text)` gives it `as_mongo_str` and `TryFrom<&MongoName>` to write it with.
///
/// # Refusals
///
/// The declaration's SHAPE is the vocabulary, so each part of it is checked here rather than left
/// to fail inside the expansion: a non-enum, an enum with no variants, a variant that carries data,
/// and any generic parameter. More come with the faces — a rename under a face that stores the
/// discriminant, two variants colliding in ONE face's namespace, two variants deriving one
/// `is_<variant>`, and a name outside GraphQL's own Name grammar, asked of the enum itself and of
/// every wire rename. One comes with the refusal type: `error(rename = "…")` naming the enum
/// itself, which the expansion would land in the same scope twice. A default name colliding with
/// something ELSE in that scope is not refused here and cannot be — the scope's contents are not the
/// macro's to see — so it stays rustc's duplicate definition, and the rename is what answers it.
///
/// What is NOT refused here is the enum's own `Copy`/`Eq`: async-graphql's `EnumType` bound demands
/// them, so a declaration missing one gets `E0277` naming the trait at the enum in a build carrying
/// the binding. A token-level check for a `#[derive(Copy)]` would refuse a declaration whose
/// `impl Copy` is hand-written, which is a correct program.
///
/// # The MIRROR mode
///
/// `#[ingraph(remote = "…")]` says the declaration RESTATES a vocabulary another crate owns — the
/// orphan rule being why the restatement exists at all — and the whole emission changes with it.
/// `ingraph-codegen`'s `enumeration::remote` carries the design; what a declaration has to know is
/// four things.
///
/// **The restatement is IDENTIFIERS.** Every word comes from the upstream's own `Display` and
/// `FromStr`, through the `remote()` gate this mode always emits, so a mirror takes no per-face
/// `rename` and no `text`/`integer` form: an upstream vocabulary spells itself, in one word, in
/// every face. That is also why `rename` names an upstream VARIANT here rather than a word.
///
/// **`#[ingraph(other)]` is the openness, declared.** Its presence says the upstream vocabulary is
/// open, and both directions of that claim are settled by the compiler at the site the claim is
/// spent: an escape over an upstream whose parse can REFUSE is a named `E0277` at the
/// `remote = "…"` token, and NO escape over an upstream that has more variants than this mirror
/// names is `E0004` at a `From` whose arms are exhaustive.
///
/// **The marker takes ONE optional cell, and it says where the totality LIVES.** The bound above
/// reads the upstream's `FromStr::Err`, which a crate whose parse is total in behaviour and
/// refusable in type fails while handing out a perfectly total gate. `from` names a gate that
/// cannot refuse, `try_from` one that can — the conversion family's own pair, and exactly one of
/// them:
///
/// | posture | totality lives in | `FromStr::Err` | `error(rename = "…")` |
/// |---|---|---|---|
/// | `other` | `<Remote as FromStr>::Err` | `Infallible` | refused |
/// | `other(from = "…")` | the gate's SIGNATURE | `Infallible` | refused |
/// | `other(try_from = "…")` | nowhere — the door can refuse | `<Enum>ParseError` | LEGAL |
///
/// The last is HALF-OPEN: open outward, where the `From<Remote>` wildcard still absorbs an upstream
/// value this mirror does not restate, and closed inward, where a word neither the parse nor the
/// gate accepts is this vocabulary's own refusal. Its gate refuses with `<Remote as FromStr>::Err`
/// and no other type. Every posture PARSES FIRST, a gate answering only for what the upstream's own
/// parse turned away.
///
/// **An open mirror ABSORBS what it did not name**, so an upstream release that grows a variant does
/// not break a build — and the absence is therefore named at TEST time, by a per-variant round-trip
/// pin walking the upstream's roster against `VARIANTS`.
///
/// **The wire face is a SCALAR**, not a GraphQL `enum`: a mirror's value set is the upstream's, so
/// an SDL member list here would publish a set this crate cannot keep true. The reference family —
/// `AsRef`, `Deref`, `Borrow` — is absent and cannot be sound: a restatement is not a wrapper, and
/// the escape holds a word rather than an upstream value.
///
/// # `delegate(fn …)`, and the two things an entry may say
///
/// An entry is a SIGNATURE, restated because Rust has no `typeof`, and this expansion writes the
/// body. Two axes move it:
///
/// **The RECEIVER.** `&self` forwards — materialize the upstream, call, hand the answer back.
/// `&mut self` WRITES BACK — materialize, mutate, convert home through this mirror's own `From` —
/// which costs two conversions per call and is what makes a mutating upstream method reachable at
/// all, a mirror storing a word rather than an upstream value. A consuming `self` and a signature
/// with no receiver are refused at the receiver the declaration wrote.
///
/// **`#[graphql(<backend>)]`,** an outer attribute on the entry, PUBLISHES that method. It is an
/// adjective on a noun: the entry is still a function, and the word only says it also reaches a
/// schema. `#[graphql(async_graphql(rename = "…"))]` moves the published word, which is the whole of
/// v1's knob.
///
/// ```ignore
/// #[ingraph(remote = "upstream::Codec", delegate(
///   fn to_u32(&self) -> Option<u32>,
///   #[graphql(async_graphql)]
///   fn is_lossless(&self) -> bool,
///   #[graphql(async_graphql(rename = "intra"))]
///   fn is_all_intra(&self) -> bool,
/// ))]
/// ```
///
/// **ONE published delegate PROMOTES the output seat**, because a word cannot carry a selection set:
/// the mirror renders as an OBJECT under its own name — `text`, the canonical slug, plus one field
/// per published method — and the scalar retreats to the INPUT seat under `<Enum>Input`. That is the
/// declared union's naming law, for the union's own reason: two schema types on one Rust type, and a
/// schema has one namespace for type names. A mirror that publishes nothing is untouched by any of
/// it, down to the emitted token.
#[proc_macro_derive(Enum, attributes(ingraph))]
pub fn r#enum(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
  let input = syn::parse_macro_input!(item as syn::DeriveInput);
  // NO host is emitted, which is the whole difference from the attribute family: a derive is handed
  // a COPY of the declaration and the compiler keeps the original, so a refusal here rides beside
  // the type without having to re-emit it — and the `#[ingraph(…)]` markers it reads stay on the
  // item, inert, where an attribute macro's echo would have had to strip them.
  r#enum::parse(&input)
    .as_ref()
    .map_or_else(
      |refused| refused.to_compile_error(),
      ingraph_codegen::enumeration::EnumModel::emit,
    )
    .into()
}

/// Equip a DECLARED UNION — an enum whose every variant carries one member type.
///
/// A union is a CHOICE between types, and the declaration is the choice: one variant per member,
/// each carrying that member and nothing else. The derive does not write the enum — the user does,
/// or a compiler line that read a schema does — exactly as `Enum` equips a vocabulary somebody
/// else declared.
///
/// ```ignore
/// #[derive(ingraph::Union)]
/// #[ingraph(graphql(async_graphql(output, input)))]
/// pub enum SearchResult {
///   Media(Media),
///   Video(Video),
/// }
/// ```
///
/// # A DERIVE, on [`Enum`](macro@r#enum)'s own doctrine
///
/// The declaration family are attribute macros because those words REWRITE the item they sit on.
/// This one rewrites NOTHING — it adds impls beside a type somebody else wrote — so it is a derive,
/// and it gains what a derive gains: a refusal rides BESIDE the declaration instead of replacing it,
/// and the `#[ingraph(…)]` markers stay on the item, inert.
///
/// The INTERFACE beside it stays an attribute, and that is not inertia: an interface is a member set
/// with a CONTRACT over it, which is a different declaration with different semantics and a
/// different wire. Nothing in this word touches any of the three. What the two DO share is the
/// member-set walk and the unwrap face the seam emits, and both are untouched by the form this word
/// takes.
///
/// # Which unions this is for
///
/// The DECLARED ones: a schema's `union SearchResult = Media | Video`, and its input-position twin.
/// The framework's other payload enums are the FAN-IN ones a node with several upstreams gets, and
/// those are the node macros' own emission — nobody writes them, so there is nothing to apply a
/// derive to.
///
/// # Attributes
///
/// On the enum, in the derive's own `#[ingraph(…)]` beside it:
///
/// - `crate = "path::to::ingraph"` — where `ingraph` lives, for a re-export shim or a renamed
///   dependency. Defaults to `::ingraph`, exactly as [`record`]'s does. It was absent while the
///   whole emission was `core`; a declared wire face names the shelf and the binding gate, which is
///   what bought it.
/// - `unwrap_error(rename = "Name")` — what the emitted REFUSAL type is called. `Record`'s `key(…)`
///   block in this grammar. Defaults to `<Union>UnwrapError`. The word is `unwrap_error` and not
///   `error` because `error` names the CONVERSION CELLS — one per leg, inside a database's block —
///   and the old spelling is a named migration refusal.
/// - `graphql(<backend>(output, input))` — the SCHEMA POSITIONS this union is rendered at. Both
///   words are optional and a block naming neither is refused; a declaration writing no `graphql(…)`
///   at all is today's union exactly, with a Rust face and no schema presence.
///
/// A variant takes no entries at all — a member is addressed by the TYPE it carries.
///
/// # `input` and `output` are a BACKEND's sub-axis
///
/// They are entries of `<backend>(…)` rather than of `graphql(…)`, which is the tree's axis law
/// unchanged: a DOMAIN block, then a BACKEND block, then that cell's entries. Which positions a type
/// is rendered at is a backend's own rendering, as `attrs(…)` and `skip` are on the record's
/// grammar. The union is the only declaration consuming the pair today; a second consumer writes the
/// same two words at the same depth.
///
/// # What a schema calls the two faces
///
/// Both are impls on the ONE Rust type the declaration already named, and a GraphQL schema has ONE
/// namespace for type names. So:
///
/// | declared | the output is called | the input is called |
/// |---|---|---|
/// | `output` | `SearchResult` | — |
/// | `input` | — | `SearchResult` |
/// | both | `SearchResult` | `SearchResultInput` |
///
/// A single face takes the union's own name, having nothing to collide with. Where both are
/// rendered the OUTPUT keeps it — it is the name a client writes in a selection set — and the input
/// derives `<Union>Input`. `input(rename = "…")` moves that word at either arity, and
/// `output(rename = "…")` moves the other — carrying the derived twin with it, so a `Pick` renamed to
/// `Sighting` publishes `Sighting` and `SightingInput`. Two faces resolving to ONE word is refused at
/// whichever one wrote it.
///
/// # What it emits
///
/// One block per member, and a refusal type beside the enum:
///
/// | item | receiver |
/// |---|---|
/// | `const fn is_<member>` | `&self` |
/// | `unwrap_<member>` · `unwrap_<member>_ref` · `unwrap_<member>_mut` | `self` · `&self` · `&mut self` |
/// | `try_unwrap_<member>` · `try_unwrap_<member>_ref` · `try_unwrap_<member>_mut` | the same three |
///
/// The `unwrap` family panics with a message naming the variant asked for and the one held; the
/// `try_unwrap` family answers with `<Union>UnwrapError`, which carries that same pair and reads it
/// out through `asked()` and `held()`. Its FIELDS are private, so nothing outside the declaring
/// module builds one.
///
/// The suffixes are `derive_more`'s `#[unwrap(ref, ref_mut)]` semantics restated as this crate's
/// own. `derive_more` is not a dependency: its `TryUnwrapError` would put a foreign path in every
/// consumer's expanded code and a foreign type in the signatures a caller writes.
///
/// One consequence is worth knowing before reaching for the owned receiver: `try_unwrap_<member>`
/// takes `self`, and on a refusal the value it was called on is DROPPED. One refusal type serves
/// all three receivers — a borrowing one has nothing owned to hand back — so there is nowhere for
/// it to travel. `is_<member>` is the check that costs nothing.
///
/// And, per declared position, the impls that position is rendered through — `ContainerType`,
/// `OutputType` and `UnionType` for the output; `InputType`, `InputObjectType` and `OneofObjectType`
/// for the `@oneOf` input, whose seats are one NULLABLE seat per member named in lower camel case
/// off the variant's own spelling. Both are HAND-WRITTEN and both ride the BINDING GATE, so a build
/// of `ingraph` without `async-graphql` expands them to nothing at all.
///
/// Hand-written because a derive may only APPEND: there is nowhere to put
/// `#[derive(async_graphql::Union)]` on an enum this word never rewrites, and a `#[cfg_attr]` could
/// not stand in — that predicate asks whether the DECLARING crate has a feature called
/// `async-graphql`, which is a different manifest and usually no feature at all. It is also what
/// keeps `description: None` a fact of the emission, for the reason [`Enum`](macro@r#enum)'s face
/// states.
///
/// **No storage.** A union is not a column: both declared positions are wire shapes, so nothing
/// persists one.
///
/// # Refusals
///
/// The declaration's SHAPE is the union, so each part of it is checked here rather than left to
/// fail inside the expansion: a non-enum, an enum with no variants, a variant carrying no member,
/// one carrying several, one carrying its member in a NAMED field, and any generic parameter.
///
/// Two more are about the member SET. Two variants carrying ONE type break GraphQL's own law —
/// *a union type must include one or more unique member types* — and two variants whose words are
/// one word derive one method seven times over. A last one comes with the refusal type:
/// `unwrap_error(rename = "…")` naming the enum itself, which the expansion would land in the same
/// scope twice.
///
/// The wire word brings its own: `graphql(…)` twice, a backend nobody ships, a backend twice, a
/// backend dressing NO position, either position twice, an option on `output`, an entry `input(…)`
/// does not take, a rename outside GraphQL's own Name grammar, and a rename onto the word the output
/// face already publishes.
///
/// One refusal is the COMPILER's and is named all the same. A member of a union declaring `input`
/// needs an `async_graphql::InputType` of its own, which no macro can see — so the expansion asks
/// for it through a marker carrying this framework's sentence, spanned at the member's own type.
#[proc_macro_derive(Union, attributes(ingraph))]
pub fn union(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
  let input = syn::parse_macro_input!(item as syn::DeriveInput);
  // NO host is emitted, for the reason `Enum` states: a derive is handed a COPY of the declaration
  // and the compiler keeps the original, so a refusal here rides beside the type without having to
  // re-emit it.
  union::parse(&input)
    .as_ref()
    .map_or_else(
      |refused| refused.to_compile_error(),
      ingraph_codegen::union::UnionModel::emit,
    )
    .into()
}

/// Equip a NEWTYPE — a type this crate declares that wraps ONE value — with the faces it names.
///
/// ```ignore
/// #[derive(Debug, Clone, PartialEq, ingraph::NewType)]
/// #[ingraph(
///   graphql(async_graphql(scalar(parse = "Language::parse"), input, output)),
///   marker(string),
///   filter,
///   cursor,
///   sqlite,
/// )]
/// pub struct Language(smol_bytes::Utf8Bytes);
/// ```
///
/// # What each KIT installs
///
/// Every row below DELEGATES to the wrapped type. Nothing is inferred: a face this declaration does
/// not name is a face the expansion does not write.
///
/// | word | rows |
/// |---|---|
/// | `graphql(<backend>(scalar(…)))` | the type's own GraphQL scalar — its `parse`, its `is_valid` and its rendering |
/// | `graphql(<backend>(input))` | `ToGraphqlInput` — what ONE operand crosses on |
/// | `graphql(<backend>(output))` | `ToGraphqlOutput` — what a wire face returns it as |
/// | `marker(<family>)` | `DefaultMarker` and `DefaultVecMarker` — the interpretation a FIELD of it is read under |
/// | `filter` | the family's filter, reached through a reading this device mints beside the type |
/// | `cursor` | `CursorValue` — a keyset position |
/// | `sqlite` / `postgres` / `mysql` | that dialect's `Type`, `Encode`, `Decode` and bind, plus the width and the read every dialect shares |
///
/// # The DOOR is one source, and every READ spends it
///
/// `scalar(parse = "…")` names a `fn(&str) -> Result<Self, E>` and `scalar(check = "…")` a
/// `fn(<the inner type>) -> Result<Self, E>`; a declaration writes at most one. Where one is
/// written, EVERY path a value arrives on goes through it — the scalar's `parse` and `is_valid`, the
/// cursor's `read_cursor`, and the dialect decode — so a column holding a value this type refuses is
/// a decode error rather than a value whose type says it cannot exist.
///
/// A WRITE spends nothing: the value is one this type already holds, so the wrapped type's own row
/// is the whole answer.
///
/// # The wire block is the union's AXIS, at the union's depth
///
/// `graphql(<backend>(…))` — a DOMAIN block, then a BACKEND block, then that cell's entries. A wire
/// word written one level up is refused as an unknown BACKEND, which is what it is.
///
/// # Refusals
///
/// A declaration that is not a struct, or does not hold exactly one field. A `filter` with no
/// `marker(<family>)` beside it — the filter kind is the family's, so the word alone names nothing.
/// A declaration naming NO kit, whose expansion would be empty. Two doors in one `scalar(…)`. A word
/// declared twice at any depth. And every word the roster carries whose kit this round has not
/// built, refused BY NAME with what it would install and what to write instead.
#[proc_macro_derive(NewType, attributes(ingraph))]
pub fn newtype(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
  let input = syn::parse_macro_input!(item as syn::DeriveInput);
  // NO host is emitted, for the reason `Enum` states: a derive is handed a COPY of the declaration
  // and the compiler keeps the original, so a refusal here rides beside the type without having to
  // re-emit it.
  newtype::parse(&input)
    .as_ref()
    .map_or_else(
      |refused| refused.to_compile_error(),
      ingraph_codegen::newtype::NewTypeModel::emit,
    )
    .into()
}

/// Equip an ID WRAPPER — a `#[repr(transparent)]` type holding one value — with the whole register
/// an address needs.
///
/// ```ignore
/// #[derive(ingraph::Id)]
/// #[repr(transparent)]
/// pub struct TrackId(uuid::Uuid);
/// ```
///
/// That is the entire declaration. There is no kit word, no `#[derive(Clone, PartialEq, Eq, Hash)]`
/// beside it and no hand-written row after it: the type stands at a record's `#[ingraph(id)]`, at an
/// aggregate's `#[ingraph(group)]`, in a filesystem path, in a SQL column, on a cursor and in a
/// schema, from this word alone.
///
/// # Named for the trait it ADMITS
///
/// `#[derive(Clone)]` gives you `Clone`; this gives you [`Id`](ingraph::Id) — the sealed key-field
/// vocabulary, entered through its third admission law. It is deliberately not spelled
/// `#[ingraph(id)]`: that word is the RECORD's, naming which FIELD of a declaration is its address.
///
/// # What it writes
///
/// | face | mechanism |
/// |---|---|
/// | `DelegatesId` | the transparency assertion, upheld BY CONSTRUCTION rather than asserted |
/// | `Debug`, `Clone`, `PartialEq`, `Eq`, `Hash` | delegated to the held value |
/// | `Display`, `FromStr` | delegated — the canonical spelling is the inner type's own |
/// | `From<Inner>`, `From<Self> for Inner`, `From<Self> for String` | the conversions, and the crossing a TEXT-column comparison asks for |
/// | `CursorValue` | delegated — a keyset position |
/// | `ColumnKind`, `Carrier<Db>`, `Assemble` | one column, bound and decoded as canonical TEXT |
/// | `ToGraphqlInput`, `ToGraphqlOutput` | the identity crossing and the borrow |
/// | `ScalarWire`, `CompositeFilterMarker`, `DefaultMarker` | the filter reading, over a minted `<Name>Wire` |
/// | `async_graphql::ScalarType` | the scalar itself, under this type's own name |
/// | `new`, `into_inner`, `as_inner` | the constructor and the two readings |
/// | `from_ref`, `from_slice`, `as_inner_slice` | the free views, `#[repr(transparent)]`'s own dividend |
///
/// The roster is a MEASUREMENT and not a wish list: it is what `findit`'s `MediaId` and
/// `mediagraph`'s `VolumeId` each hand-wrote, independently, impl for impl.
///
/// # THE ONE OBLIGATION ON THE WRAPPED TYPE: a canonical text form
///
/// It must implement [`Display`](core::fmt::Display) and [`FromStr`](core::str::FromStr), the
/// latter with a refusal that is an [`Error`](core::error::Error). Every row from `Display` down
/// spends one or the other — the bind renders, the decode reads back, the scalar does both — and the
/// storage pair crosses through `String` rather than through the wrapped type's own column faces,
/// which is the road both live registers took and for the reason they took it: `ingraph` ships no
/// value-column row for a bare `uuid::Uuid` to delegate to.
///
/// So `[u8; N]` — a measured member of the vocabulary with neither face — is refused, at the
/// declaration, naming what is missing. A digest is a perfectly good key and not a text-shaped
/// value; its road is `unsafe impl ingraph::DelegatesId`, which asks for no text at all.
///
/// # `Ord` is NOT written, and `Copy` is the declaration's own
///
/// No id duty reads an order — the stored order is the backend's reading of the value and the path
/// segment is the framework's own rendering — so a device that minted one would be inventing an
/// order for a type whose author may have refused it. `#[derive(PartialOrd, Ord)]` beside this word
/// is how a declaration that wants one says so, and `#[derive(Copy)]` resolves against the `Clone`
/// this device writes.
///
/// # THE DOOR HAS NO INVARIANT, and that is a requirement rather than an observation
///
/// `from_ref` views any `&Inner` as a `&Self`. A wrapper whose values are a CHECKED SUBSET of its
/// inner's therefore does not belong here — take `#[derive(ingraph::NewType)]` with
/// `scalar(check = "…")` or `scalar(parse = "…")`, where every read path is spent on the door.
///
/// # Refusals
///
/// A declaration that is not a struct; one whose field is NAMED, or that holds any number of values
/// but one; one carrying no `#[repr(transparent)]`; one that is GENERIC. Each is refused by name,
/// with what to write instead — as is every word `#[derive(ingraph::NewType)]` carries that this
/// door does not, pointed at the door that has it.
#[proc_macro_derive(Id, attributes(ingraph))]
pub fn id(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
  let input = syn::parse_macro_input!(item as syn::DeriveInput);
  // NO host is emitted, for the reason `Enum` states: a derive is handed a COPY of the declaration
  // and the compiler keeps the original, so a refusal here rides beside the type without having to
  // re-emit it.
  id::parse(&input)
    .as_ref()
    .map_or_else(
      |refused| refused.to_compile_error(),
      ingraph_codegen::id::IdModel::emit,
    )
    .into()
}

/// Declare an INTERFACE — a member set with a contract over it.
///
/// An interface is a union plus a promise. The union half is the same payload-carrying enum
/// [`Union`] equips: one variant per member, each carrying that member and nothing else. The
/// promise is `fields(…)` — every member has these fields, at these types.
///
/// ```ignore
/// #[ingraph::interface(
///   persist(sqlite, postgres),
///   graphql(computed(error = "media::ComputeError")),
///   fields(
///     title: String,
///     mask(type = "Mask", copy, persist(sqlite(type = "u32"), postgres(type = "int4"))),
///     created_at(type = "Timestamp", members(Audio(field = "imported_at"))),
///     display_label(type = "String", graphql(computed)),
///     checksum(type = "u64", graphql(try_computed)),
///   ),
/// )]
/// pub enum Media {
///   Video(Video),
///   Audio(Audio),
/// }
/// ```
///
/// # A field is in ONE of three tiers, and the tier decides whose face carries it
///
/// | tier | written | every member | the face |
/// |---|---|---|---|
/// | stored | nothing, or `persist(<db>(type = "…"))` | carries the column | `<I>Fields`, on the member |
/// | computed | `graphql(computed)` | DERIVES the value | `<I>Derivations`, on its wire output |
/// | try_computed | `graphql(try_computed)` | derives it, fallibly | the same, returning a `Result` |
///
/// The domain contract is STORED-ONLY. A computed field is a query-layer construct — it is derived
/// to be answered, and what answers a query is the wire output — so putting one on the domain trait
/// would make every member's domain type owe a method its rows have no column for. `<I>Derivations`
/// is DECLARED and implemented nowhere: a member's output type writes the impl by hand, and there
/// is no adapter under it, because a hand author writes their own glue.
///
/// Stored and computed are mutually exclusive in both directions, and each direction has its own
/// refusal.
///
/// # Attributes
///
/// On the enum:
///
/// - `crate = "path::to::ingraph"` — where `ingraph` lives, exactly as [`record`]'s. Present here
///   where a union has none, because an interface's expansion DOES name framework paths: the
///   membership evidence, the storability its equations read a row through, and the backend gates
///   they ride.
/// - `unwrap_error(rename = "Name")` — what the emitted REFUSAL type is called. Defaults to
///   `<Interface>UnwrapError`, which is the union's convention reached through the union's own
///   function. `error` names the CONVERSION CELLS instead, and the old spelling is a named
///   migration refusal — one word per thing typed.
/// - `persist(sqlite, postgres, …)` — which databases the contract's pins are checked at. A
///   SELECTION rather than a storage declaration: an interface owns no table. A database block may
///   carry `alias(prefix = "__mine")`, which moves the words a union statement INVENTS in that
///   database — the discriminant every arm projects and the derived table the outer query names.
///   `depth` is refused here: it is the length of an alias table, and an interface has none.
/// - `graphql(computed(error = "path::To"))` — the type every fallible computed field answers with.
///   ONE cell and DB-LESS, which is this grammar's one ruled exception to database blocks: a
///   computed value is derived from the member rather than read out of a row, so the crossing names
///   no database.
/// - `fields(…)` — the contract. An interface with none is a union, and is refused by that reason.
///
/// A field is `<name>: <Type>` or `<name>(type = "<Type>", …)`, and the long form takes `copy`,
/// `persist(<db>(type = "…"))`, `graphql(…)` and a MEMBER block. The long form's type is written in
/// a STRING, as every other `type` in this grammar is; the short form's is the Rust type itself,
/// because there it is what the `:` already introduces.
///
/// # A member may call a stored field something else
///
/// `created_at(type = "Timestamp", members(Audio(field = "imported_at")))` — the member `Audio` carries this
/// field as `imported_at`, in its own struct and in its own row.
///
/// Declared on the INTERFACE rather than on the member, and the reason is what a macro can see: a
/// member-side word would have to reach the interface's expansion across a derive boundary, and the
/// only things that cross one are a type and a const — neither of which produces the IDENT a field
/// access needs. Written here, every hop is backed by the same derive input, starting with the
/// block's key, which is checked token-for-token against the enum's own variants in VERBATIM case.
///
/// What a block moves is the ACCESS and not the METHOD: a caller writes the interface's name
/// whatever member it is holding. `field = "…"` is the only entry it takes; one `members(…)` per
/// field, never empty; and `members(…)` on a computed field is refused — a derived value is read
/// out of no column at all.
///
/// # The axis law
///
/// A DOMAIN block, then a DATABASE block, then that cell's entries — at every level. So a database
/// name written where a domain belongs is refused BY NAME rather than as an unknown entry, wherever
/// it appears.
///
/// A field's `members(…)` extends it one step — interface field block ▸ `members(…)` ▸ one block
/// per variant ▸ entries — and the step is this grammar's alone: a record grows no member axis,
/// having no members.
///
/// POSITION decides what a key is. Outside `members(…)` every key is a word this grammar owns;
/// inside it every key is a VARIANT, matched token-for-token against the enum's own. A variant
/// written outside the container is refused BY NAME rather than as an unknown word, and one whose
/// spelling collides with a grammar word — or one in lower case — is reachable inside it, where a
/// rule reading the first letter had a corner it could not address.
///
/// # What it emits
///
/// The union face — `is_<member>`, the `unwrap_<member>` family in all three receivers, and the
/// sealed refusal — through the same seam `Union` reaches, so an interface's members are asked for
/// exactly as a union's are.
///
/// # Refusals
///
/// The SHAPE refusals are the union's family, stated in this declaration's own terms: a non-enum,
/// an enum with no variants, a variant carrying no member, one carrying several, one carrying its
/// member in a named field, any generic parameter, two variants carrying one type, and two variants
/// whose words derive one method.
///
/// Its own are the contract's: a field declared twice, a field with no type, an entry neither form
/// admits, a database name at a domain position, an interface with no `fields(…)` at all, and the
/// tier collision in both of its directions. `members(…)` adds five more — a key naming no variant
/// (refused by listing the ones there are), one member named twice in one container, a container on
/// a computed field, a second container on one field, and one naming nobody. A member block written
/// OUTSIDE the container is refused by name, which is a migration rather than an unknown word.
///
/// A field's `graphql(output(<db>(…)))` is ADMITTED AND REFUSED rather than unknown: it is a real
/// entry of the settled design whose consumer is the interface's own output face, whose stored half
/// waits on an accessor a member's wire object does not publish yet, so the refusal names the shape
/// and says what it arrives with. The four operand and hydration cells beside it are READ — see
/// [`interface`]'s own note for which level each sits at and why.
#[proc_macro_attribute]
pub fn interface(
  args: proc_macro::TokenStream,
  item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
  equip(args, item, |input, arguments| {
    interface::parse(input, arguments).as_ref().map_or_else(
      syn::Error::to_compile_error,
      ingraph_codegen::interface::InterfaceModel::emit,
    )
  })
}

/// Declare a GRAPH ROOT — the struct whose fields are an application's nodes.
///
/// ```ignore
/// #[ingraph::graph]
/// pub struct Media {
///   videos: Video,
///   scenes: Scene,
///   search: TranscriptText,
/// }
/// ```
///
/// The list is the whole declaration. There is no registry a node enrols itself in and nothing on a
/// node's own binding points back at a graph: an application writes its nodes once, in the order
/// it wants them walked, and this derive turns that order into a walk.
///
/// # Attributes
///
/// On the struct, one entry and no other:
///
/// - `crate = "path::to::ingraph"` — where `ingraph` lives, for a re-export shim or a renamed
///   dependency. Defaults to `::ingraph`, exactly as [`record`]'s does.
///
/// A FIELD takes the words that are the ROOT's to author, and no others: `resource` in its three
/// spellings, a `teardown` composed with any of them, `interface`, `fuse`, and `query` — the ROOT
/// QUERY's membership. The example above writes none of them, which is the bare shape rather than
/// the whole grammar. What a node IS, how it is stored, and whether it says goodbye stay in that
/// node's own declaration, because a word here for any of those would be a second author for one
/// fact. Every word a field does take is about the LIST instead: which TIER the field sits on, and
/// whether THIS deployment publishes its root fields — facts no member's own declaration can hold,
/// since a member cannot see the root that mounts it.
///
/// # What it emits
///
/// | item | condition |
/// |---|---|
/// | `type_iter<V: TypeVisitor>(visitor)` — one `next_type::<T>()` per field | always |
/// | `<Root>Options` — one section per field, and the doors to state one | always |
/// | its `Deserialize` impl | serde is compiled in |
/// | `init<Db>(conn)` — create every table this graph declares | the SQL family is compiled in |
/// | `validate<Db>(conn)` — audit a live schema against it | the same |
///
/// The three entries are INHERENT and take the root's own visibility, and so does the spine.
/// `type_iter` could not be a trait method: its body discharges one storage-description predicate
/// per field, and an impl may not add a where clause to a trait method (`E0276`).
///
/// # The OPTIONS SPINE, and what its `Option` means
///
/// `<Root>Options` holds `Option<NodeSection<<T as AsyncConstructor>::Options>>` per field, named by the
/// mount. PRESENCE IS ENABLEMENT: a node with no section is a node that never launches, so an
/// application may declare a catalog and a deployment may take a subset of it without either
/// writing anything about the other. Presence is the ONLY enablement axis: a section that is
/// written is a node that runs, and a deployment turns one off by pointing at a different document
/// rather than by toggling this one.
///
/// Every field is `serde(default)` and the type is `deny_unknown_fields`, so a document naming three
/// of thirty nodes parses and a misspelled mount is a refusal naming it. The framework reads NO
/// file: which format states a deployment, how many layers merge into it and where they live are the
/// application's questions.
///
/// Each field names its node's OWN options through the construction contract, so a declared node
/// states how it is BUILT as well as how it is stored — a field whose type implements no
/// `AsyncConstructor` is `E0277` where the graph is written, carrying that trait's own sentence. A node
/// with nothing to configure writes `type Options = ();`.
///
/// HANDLES ARE PARAMETERS. `init` and `validate` take the connection they run on, so a graph
/// describes what exists and never holds what it is stored in.
///
/// The two entries ride the SQL family's gate, because their signatures name it; the walk names no
/// database and is emitted unconditionally, which is what keeps it the single walk authority in a
/// build with no driver at all.
///
/// # The audit a bound makes, and the one nobody can
///
/// Each field carries a `Describe<V::Db>` predicate at the walk, so a field whose type is not a node
/// this database knows how to create is `E0277` where the graph is written — carrying that
/// trait's own sentence, and naming the type and the database.
///
/// What a field's type SUBSCRIBES to is not checkable here at all. A member's subscriptions are
/// written in the member's own declaration, which this derive cannot see, so
/// subscribe-completeness is an assembly-time check and is named as one rather than half-attempted.
///
/// # Refusals
///
/// The declaration's SHAPE is the graph, so each part of it is checked here rather than left to
/// fail inside the expansion: an enum, a positional or unit struct, a struct with no field, and any
/// generic parameter. The rest are about the LIST — one type listed twice, two fields naming one
/// resource, a member mounted at the RESERVED `resources` or `registry` key, and an entry inside a
/// field's `#[ingraph(…)]` that is not one of the words above, which is refused BY NAME against that
/// roster.
#[proc_macro_attribute]
pub fn graph(
  args: proc_macro::TokenStream,
  item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
  equip(args, item, |input, arguments| {
    graph::parse(input, arguments).as_ref().map_or_else(
      syn::Error::to_compile_error,
      ingraph_codegen::graph::GraphModel::emit,
    )
  })
}

/// Give a HAND-WRITTEN struct the FILTER face a record's declaration gets — a predicate over its
/// fields, each field its type's filter.
///
/// # The bare door of a unit `#[ingraph::record(…)]` already composes
///
/// There is ONE emitter. `record` composes this walk and adds what a grammar word adds — the
/// storage lowerings, the wire faces, the row equations; this door composes the same walk and adds
/// nothing. So a record field's filter and a standalone type's filter cannot drift, and the identity
/// is pinned as TOKENS rather than argued.
///
/// # The vocabulary is the record's, wherever it reaches this face
///
/// The field grammar is read by the RECORD's own reader, so there is no reduced dialect: the
/// interpretation words (`scalar`, `string`, `bytes`, `enum`, `bool`, `duration`, `list(…)`,
/// `set(…)`, `label = "…"`), `rename = "…"` and the whole `graphql(…)` family are taken
/// here exactly as they are taken there. What a bare struct has no use for — `id`, `key(…)`,
/// `lineage(…)`, `copy`, `repeated`, `optional`, `ref = "…"`, and the per-database layout words —
/// refuses BY NAME at the token that wrote it, because a door that took a word it does not spend
/// would leave an author reading a declaration the expansion does not obey.
///
/// # The container's own words
///
/// `crate = "…"`, `filter(rename = "…")`, and — shared with the other two doors —
/// `comparison(rename = "…")`, `order_by(rename = "…")`, its DATABASES bare, and the conversion
/// hook `filter = "…"`. One `#[ingraph(…)]` serves every derive on the declaration, which is what
/// lets all three sit on one struct.
///
/// # THE ELEMENT MODE — `#[ingraph(operator(<family>))]`
///
/// The same derive, a second lawful identity, and the MARKER is the watershed: written, this
/// declaration is one VALUE rather than a row of columns, and what it earns is a filter of its own
/// plus the wire citizenship an operand needs.
///
/// ```ignore
/// #[derive(Debug, Clone, PartialEq, ingraph::Filter)]
/// #[ingraph(operator(string))]
/// pub struct Tag(String);
/// ```
///
/// | item | what it is |
/// |---|---|
/// | `TagFilter` | the minted filter — the family's operation set, over `Tag`, owned by THIS crate |
/// | `StringFilterMarker` / `DefaultMarker` | the two rows a FIELD of `Tag` resolves through |
/// | `GraphqlFilter`, `ToDatabaseComparison` | the emptiness answer and the lowering map, delegated |
/// | `ScalarType`, `ToGraphqlInput`, `ToGraphqlOutput` | the element's own wire face and its two crossings, behind the BINDING gate |
///
/// **Why a minted type rather than the framework's own.** `impl async_graphql::InputType for
/// TextFilter<Tag>` is `E0117` in a declaring crate — RFC 2451 does not admit `ForeignTrait for
/// ForeignType<Local>` — and `ingraph` cannot write it either, its scalar and byte faces being one
/// REGISTRATION PER OPERAND over a set a declarer's types are not in. `TagFilter` is local, so every
/// impl above names a local self type and the orphan wall never appears.
///
/// **The FAMILIES.** `scalar`, `string`, `bytes` and `enum` — the four value readings whose filter
/// kind carries an OPERAND PARAMETER for a declared element to sit in. `bool` and `duration` carry
/// none, and `list`/`set` are collection POSITIONS rather than elements; each refuses BY NAME at the
/// word. A BARE `operator` is the `scalar` family. ONE SHAPE at all four: the table above is what
/// every family emits, and the family decides what is IN each item and never which items there are.
///
/// **`filter(rename = "…")` moves BOTH of the minted type's names** — the Rust one and the input
/// object's — at every family alike. `enum` used to move only the Rust one, its door having been a
/// type ALIAS with no wire face of its own; the alias has retired and the word means one thing.
///
/// **The wire form is the INNER type's, under the ELEMENT's name.** `Tag(String)` crosses as a
/// string in a scalar named `Tag`; an inner type with no wire face of its own is `E0277` naming that
/// type. `graphql(rename = "…")` moves that scalar's name and nothing else — a wire type name is a
/// schema commitment, which is why it gets a word of its own rather than riding on a Rust rename. The
/// other two modes mint no scalar and refuse the word by name.
///
/// **Refusals.** A declaration that is not ONE field (a unit struct, two fields, an enum); a family
/// word outside the four; `operator(…)` on `#[derive(ingraph::Comparison)]` or
/// `#[derive(ingraph::OrderBy)]`, whose faces are over a row's columns and an element has none; the
/// container words an element does not spend (the store words, `comparison(rename)`,
/// `order_by(rename)`, the conversion hook); `graphql(rename = "…")` in either mode that mints no
/// scalar; and an `#[ingraph(…)]` on the element's own field.
#[proc_macro_derive(Filter, attributes(ingraph))]
pub fn filter(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
  standalone(item, standalone::Face::Filter)
}

/// Give a HAND-WRITTEN struct the COMPARISON face — one predicate type per database it names, each
/// field the comparison its column's filter crosses into.
///
/// See [`macro@Filter`] for the family's law, its vocabulary and its refusals. What this door adds
/// is the DATABASE set: `#[ingraph(sqlite, postgres)]` mints one comparison per database,
/// named as a record's is, and a declaration naming none gets ONE comparison generic in its dialect.
///
/// # The conversion hook
///
/// `#[ingraph(filter = "path::to::Filter")]` names the filter seat this comparison is crossed into
/// FROM, and the door emits the map row that says so — `ToDatabaseComparison<Self, Db>`, exactly
/// what a record emits for its own emitted filter. Without it, a FIELD-level conversion word refuses
/// by name: a conversion refines a crossing, a crossing starts from a seat, and a refinement of
/// nothing is not a thing to write.
#[proc_macro_derive(Comparison, attributes(ingraph))]
pub fn comparison(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
  standalone(item, standalone::Face::Comparison)
}

/// Give a HAND-WRITTEN struct the ORDER-BY face — one term per field, each carrying the direction it
/// runs in, plus the two questions every term answers.
///
/// See [`macro@Filter`] for the family's law, its vocabulary and its refusals.
///
/// All four halves of the face, where a record gates two: a record's `identity` rides the PAGE's own
/// law — a stored id and a SQL clause machine — and neither is a fact a hand-written struct has.
/// What is ordered here is the struct's own fields, and every term of it names one.
#[proc_macro_derive(OrderBy, attributes(ingraph))]
pub fn order_by(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
  standalone(item, standalone::Face::OrderBy)
}

/// The three doors' shared body — read once, emit the face that was asked for.
///
/// NO host is emitted, which is the derive family's own rule: a derive is handed a COPY of the
/// declaration and the compiler keeps the original, so a refusal rides beside the type without
/// having to re-emit it — and the `#[ingraph(…)]` markers stay on the item, inert, where an
/// attribute macro's echo would have had to strip them. It is also what lets THREE derives read one
/// marker set without an ordering rule between them.
fn standalone(item: proc_macro::TokenStream, face: standalone::Face) -> proc_macro::TokenStream {
  let input = syn::parse_macro_input!(item as syn::DeriveInput);
  standalone::parse(&input, face)
    .map_or_else(
      |refused| refused.to_compile_error(),
      |model| standalone::emit(&model, face),
    )
    .into()
}