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
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
//! A DERIVED INDEX's acceptance: the one upstream it names, what it takes from it, and every family
//! it does not claim.
//!
//! ```text
//! #[ingraph::fulltext(
//!   crate = "path::to::ingraph",
//!   upstream(node = "asr::Segment", title = "speaker", body = "text"),
//! )]
//! pub struct SearchDocument {
//!   #[ingraph(searchable)] title: String,
//!   #[ingraph(searchable)] body: String,
//! }
//! ```
//!
//! One shape, three storages. `fulltext`, `vector` and `blob` differ in which engine holds the
//! documents and in nothing this grammar reads, so they share a pass and carry a
//! [`NodeKind`] for the sentences that name one.
//!
//! # `upstream(…)` is the edge AND the projection, which is why it is not `subscribe`
//!
//! A derived index holds ONE DOCUMENT PER UPSTREAM MESSAGE, and every field of that document is read
//! out of the message. So naming the upstream is not enough — each field has to say WHICH of the
//! upstream's fields it comes from — and `upstream(…)` carries both: `node = "…"` is the edge, and
//! every other entry is `<this index's field> = "<the upstream's field>"`.
//!
//! `subscribe = "…"` is the other spelling and it is refused here by name. It names an edge and
//! projects nothing, which is what a node that computes its own fields needs and is exactly what a
//! derived index does not.
//!
//! # The ELECTION is a field marker, and the head word that used to carry it has retired
//!
//! Which of a declaration's fields the index is actually OVER is a role, and a role is worn by the
//! thing that has it: `#[ingraph(knn)]` on a vector declaration's field, `#[ingraph(searchable)]` on
//! a full-text declaration's. Presence is the election; absence is stored-not-indexed payload —
//! hydrated with the rest of the document and reached by no query. A declaration that marks NO field
//! is refused by name, because an index that indexes nothing is a declaration with no subject.
//!
//! `embedding(<field>)` was the head word this used to be spelled with, and it is refused by name
//! with the marker in the sentence. What the move buys is spans: the head named a field from outside
//! it, so *is not an `Embedding<E, N>`* landed on the head's own ident and the field's TYPE — the
//! thing that was actually wrong — was somewhere else in the file. The marker's refusals land on the
//! field's own tokens.
//!
//! # The ENGINES are on the field too, BARE, beside the marker
//!
//! `#[ingraph(knn, lance, hnsw(ef = 200), fanout)]` — election, engines and liveness, one story in
//! one place. The words are bare and carry their own options because on an index field the ENGINE IS
//! THE STORE: there is no second axis for a `persist(…)` wrapper to namespace against, so the
//! record's shape is not repeated and `persist` on a field here is refused by name.
//!
//! Several engines are declared PORTABILITY and the default is SINGLE-WRITE — the record's own
//! semantics, measured and mirrored rather than reinvented — and `fanout` is the one departure: with
//! it every declared engine is live at once. A slot is `(field × engine)`, which is what makes two
//! fields of one declaration independent corpora. See [`ingraph_codegen::engine`].
//!
//! # Nothing here resolves the upstream, and that is the mechanism rather than a limitation
//!
//! Two macro expansions cannot see each other, so what `asr::Segment` even IS is unknowable at this
//! point. Every claim the declaration makes about it is therefore emitted for rustc to check, at the
//! span of the string the author wrote — see [`ingraph_codegen::index`] for the table of which error
//! each mistake becomes. A grammar that tried to check them here would be a macro re-implementing
//! name resolution, and every mistake would land somewhere the author cannot see.

use ingraph_codegen::{
  engine::{DeclaredLane, Engine, EngineKind, FieldEngines, Road},
  extension::{self, ColumnExtension, Extension, ExtensionSource},
  index::{
    self, Dedup, Elected, ElectionBackend, ElectionLabel, Field, FieldNumbers, Fold, IndexBackend,
    IndexGraphql, IndexModel, IndexRename, Labelled, Numbers, Projected, RenamePiece, Upstream,
  },
  model::{Conversion, GraphqlKind, borrowed_key},
  prefix::EmissionPrefix,
  prelude::*,
};
use quote::ToTokens as _;

use crate::{
  alias,
  attribute::{self, named, set_once},
  column,
  errors::Errors,
  parse::owns_one_storage,
  value,
};

#[cfg(test)]
mod artifacts;
#[cfg(test)]
mod artifacts_rider;
#[cfg(test)]
mod asked;
#[cfg(test)]
mod engine_types;
#[cfg(test)]
mod engines;
#[cfg(test)]
mod lanes;
#[cfg(test)]
mod leaderboard;
#[cfg(test)]
mod rename_seats;
#[cfg(test)]
mod renames;
#[cfg(test)]
mod roads;
#[cfg(test)]
mod searchable_road;
#[cfg(test)]
mod seats;
#[cfg(test)]
mod skin_prefix;
#[cfg(test)]
mod skins;
#[cfg(test)]
mod subscribe_word;
#[cfg(test)]
mod tests;

/// Validate a decorated declaration into the model the emitter consumes.
///
/// # Errors
/// A [`syn::Error`] carrying EVERY rule the pass could still see violated, each spanned at the
/// token that violated it, so one compile reports the whole declaration's problems.
pub(crate) fn parse(
  input: &syn::DeriveInput,
  arguments: &[syn::Attribute],
  kind: NodeKind,
) -> syn::Result<IndexModel> {
  let index = &input.ident;
  let mut errors = Errors::default();
  crate::host::refuse_a_moved_option_block(&input.attrs, &mut errors);
  let Head {
    krate,
    block,
    dedup,
    stores,
    extension,
    data,
    graphql,
    rename,
    slot,
    numbers,
    keys,
    subscribe,
  } = options(arguments, kind, &mut errors);
  concrete(&input.generics, kind, &mut errors);

  let fields = match named_fields(input, kind) {
    Ok(fields) => fields,
    Err(terminal) => return Err(errors.seal(terminal)),
  };
  if fields.named.is_empty() {
    errors.push(syn::Error::new_spanned(
      index,
      format!(
        "{article} {noun} with no fields indexes nothing — it holds one document per upstream \
         message, and a document with no field is that message's key repeated, which the upstream \
         already answers",
        article = kind.article(),
        noun = kind.noun(),
      ),
    ));
  }

  // A LOOP rather than the `filter_map` it replaces: each field now yields TWO answers — the column
  // the model carries and the ROLE its marker declared — and the pair is what the election is read
  // off below. Kept in step by construction, one push per field.
  let mut columns: Vec<Column> = Vec::new();
  let mut roles: Vec<Role> = Vec::new();
  for field in &fields.named {
    let Some(name) = field.ident.clone() else {
      continue;
    };
    // THE ONE-STORAGE LAW, caught by the derive rather than by the linker's namespace.
    //
    // Two storage macros on one declaration are ordinarily undetectable — two expansions cannot
    // see each other — and are refused by the marker each mints colliding in the declaring scope.
    // Between two DERIVED indexes the collision arrives earlier: the first macro rewrote the item,
    // so the second is handed a declaration that already carries the injected key. That is a fact
    // about this declaration and this pass can read it, so it says the law rather than reporting
    // the field as a reserved name the author never wrote.
    if name == borrowed_key(&EmissionPrefix::default()) {
      errors.push(syn::Error::new_spanned(
        &name,
        format!(
          "this declaration already carries a storage macro's injected key, so a second storage \
           macro is being asked to index a document that has one. {}",
          owns_one_storage(kind),
        ),
      ));
      continue;
    }
    // A derived index declares no database blocks, so the fence it is held to is the
    // framework's own namespace and nothing else — `Fence::default`'s stated case.
    column::refuse_framework_namespace(&alias::Fence::default(), &name, &mut errors);
    // `node` is `upstream(…)`'s own entry, so a field of that name has no entry left to be
    // projected by. Refused HERE rather than left to the unprojected-field rule below, which
    // would report the consequence and send the author to write the one entry that cannot exist.
    if name == "node" {
      errors.push(syn::Error::new_spanned(
        &name,
        format!(
          "`node` cannot be {article} {noun}'s field — inside `upstream(…)` it names the UPSTREAM, \
           so `node = \"…\"` there is already spoken for and this field has no entry left to be \
           read out of. Rename the field",
          article = kind.article(),
          noun = kind.noun(),
        ),
      ));
    }
    let (project, mut role) = markers(&field.attrs, &name, kind, &mut errors);
    // The two judgements the walk could not make while it was walking — see `engines_of`.
    engines_of(&name, &mut role, kind, &mut errors);
    columns.push(Column {
      project,
      ty: field.ty.clone(),
      source: name.clone(),
      name,
    });
    roles.push(role);
  }

  // The two bails are both about the UPSTREAM, and neither is checkable past its own absence: with
  // no upstream there is no key to be addressed by, and therefore no model to carry the projections
  // that were checked on the way here.
  let Some(block) = block else {
    return Err(errors.seal(syn::Error::new_spanned(
      index,
      format!(
        "{article} {noun} draws its documents from an upstream, and `upstream(…)` is where it names \
         one — `upstream(node = \"path::To::Upstream\", <field> = \"<upstream field>\", …)`. It is \
         not optional: a derived index mints no id of its own, so without an upstream it has no key \
         to be addressed by either",
        article = kind.article(),
        noun = kind.noun(),
      ),
    )));
  };
  let projections = projections(&block, &columns, kind, index, &mut errors);
  let Some(node) = block.node else {
    return Err(errors.seal(syn::Error::new_spanned(
      &block.at,
      "`upstream(…)` needs `node = \"path::To::Upstream\"` — the projections beside it say which of \
       the upstream's fields this declaration reads, and without the upstream there is nothing for \
       them to be read out of",
    )));
  };

  let Elections {
    embeddings,
    labelled,
    searchable,
    engines,
    numbers: field_numbers,
  } = elect(&columns, &roles, kind, index, &mut errors);
  let model = IndexModel {
    prefix: EmissionPrefix::default(),
    index: index.clone(),
    kind,
    vis: input.vis.clone(),
    krate,
    source: Upstream { node, projections },
    embeddings,
    labelled,
    searchable,
    engines,
    stores,
    extension,
    data,
    graphql,
    numbers,
    field_numbers,
    rename,
    slot,
    keys,
    subscribe,
    dedup: dedup.unwrap_or_else(|| {
      // MANDATORY on every retrieving kind, and the model still needs a value to carry past the
      // refusal: the errors are sealed before this model reaches an emission, so what stands here is
      // never spent — it is what keeps ONE refusal from becoming a cascade of unrelated ones.
      if matches!(kind, NodeKind::Fulltext | NodeKind::Vector) {
        errors.push(syn::Error::new_spanned(index, DEDUP_IS_MANDATORY));
      }
      Dedup::Hash
    }),
    fields: columns,
  };
  emitted_methods(&model, &mut errors);
  emitted_types(&model, &mut errors);
  named_mints(&model, &mut errors);
  written_seats(&model, &mut errors);
  spent_guards(&model, &mut errors);
  errors.into_result(model)
}

/// **THE HEAD'S `streams` GUARD, CHECKED AGAINST WHAT IT GUARDS** — [`written_seats`]' law one axis
/// over, at the one BONES number whose subject a declaration may not have.
///
/// The word guards the `_with` road, which is emitted for `list(embedding)` elections alone, so a
/// container that wrote it and elected no set has stated a rule nothing reads. That is the swallowed
/// authoring error the seat law refuses by name, and the ELECTION tier already refuses its own half
/// where the label is in hand ([`streams_is_a_sets_word`]).
///
/// Read AFTER the model is built for that function's reason: *is any election a set* is a fact about
/// the fields, which the head's own walk has not seen yet.
///
/// `limit`, `depth` and `ceiling` need no such audit, being about every door this declaration has.
/// The span is the DECLARATION's ident, which is `DEDUP_IS_MANDATORY`'s own choice at the same
/// grain: the head carries no token for one number, so what a caret can honestly sit on is the thing
/// the sentence is about.
fn spent_guards(model: &IndexModel, errors: &mut Errors) {
  if model.numbers.streams.is_none()
    || model
      .embeddings
      .iter()
      .any(|elected| elected.label.is_set())
  {
    return;
  }
  let index = &model.index;
  errors.push(syn::Error::new_spanned(
    index,
    format!(
      "`{index}` writes `{STREAMS} = N` at its head and elects no `list(embedding)` field — the \
       guard bounds how many query vectors one request may ask a SET election's `_with` road with, \
       and this declaration has no such road for it to stand on. Label the election that carries \
       several embeddings `list(embedding)`, or take the word off. What bounds every road a \
       declaration does have is `{CEILING} = N`, which caps the DEPTH a request may ask for"
    ),
  ));
}

/// **EVERY SEAT AN ELECTION WROTE, CHECKED AGAINST WHAT IT ACTUALLY MOUNTS** — the mints-none audit,
/// at the seats the 2026-08-16 rename round minted.
///
/// # Seats may sit EMPTY; written words must point at something MINTED
///
/// That is the law and it is a distinction rather than a strictness. An unwritten seat is a
/// capability awaiting a user and costs a declaration nothing — the whole grammar is unwritten on
/// most declarations. A WRITTEN word that reaches no emitted name is a swallowed authoring error:
/// its author believes they renamed a query field, and the schema publishes the derived name or
/// publishes nothing at all. The house already refuses that class by name — `lineage(rename)` on a
/// lineage-less record, and the near-miss family beside it — and these seats join it.
///
/// # Read after the model is built, for [`named_mints`]' own reason
///
/// *Which roads does this election mount* is a fact about its label, its engines and the head's
/// `keys` word together, so it is asked of the settled model rather than of the tokens. The
/// predicates themselves are `ingraph-codegen`'s, beside the emitter whose conditions they mirror —
/// see [`IndexModel::unmounted`](ingraph_codegen::index::IndexModel::unmounted), where the scope and
/// the three cases it deliberately leaves open are written down.
///
/// The span is the WORD's own literal, so a caret lands on what an author has to delete.
fn written_seats(model: &IndexModel, errors: &mut Errors) {
  for written in &model.field_numbers {
    let Some(skin) = written.skin(GraphqlKind::AsyncGraphql) else {
      continue;
    };
    for road in Field::ALL {
      let (Some(word), Some(why)) = (skin.road(road), model.unmounted(&written.field, road)) else {
        continue;
      };
      errors.push(syn::Error::new_spanned(
        word,
        format!(
          "`{road}` names {what} for `{field}`, and this election publishes none: {why}",
          road = road.as_str(),
          what = road.what(),
          field = written.field,
        ),
      ));
    }
    if let (Some(word), Some(why)) = (
      skin.engines.as_ref(),
      model.unminted_engines(&written.field),
    ) {
      errors.push(syn::Error::new_spanned(
        word,
        format!(
          "`{ENGINES}` names the per-leg product `{field}` would state one floor in, and this \
           election mints none: {why}",
          field = written.field,
        ),
      ));
    }
  }
}

/// EVERYTHING THE HEAD SAID, in one value.
///
/// A struct rather than the tuple it replaces, and the round that grew the `graphql(…)` block is
/// what settled it: seven positional halves — three of them `Option`s of unrelated shapes — is a
/// signature whose caller binds by counting commas. The names are the documentation, and a word
/// added later takes a field rather than a position.
struct Head {
  /// `crate = "…"`, defaulted to `::ingraph`.
  krate: syn::Path,
  /// `upstream(…)`, or [`None`] where the declaration named no upstream — a refusal, sealed by the
  /// caller.
  block: Option<UpstreamBlock>,
  /// `dedup(…)`, mandatory on the retrieving kinds and refused on `blob`.
  dedup: Option<Dedup>,
  /// A blob's HEAD engines, empty on the other two kinds.
  stores: Vec<Engine>,
  /// `extension(…)` in whichever of its six forms, blob only.
  extension: Option<Extension>,
  /// The bare `data` PERMISSION, blob only.
  data: bool,
  /// `graphql(…)` — which backends dress this declaration, or [`None`] where it named none.
  graphql: Option<IndexGraphql>,
  /// `rename = "…"` or `rename(<piece> = "…", …)` — what this declaration's minted RUST types are
  /// called.
  rename: Option<IndexRename>,
  /// `slot = "…"` — what this family's corpus is called where it is stored, blob only.
  slot: Option<syn::LitStr>,
  /// `limit = N`, `depth = N`, `ceiling = N` — the CONTAINER tier's numbers, refused on `blob`.
  numbers: Numbers,
  /// The bare `keys` word — this declaration's upstream is an ENTITY, so its answer family mounts
  /// the keys tier alone. Refused on `blob`, which answers an address and has no tier pair.
  keys: bool,
  /// The bare `subscribe` word — this declaration LAUNCHES, filling its own corpora from the edge
  /// `upstream(…)` already named. Full-text only; see [`subscribe_wrong_kind`].
  subscribe: bool,
}

/// The macro's own arguments: `crate = "…"`, `upstream(…)`, `dedup(…)`, `graphql(…)`, and one named
/// refusal per family a derived index does not claim — the retired election head word among them.
/// What a STORE WORD is told at a derived index's head — one sentence over five entries, because
/// the mistake is one mistake and only the word that spelled it differs.
///
/// The unwrap is what made the mistake reachable. A record's stores lived inside `persist(…)` and an
/// author transplanting the block onto an index met the row above; they are BARE now, so the word
/// that actually arrives here is `sqlite`. On the two retrieving kinds it would otherwise fall
/// through to the generic unknown-entry sentence, and on a `blob` it is worse than that — every head
/// word this grammar does not own is an ENGINE there, so `#[ingraph::blob(sqlite)]` would register a
/// store called `sqlite` and fail much later, at a `Bound` the author never wrote.
/// It costs a `blob` the four words as ENGINE NAMES, and that is the trade taken rather than an
/// oversight: this grammar now OWNS them, so a family that wanted a store called `sqlite` cannot
/// have one. What it buys is that the mistake an author will actually make — moving a record's head
/// onto an index — is answered at the word they wrote instead of at a `Bound` they did not.
const STORES_NO_ROWS: &str = "a derived index stores no rows — a store word names the DATABASE rows \
                              land in, and a node whose messages land in one is a `record`. This \
                              node's own storage is its ENGINES, and they are per FIELD";

fn options(attrs: &[syn::Attribute], kind: NodeKind, errors: &mut Errors) -> Head {
  /// One family a derived index does not claim: the word, and what it has instead.
  ///
  /// A TABLE rather than an arm apiece, [`crate::fields`]'s reason: what each refusal says differs
  /// in one clause and the storage law is the rest, so separate arms would be separate places for
  /// that law to drift.
  ///
  /// `graphql` LEFT this table in the index-graphql round: the word is now a real block on the two
  /// retrieving kinds and a refusal with its own sentence on the third, and neither of those is
  /// *the family this declaration does not claim*.
  const CLAIMED: [(&str, &str); 10] = [
    (
      "key",
      "a derived index does not name its key type, because it declares none — its key is the \
       upstream's, carried whole",
    ),
    (
      "lineage",
      "a derived index does not declare a lineage — a document descends from the message it was \
       derived from, so the path to the root is the upstream's and is bound from it",
    ),
    (
      "persist",
      "a derived index stores no rows — `persist(…)` was the ROW storage's old wrapper, and it is \
       gone besides: a node whose messages land in a database is a `record`, and a record names its \
       stores BARE",
    ),
    ("sqlite", STORES_NO_ROWS),
    ("postgres", STORES_NO_ROWS),
    ("mysql", STORES_NO_ROWS),
    ("mongo", STORES_NO_ROWS),
    ("table", STORES_NO_ROWS),
    (
      "derived",
      "a derived index declares no reverse positions — a reverse position is another record \
       pointing back at this one's rows, and this node has none",
    ),
    (
      "implements",
      "an interface's members are NODES WITH ROWS — a membership is proved by a stored row \
       answering the contract's columns, and a derived index has no row of its own to answer with",
    ),
  ];

  let mut krate = None;
  let mut block: Option<UpstreamBlock> = None;
  let mut dedup: Option<Dedup> = None;
  let mut stores: Vec<Engine> = Vec::new();
  let mut extension: Option<Extension> = None;
  let mut graphql: Option<IndexGraphql> = None;
  let mut numbers = Numbers::default();
  let mut graphql_at: Option<syn::Path> = None;
  let mut rename: Option<IndexRename> = None;
  let mut rename_at: Option<syn::Path> = None;
  let mut slot: Option<syn::LitStr> = None;
  // A BOOL rather than an `Option<syn::Path>`: the word carries nothing, and the repeat refusal
  // lands on the SECOND one, which is in hand where it is written — so a stored first path would be
  // a token nothing spends. `Role::elected` one grain down is the same shape for the same reason.
  let mut data = false;
  let mut keys = false;
  let mut subscribe = false;
  attribute::walk(attrs, errors, |meta, errors| {
    // `crate` is a keyword; syn's nested-meta path parser takes it with `Ident::parse_any`, so it
    // arrives here as an ordinary one-segment path.
    if meta.path.is_ident("crate") {
      match value::parse_literal::<syn::Path>(
        &meta,
        "`#[ingraph(crate = \"…\")]` must be a path to the `ingraph` crate, in a string literal",
      ) {
        Ok(path) => set_once(
          &mut krate,
          path,
          &meta.path,
          "`crate` is declared more than once — one declaration names one crate",
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }

    if meta.path.is_ident("upstream") {
      let at = meta.path.clone();
      // A SECOND source is the M×N shape, not a repeat: two upstreams key one index by an ENUM over
      // their keys, which is a different carried field of a different type. Named rather than
      // refused as a duplicate, because an author who wrote two has the right idea.
      if block.is_some() {
        errors.push(named(
          &meta,
          format!(
            "a second `upstream(…)` is the MULTI-UPSTREAM shape and that grammar has not arrived — with \
             two upstreams a document came from one or the other, so the key this {noun} carries \
             becomes an enum over both upstreams' keys and the field holding it changes type. One \
             upstream is one `upstream(…)`",
            noun = kind.noun(),
          ),
        ));
        return Ok(());
      }
      let mut node = None;
      let mut entries: Vec<UpstreamEntry> = Vec::new();
      let walked = attribute::options(&meta, |inner| {
        source_entry(&inner, &mut node, &mut entries, errors)
      });
      block = Some(UpstreamBlock { node, entries, at });
      return walked;
    }

    // How a RETRIEVE over this index tells two of its keys apart. Legal on `fulltext` and on
    // `vector` — the two kinds that answer a query — and refused on `blob`, which answers an
    // address and has no hit stream to collapse.
    if meta.path.is_ident("dedup") {
      if !matches!(kind, NodeKind::Fulltext | NodeKind::Vector) {
        errors.push(named(
          &meta,
          format!(
            "`dedup(…)` is a RETRIEVE's word and {article} {noun} does not retrieve — dedup \
             collapses an engine's hit stream by key, and this node answers an address rather than \
             a ranking",
            article = kind.article(),
            noun = kind.noun(),
          ),
        ));
        return Ok(());
      }
      if dedup.is_some() {
        errors.push(syn::Error::new_spanned(
          &meta.path,
          "`dedup` is declared more than once — one index dedupes one way",
        ));
        return Ok(());
      }
      return attribute::options(&meta, |inner| {
        dedup_word(&inner, &mut dedup, errors);
        Ok(())
      });
    }

    // WHAT THE CORPUS IS CALLED WHERE IT IS STORED — the DURABLE name, and the one word in this
    // grammar that reaches a deployment's disk. Claimed above the open position below it for the
    // reason every framework word is.
    if meta.path.is_ident(SLOT) {
      if kind != NodeKind::Blob {
        errors.push(named(&meta, slot_wrong_grain(kind)));
        return Ok(());
      }
      if slot.is_some() {
        errors.push(syn::Error::new_spanned(
          &meta.path,
          "`slot` is declared more than once — one family's objects live in ONE place, and a second \
           name would be a second answer to a question with one",
        ));
        attribute::skip_entry(&meta);
        return Ok(());
      }
      match value::literal(&meta, SLOT_SHAPE) {
        Ok(name) => {
          refuse_a_malformed_slot(&name, errors);
          slot = Some(name);
        }
        Err(e) => errors.push(e),
      }
      return Ok(());
    }

    // WHAT THE MINTED RUST TYPES ARE CALLED — the BONES axis, at the top level and never inside a
    // backend block. Claimed above every open position below it for the reason the wire word is: on
    // a blob the catch-all would otherwise read it as a store called `rename`.
    if meta.path.is_ident(RENAME) {
      if kind == NodeKind::Blob {
        errors.push(named(&meta, BLOB_MINTS_NO_TYPE.to_owned()));
        return Ok(());
      }
      if rename_at.is_some() {
        errors.push(named(
          &meta,
          "`rename` is declared more than once — the two forms are ONE word: `rename = \"…\"` \
           re-bases the whole minted family and `rename(<piece> = \"…\")` names individual mints, \
           so writing both says the family is called two things"
            .to_owned(),
        ));
        return Ok(());
      }
      rename_at = Some(meta.path.clone());
      return rename_word(&meta, &mut rename, kind, errors);
    }

    // THE AXIS MISTAKE, refused BY NAME rather than left to the unknown-entry line: an author who
    // wrote `first` here has a coherent idea in the wrong tier, and what they are owed is which of
    // the two words this position takes.
    if meta.path.is_ident(FIRST) {
      errors.push(named(&meta, first_is_the_skins_word(kind)));
      return Ok(());
    }

    // THE NUMBER WORDS — the container tier of the wire road's number design, read above the open
    // position for the wire block's own reason: on a blob every word this grammar does not own is
    // somebody's ENGINE, so a word it does own has to be claimed before the catch-all takes it for
    // a store called `limit`.
    if let Some(walked) = numbers_word(&meta, &mut numbers, "this declaration's head", errors) {
      if kind == NodeKind::Blob {
        // The seat is cleared as well as refused, so one wrong word does not become a cascade about
        // a number the model was never going to spend.
        numbers = Numbers::default();
        errors.push(named(
          &meta,
          blob_takes_no_number(&meta.path.to_token_stream().to_string()),
        ));
      }
      return walked;
    }

    // THE WIRE SKINS — one word per backend this declaration is dressed for.
    //
    // Read here, above every open position below it, for the reason every framework word is: on a
    // blob every word this grammar does not own is somebody's engine, and a word it owns has to be
    // claimed before the catch-all swallows it as a store called `graphql`.
    if meta.path.is_ident(GRAPHQL) {
      if kind == NodeKind::Blob {
        errors.push(named(&meta, BLOB_MINTS_NO_WIRE.to_owned()));
        return Ok(());
      }
      if graphql_at.is_some() {
        errors.push(syn::Error::new_spanned(
          &meta.path,
          "`graphql(…)` is declared more than once — one block holds every backend, and a second \
           one could only repeat or contradict the first. Two skins are two WORDS inside one block: \
           `graphql(async_graphql, …)`",
        ));
        attribute::skip_entry(&meta);
        return Ok(());
      }
      graphql_at = Some(meta.path.clone());
      return graphql_word(&meta, &mut graphql, errors);
    }

    // The RETIRED head word, refused by name with its successor in the sentence. It is one refusal
    // on every kind rather than an election on one and a wrong-kind on two: the word no longer
    // elects anything anywhere, so what an author who wrote it needs told is the marker — and which
    // marker their own declaration takes.
    if meta.path.is_ident("embedding") {
      errors.push(named(&meta, retired_head_word(kind)));
      return Ok(());
    }

    // THE TIER WORD — `keys`, and it declares a fact about the UPSTREAM rather than patching this
    // declaration.
    //
    // A dressed election answers each road at two tiers: the KEYS tier hands back addresses and
    // touches no store, and the HYDRATED tier hands back the upstream's whole entities and reads
    // them out of one. The second projects `<Upstream as Hydrates>::Db`, which only a record with a
    // queryable row implements — so which tiers a declaration can mount is decided by which RUNG of
    // the record ladder its upstream is on, and by nothing this declaration could choose.
    //
    // A RECORD upstream mounts both, unconditionally and with no word: storage is guaranteed, so
    // hydration can never miss. An ENTITY upstream mounts the keys tier, and this word is where it
    // says so — the pure-engine deployment's honest home, a search surface over a node that holds no
    // rows anywhere. Written with no word, an entity upstream reaches the hydrated demand and the
    // compiler answers `E0277` at `upstream(node = "…")` carrying `Hydrates`' own sentence, which
    // names both exits: persist the upstream, or wear this word.
    if meta.path.is_ident(KEYS_TIER) {
      if kind == NodeKind::Blob {
        errors.push(named(
          &meta,
          format!(
            "{article} {noun} answers an ADDRESS rather than a ranking, so it mounts no tier pair \
             for `{KEYS_TIER}` to narrow — the word says a dressed election publishes addresses \
             and not hydrated entities, and every answer here is an address already",
            article = kind.article(),
            noun = kind.noun(),
          ),
        ));
        attribute::skip_entry(&meta);
        return Ok(());
      }
      if attribute::has_value(&meta) || attribute::has_block(&meta) {
        errors.push(named(
          &meta,
          format!(
            "`{KEYS_TIER}` is a BARE word — it states which RUNG this declaration's upstream is \
             on, and a rung has no knob. What it would carry is already decided elsewhere: WHICH \
             fields are elected is each field's own marker, and WHAT a key looks like is the \
             upstream's key type"
          ),
        ));
        return Ok(());
      }
      if keys {
        errors.push(syn::Error::new_spanned(
          &meta.path,
          format!(
            "`{KEYS_TIER}` is declared more than once — the word is PRESENCE, so the second one \
             says exactly what the first already said"
          ),
        ));
        attribute::skip_entry(&meta);
        return Ok(());
      }
      keys = true;
      return Ok(());
    }

    // THE LAUNCH WORD, and the one place this grammar's `subscribe` differs from every other
    // kind's: elsewhere the word NAMES AN EDGE, and here the edge is already `upstream(…)`'s. So
    // what is left for it to say is the other half — that this declaration is a NODE the deployment
    // launches, rather than a corpus somebody else fills. See `IndexModel::subscriber`.
    if meta.path.is_ident(SUBSCRIBE) {
      if kind != NodeKind::Fulltext {
        errors.push(named(&meta, subscribe_wrong_kind(kind)));
        attribute::skip_entry(&meta);
        return Ok(());
      }
      if attribute::has_value(&meta) {
        errors.push(named(
          &meta,
          format!(
            "`{SUBSCRIBE}` is a BARE word here, and the difference from every other kind's is the \
             one thing worth knowing about it: an operator's and a record's `{SUBSCRIBE} = \"…\"` \
             NAMES the upstream, and {article} {noun} already named one in `upstream(…)` — where \
             the edge and the projection are ONE entry, because every field of a document is read \
             out of the message it was derived from. So there is no edge left for a value to name, \
             and what the bare word says is the half `upstream(…)` does not: that this declaration \
             LAUNCHES",
            article = kind.article(),
            noun = kind.noun(),
          ),
        ));
        return Ok(());
      }
      if attribute::has_block(&meta) {
        errors.push(named(
          &meta,
          format!(
            "`{SUBSCRIBE}` carries no block here — the per-upstream words an operator writes inside \
             one (`channel`, `changes(<db>)`, `out`, `key`, `notify`) all describe an edge, and \
             this declaration's edge is `upstream(…)`'s. They are recorded and not built: a \
             subscribing index takes its edge at the framework's own depth and receives the \
             upstream's message whole, which is what its projections read"
          ),
        ));
        return Ok(());
      }
      if subscribe {
        errors.push(syn::Error::new_spanned(
          &meta.path,
          format!(
            "`{SUBSCRIBE}` is declared more than once — the word is PRESENCE, so the second one \
             says exactly what the first already said"
          ),
        ));
        attribute::skip_entry(&meta);
        return Ok(());
      }
      subscribe = true;
      return Ok(());
    }

    // HOW THE ADDRESSES END — the artifact family's own word, in whichever of its six forms.
    if meta.path.is_ident(extension::EXTENSION) {
      if kind != NodeKind::Blob {
        errors.push(named(&meta, extension::wrong_kind(kind)));
        return Ok(());
      }
      if extension.is_some() {
        errors.push(syn::Error::new_spanned(
          &meta.path,
          "`extension` is declared more than once — one family ends its addresses ONE way, and a \
           second word would be a second answer to a question with one",
        ));
        attribute::skip_entry(&meta);
        return Ok(());
      }
      extension_word(&meta, &mut extension, errors);
      return Ok(());
    }

    // WHETHER THE BYTES TRAVEL — the artifact family's other head word, and a PRESENCE one. It is
    // read here, above the catch-all below, for the reason every framework word is: on a blob every
    // word this grammar does not own is somebody's engine, so a word it owns has to be claimed
    // before the open position swallows it as a store called `data`.
    if meta.path.is_ident(index::DATA) {
      if kind != NodeKind::Blob {
        errors.push(named(&meta, index::data_wrong_kind(kind)));
        return Ok(());
      }
      if data {
        errors.push(syn::Error::new_spanned(
          &meta.path,
          "`data` is declared more than once — the word is PRESENCE, so the second one says exactly \
           what the first already said. There is no stronger form of it to reach for: whether this \
           family's bytes may ride beside its address is one fact, and it is either declared or it \
           is not",
        ));
        attribute::skip_entry(&meta);
        return Ok(());
      }
      if attribute::has_value(&meta) || attribute::has_block(&meta) {
        errors.push(named(
          &meta,
          "`data` is a BARE word — write it and this family's object may be served inline beside \
           its address, leave it out and the address is the whole of the answer. There is nothing \
           for it to carry: what an address ENDS with is `extension`'s question and WHERE the \
           object is stored is the store word's, so *the bytes may ride along* has no knob left \
           inside it"
            .to_owned(),
        ));
        return Ok(());
      }
      data = true;
      return Ok(());
    }

    // The FANOUT marker, at the head where a blob's engines are — refused by name, with the DESIGN's
    // own reason rather than as an unknown word. It is deferred, not absent, and an author who
    // reached for it is owed the difference.
    if kind == NodeKind::Blob && meta.path.is_ident(FANOUT) {
      errors.push(named(
        &meta,
        "`fanout` writes one document to EVERY declared engine at once so that each engine's \
         ranking enters fusion as separate evidence — and an artifact family answers an ADDRESS \
         rather than a ranking, so there is no second ranking for a second copy to contribute. \
         Storing one artifact in two places is a real want and a different feature; it is recorded \
         and not built. Several engines here are declared PORTABILITY, and the deployment picks one"
          .to_owned(),
      ));
      attribute::skip_entry(&meta);
      return Ok(());
    }

    // This node's OWN storage block, refused for good now rather than as a wait. The engines ARRIVED
    // and they did not land here: they are per-FIELD, because a slot is `(field × engine)` and a
    // block on the head could only name engines for the declaration as a whole.
    if kind
      .storage_block()
      .is_some_and(|own| meta.path.is_ident(own))
    {
      errors.push(named(
        &meta,
        format!(
          "`{block}(…)` is not where {article} {noun} names its ENGINES — a slot is one FIELD in \
           one engine, so the engines are written on the field beside its election: \
           `#[ingraph({marker}, <engine>, <engine>(<knob> = …))]`. A block here could only name \
           them for the whole declaration, which is a grain coarser than the storage actually is",
          block = kind.as_str(),
          article = kind.article(),
          noun = kind.noun(),
          marker = kind.election().unwrap_or("…"),
        ),
      ));
      return Ok(());
    }

    // Somebody else's storage block, which is the one-storage law read from this side.
    for other in [NodeKind::Fulltext, NodeKind::Vector, NodeKind::Blob] {
      if other != kind && meta.path.is_ident(other.as_str()) {
        errors.push(named(
          &meta,
          format!(
            "{article} {noun} owns no {held} — one is its OWN node, declared with the `{other}` \
             macro over the same upstream. {law}",
            article = kind.article(),
            noun = kind.noun(),
            held = other.noun(),
            other = other.as_str(),
            law = owns_one_storage(kind),
          ),
        ));
        return Ok(());
      }
    }

    for (family, why) in CLAIMED {
      if meta.path.is_ident(family) {
        errors.push(named(&meta, format!("{why}. {}", owns_one_storage(kind))));
        return Ok(());
      }
    }

    // THE AGGREGATE's two role words, refused by name and ABOVE the blob's engine catch-all below —
    // a word this grammar can answer must never be read as somebody's engine.
    for word in [
      ingraph_codegen::aggregate::GROUP,
      ingraph_codegen::aggregate::MEASURE,
    ] {
      if meta.path.is_ident(word) {
        errors.push(named(
          &meta,
          crate::aggregate::wrong_kind(word, kind, crate::aggregate::Written::AtTheHead),
        ));
        return Ok(());
      }
    }

    // AN ENGINE BLOCK, on the ONE kind whose engines are named at the head. Everything the field
    // grammar does for a `(field × engine)` slot, done here for a `(declaration × engine)` one: an
    // artifact family elects nothing, so there is no field for a block to sit beside and the head is
    // the only position coarse enough to name where its objects go.
    //
    // A CATCH-ALL, and it has to be: every word the framework does not own is an engine, which is
    // what an open vocabulary means. It sits below every named arm above so that a word this grammar
    // DOES own is never read as somebody's engine.
    if kind == NodeKind::Blob {
      match meta.path.get_ident().cloned() {
        Some(word) => blob_engine(&meta, word, &mut stores, errors),
        None => errors.push(attribute::unknown(
          &meta,
          "an engine is named by ONE word — `fs`, `s3` — and a path with several segments names no \
           engine. The word is bare because it is a NAME the deployment binds: a path written on a \
           declaration would bind it here, where the store a build actually compiled is not knowable",
          // THE OPEN POSITION, and #256's D2 read from this side: every word the framework does not
          // own is an engine, so there is no vocabulary here for a typo to miss. What a misspelt
          // engine word gets is the `Bound` sentence at the type layer, later than a typo deserves,
          // and closing that gap needs the projection-through-member the two-expansion wall blocks.
          &[],
        )),
      }
      return Ok(());
    }

    errors.push(attribute::unknown(
      &meta,
      &format!(
        "unknown entry on {article} {noun} — it takes `upstream(…)`{retrieves} and `crate = \"…\"`, \
         every other block naming something a node with no rows and no id of its own does not have. \
         WHICH of its fields it indexes is not written here at all, and neither is WHERE they are \
         stored: both are markers on the field itself{elects}",
        article = kind.article(),
        noun = kind.noun(),
        retrieves = match kind {
          NodeKind::Fulltext =>
            ", `dedup(…)`, `graphql(<backend>)`, `keys`, `subscribe`, `limit = N`, `depth = N`, \
             `ceiling = N`, `streams = N`",
          NodeKind::Vector =>
            ", `dedup(…)`, `graphql(<backend>)`, `keys`, `limit = N`, `depth = N`, `ceiling = N`, \
             `streams = N`",
          _ => "",
        },
        elects = match kind.election() {
          Some(marker) => format!(", `#[ingraph({marker}, <engine>)]`"),
          None => String::new(),
        },
      ),
      // The head's own words, and `dedup` only on the kinds that retrieve — the sentence's own
      // split, so a `blob` is never offered a word its next compile would refuse.
      &match kind {
        NodeKind::Fulltext => {
          let mut words = vec!["upstream", "dedup", GRAPHQL, KEYS_TIER, SUBSCRIBE, "crate"];
          words.extend(NUMBER_WORDS);
          words
        }
        NodeKind::Vector => {
          let mut words = vec!["upstream", "dedup", GRAPHQL, KEYS_TIER, "crate"];
          words.extend(NUMBER_WORDS);
          words
        }
        _ => vec!["upstream", "crate"],
      },
    ));
    Ok(())
  });
  if let Some(Extension::Column(column)) = &extension {
    extension_fences(column, errors);
  }
  Head {
    numbers,
    krate: krate.unwrap_or_else(|| syn::parse_quote!(::ingraph)),
    block,
    dedup,
    stores,
    extension,
    data,
    graphql,
    rename,
    slot,
    keys,
    subscribe,
  }
}

/// The four BONES numbers, as an author writes them at either tier.
///
/// A closed set, and it is the SUGGESTION TABLE as well as the vocabulary: a near miss at either
/// position is answered with these four and never with a neighbouring scope's words.
pub(crate) const NUMBER_WORDS: [&str; 4] = [LIMIT, DEPTH, CEILING, STREAMS];

/// `limit = N` — how many rows a door of this thing answers with when nothing asks otherwise.
pub(crate) const LIMIT: &str = "limit";

/// `depth = N` — how deep each stream behind a fold is fetched when nothing asks otherwise.
pub(crate) const DEPTH: &str = "depth";

/// `ceiling = N` — the WALL, the one number here that no request may rewrite.
const CEILING: &str = "ceiling";

/// `streams = N` — the second PROTECTIVE number: how many query vectors one request may ask a
/// `_with` road with.
///
/// # It shares a string with a FLOOR WORD, and the two never meet
///
/// [`FLOOR_WORDS`] holds a `"streams"` of its own — the framework's answer ROW on a set hit, refused
/// every rename at every skin position. This one is a BONES number, read at the head and on an
/// election, which is outside every `graphql(…)` block. So the two readers cannot see each other's
/// position: [`numbers_word`] runs where a backend block is not, and [`floor_word`] runs only inside
/// one.
///
/// They are one CONCEPT wearing two surfaces, which is exactly `depth`'s shape — a bones number and
/// a wire row, spelled the same because they are about the same thing — and the ruling that minted
/// this word said so by name.
const STREAMS: &str = "streams";

/// `first = N` — the same number as [`LIMIT`], in GraphQL's own word, inside a backend block.
const FIRST: &str = "first";

/// The bare `keys` at the HEAD — this declaration's upstream is an ENTITY, so its answer family
/// mounts the keys tier alone.
///
/// Spelled apart from the road word [`Field::Keys`] writes on an ELECTION: the two share a string
/// and nothing else. One is a RENAME inside a backend block, naming a field in that backend's
/// schema; this one is a TIER FACT at the head, about which rung the upstream sits on. One const
/// read by both grammars would be a name whose meaning depended on where it was read.
const KEYS_TIER: &str = "keys";

/// The bare `subscribe` at the HEAD — this declaration is a NODE the deployment LAUNCHES, which
/// receives its upstream's messages over a real edge and fills its own corpora.
///
/// The same string every other kind's edge word is spelled with, and deliberately: what an author
/// reaches for when they want a declaration wired into a running graph is this word, and a grammar
/// that spelled it `launch` here would make one act have two names for no reason a reader could
/// state. What it CARRIES differs — see the refusals at the head — because the edge it would have
/// named is `upstream(…)`'s already.
const SUBSCRIBE: &str = "subscribe";

/// The sentence [`SUBSCRIBE`] is refused with on the two kinds that do not have the road yet.
///
/// It names the DEFERRAL rather than reporting an unknown word, which is this grammar's posture for
/// every word that is coming: the pattern landed on the full-text road because tantivy is the one
/// engine in this tree that answers the write lane, and a vector or artifact declaration wearing the
/// word would launch a node with nowhere to put what it received.
fn subscribe_wrong_kind(kind: NodeKind) -> String {
  format!(
    "`{SUBSCRIBE}` makes a declaration a LAUNCHABLE NODE — one that receives its upstream's \
     messages over an edge and fills its own corpora — and {article} {noun} does not have that road \
     yet. It is deferred rather than absent: the road is one `FulltextLane`-shaped seam per storage \
     family, and the full-text one landed first because it is the family with a live engine behind \
     it. Until this kind has its own, the corpora are filled by a hand that holds the mount",
    article = kind.article(),
    noun = kind.noun(),
  )
}

/// What a ROAD BLOCK names, in the sentences [`attribute::named_block`] writes about its shape.
///
/// A FIELD where every other block in this workspace names a TYPE — which is the whole reason that
/// layer takes the noun as a parameter: the 2026-08-16 ruling put both axes under one grammar, and a
/// road's author told the block was *for naming the type* would be reading a sentence about the
/// wrong axis.
const FIELD_NOUN: &str = "field";

/// ONE ROAD'S QUERY-FIELD NAME, read out of its own block — `keys(rename = "clipNeighbours")`.
///
/// # A BLOCK and no longer a flat word, which is the ruling's first law
///
/// `keys = "…"` was the shipped spelling and is now `keys(rename = "…")`, on the user's own
/// sentence — *不要有糖, 糖留给以后其他东西, rename 不值得一个糖*. ONE grammar covers every name
/// seat there is, so the flat position stays free for whatever later earns it, and a reader who has
/// learnt `output(rename = …)` has learnt this too.
///
/// HELD TO GRAPHQL'S OWN GRAMMAR at the literal that wrote it, [`crate::wire`]'s measurement: a
/// field named outside `[_A-Za-z][_0-9A-Za-z]*` builds a schema whose exported SDL is not parseable
/// GraphQL, and no layer below this one refuses it. VERBATIM otherwise — a derived field name is
/// composed of three parts, so a word that re-cased or re-composed what an author wrote would be a
/// rename they could not predict.
fn road_block(
  meta: &syn::meta::ParseNestedMeta<'_>,
  slot: &mut Option<syn::LitStr>,
  road: Field,
  field: &syn::Ident,
  errors: &mut Errors,
) -> syn::Result<()> {
  let word = road.as_str();
  let walked = attribute::named_block(meta, slot, word, FIELD_NOUN, errors, |option| {
    value::literal(
      option,
      &format!(
        "`{word}(rename = \"…\")` is what this backend calls {what} for `{field}`, in a string \
         literal — `{word}(rename = \"clipNeighbours\")`. It names a field in the ROOT's namespace \
         and nothing in Rust, so it is carried verbatim",
        what = road.what(),
      ),
    )
  });
  if let Some(written) = slot.as_ref() {
    crate::wire::refuse_invalid_name(&written.value(), written, errors);
  }
  walked
}

/// ONE NUMBER, read into its seat — the shared reader both tiers and both axes spend.
///
/// # Why the currency is `NonZeroU32` and the zero is refused HERE
///
/// The door family's own currency became `NonZeroUsize` in the retype round, precisely so that a
/// zero would be unrepresentable rather than a fork somebody has to remember. A declaration's number
/// is the same number one tier up, so the same law holds — and this is the position that can say WHY
/// a zero is wrong for each word, which a type-level refusal inside an expansion could not.
///
/// `pub(crate)` so the SEARCH grammar reads its two numbers through it: a recipe's `limit` and a
/// member's `depth` are the same numbers at the tier above an election's, and a second reader would
/// be a second place for the width, the zero and the repeat to be decided.
pub(crate) fn number(
  meta: &syn::meta::ParseNestedMeta<'_>,
  slot: &mut Option<core::num::NonZeroU32>,
  word: &str,
  scope: &str,
  errors: &mut Errors,
) -> syn::Result<()> {
  let written = match value::integer(meta, &number_shape(word)) {
    Ok(written) => written,
    Err(refusal) => {
      errors.push(refusal);
      return Ok(());
    }
  };
  let Ok(count) = written.base10_parse::<u32>() else {
    errors.push(syn::Error::new_spanned(
      &written,
      format!(
        "`{word}` is past what this grammar carries a declared number at — the width is `u32`, \
         which is the width `route_depth` already takes a wall at, and a number a person types is \
         not an address space"
      ),
    ));
    return Ok(());
  };
  let Some(count) = core::num::NonZeroU32::new(count) else {
    errors.push(syn::Error::new_spanned(&written, number_zero(word)));
    return Ok(());
  };
  set_once(
    slot,
    count,
    &meta.path,
    &format!("`{word}` is declared more than once in {scope} — one number"),
    errors,
  );
  Ok(())
}

/// The refusal one of these words gets when its value is not a plain integer.
///
/// A BARE integer rather than a string, on the `alias(depth = …)` precedent: the values written as
/// strings in this grammar are the ones that are RUST — a path, a type, an identifier — and are
/// re-parsed on the way in. A count is a number in both languages and has nothing to be re-parsed
/// from.
fn number_shape(word: &str) -> String {
  format!("`{word}` is a COUNT, as a plain integer — `{word} = 20`")
}

/// The refusal a ZERO gets, in this word's own terms.
fn number_zero(word: &str) -> String {
  match word {
    CEILING => format!(
      "`{CEILING} = 0` is a wall no request can get through — a ceiling CAPS a fetch, so zero would \
       refuse every read this declaration has rather than protect them. A deployment that wants no \
       reads removes the doors; leaving the word out is the author's informed openness"
    ),
    STREAMS => format!(
      "`{STREAMS} = 0` admits no query vectors at all, which refuses every question the `_with` \
       road has rather than bounding them: a set query with no query vectors asks nothing, so a \
       guard of zero is a road that answers nobody. The smallest guard that admits a question is \
       `{STREAMS} = 1`; leaving the word out is the author's informed openness"
    ),
    FIRST => format!(
      "`{FIRST} = 0` would publish an SDL default of nothing — a schema whose page size promises no \
       rows. The wire's `first: 0` is a REQUEST and answers `[]` without touching a door; a DEFAULT \
       of zero is a declaration saying every unasked query is empty"
    ),
    _ => format!(
      "`{word} = 0` asks for an answer with no rows, which this family made unrepresentable rather \
       than forkable — every door's number is a `NonZeroUsize`. What a caller who wants nothing \
       does is not ask"
    ),
  }
}

/// Whether `meta` is one of the three, and its reading where it is — [`None`] where the word belongs
/// to whoever called.
fn numbers_word(
  meta: &syn::meta::ParseNestedMeta<'_>,
  numbers: &mut Numbers,
  scope: &str,
  errors: &mut Errors,
) -> Option<syn::Result<()>> {
  for (word, slot) in [
    (LIMIT, &mut numbers.limit),
    (DEPTH, &mut numbers.depth),
    (CEILING, &mut numbers.ceiling),
    (STREAMS, &mut numbers.streams),
  ] {
    if meta.path.is_ident(word) {
      return Some(number(meta, slot, word, scope, errors));
    }
  }
  None
}

/// What an author who wrote `first` at the BONES tier is told.
///
/// TRUTHFUL and not a wrong-word line: `first` IS a number this declaration takes, one block over.
/// The head carries the Rust vocabulary because the head is where a door's semantic default is
/// stated, and the schema's own spelling of the same number sits inside the skin that publishes it.
fn first_is_the_skins_word(kind: NodeKind) -> String {
  match kind {
    NodeKind::Blob => blob_takes_no_number(FIRST),
    _ => format!(
      "`{FIRST}` is GRAPHQL's word for how many, so it is written inside the skin that publishes \
       it — `{GRAPHQL}(<backend>({FIRST} = N))`, at this head or on an election. What the head \
       takes in Rust vocabulary is `{limit}`, which is the same number a door is called with, and \
       `{depth}` beside it",
      limit = NUMBER_WORDS[0],
      depth = NUMBER_WORDS[1],
    ),
  }
}

/// What a BLOB is told when it writes one of them.
///
/// TRUTHFUL and not a wrong-kind line: the words are about DOORS — how many rows one answers, how
/// deep a fold fetches, how much a request may cost — and an artifact family answers an ADDRESS for
/// a key it was handed. There is no ranking, no fold and no page for a number to be about.
fn blob_takes_no_number(word: &str) -> String {
  format!(
    "`{word}` is a number about RETRIEVAL — how many rows a door answers, how deep a fold fetches, \
     and how much of either a request may ask for. An artifact family retrieves nothing: it answers \
     the ADDRESS of the object stored under a key it was handed, so there is no ranking for a \
     number to cut. The word opens on `vector` and `fulltext` declarations, at the head and on an \
     election"
  )
}

/// THE ELECTION'S OWN SKIN BLOCK — `graphql(<backend>(first = N, keys(rename = "…")))`, on a field.
///
/// # It is the container block's twin, one tier down, and it exists for that one's reason
///
/// A wire default is the SKIN's fact, so it lives in the block that names the skin: two backends
/// dressing one election each publish their own default, and neither touches the other's. What the
/// FIELD adds over the head is specificity — the same word, written closer to the door it is about,
/// which is what makes the resolution a chain rather than a single seat.
///
/// # TEN WORDS in three classes, and the classes are what a reader has to hold
///
/// `first` is a NUMBER, published as an SDL default, and it is the one word here written flat: a
/// count has no name for a `rename` row to carry.
///
/// Four name TYPES. `question` and `engines` are the two a request builds by hand for this election
/// — `<Index><Field>Question` and `<Index><Field>Engines`; `sighting` and `fused_key_match` are the
/// two a fused answer is READ through — `<Index><Field>Sighting` and `<Index><Field>FusedKeyMatch`.
/// The ARGUMENTS and ROWS that carry all four are spelled `question:`, `engines:`, `evidence` and
/// `node` in every schema this framework writes and are not moved by anything here: that vocabulary
/// is the uniform floor, and [`FLOOR_WORDS`] is where the whole of it is refused by name.
///
/// The five road words name the QUERY FIELDS this election mounts, one per rung of
/// [`Field`] — and they live here rather than at either type-renaming tier because a query field is
/// neither a Rust type nor an SDL type. It is a name in the ROOT's own namespace, where every
/// mounted declaration's fields meet, so the collision the word breaks is per FIELD and per BACKEND
/// — exactly this block's grain.
///
/// Every word is spent, which is the presence law and not a stub: a word parsed into a model
/// nothing reads is a promise rather than a rule.
fn election_skins(
  meta: &syn::meta::ParseNestedMeta<'_>,
  skins: &mut Vec<ElectionBackend>,
  field: &syn::Ident,
  errors: &mut Errors,
) -> syn::Result<()> {
  let walked = attribute::options(meta, |inner| {
    let Some(kind) = crate::parse::graphql_kind(&inner.path) else {
      errors.push(attribute::unknown(
        &inner,
        &format!(
          "unknown backend in `{GRAPHQL}(…)` on `{field}` — this framework renders through {list}, \
           and a word naming none of them names no skin. The block holds WORDS rather than knobs \
           for the head block's reason: each one adds one backend's own description over the same \
           Rust election",
          list = backend_list(),
        ),
        &GraphqlKind::ALL.map(GraphqlKind::as_str),
      ));
      return Ok(());
    };
    if skins.iter().any(|backend| backend.kind == kind) {
      errors.push(syn::Error::new_spanned(
        &inner.path,
        format!(
          "`{kind}` is declared more than once in `{GRAPHQL}(…)` on `{field}` — one block per \
           backend, because a backend has ONE skin and a second word could only re-describe it",
          kind = kind.as_str(),
        ),
      ));
      attribute::skip_entry(&inner);
      return Ok(());
    }
    let mut backend = ElectionBackend::of(kind);
    let walked = attribute::options(&inner, |entry| {
      if entry.path.is_ident(FIRST) {
        return number(
          &entry,
          &mut backend.first,
          FIRST,
          &format!("`{field}`'s backend block"),
          errors,
        );
      }
      // THE FOUR TYPE SEATS — the request side's two and the answer side's two — read through the
      // same block every SDL type rename in this workspace takes: a `LitStr` behind a `rename` row,
      // fenced by GraphQL's own Name grammar and by nothing of Rust's.
      for (word, seat) in [
        (QUESTION, &mut backend.question),
        (ENGINES, &mut backend.engines),
        (SIGHTING, &mut backend.sighting),
        (FUSED_KEY_MATCH, &mut backend.fused_key_match),
      ] {
        if entry.path.is_ident(word) {
          let walked = attribute::sdl_name_block(&entry, seat, word, errors);
          if let Some(name) = seat.as_ref() {
            crate::wire::refuse_invalid_name(&name.value(), name, errors);
          }
          return walked;
        }
      }
      // THE FIVE ROAD SEATS. The table is written out rather than derived, because a `&mut` per seat
      // is what the reader fills; the READ side is `ElectionBackend::road`, and
      // `every_road_word_reaches_its_own_seat` is what holds the two lists to each other.
      for (road, seat) in [
        (Field::Keys, &mut backend.keys),
        (Field::Hydrated, &mut backend.hydrated),
        (Field::Fused, &mut backend.fused),
        (Field::Similar, &mut backend.similar),
        (Field::SimilarHydrated, &mut backend.similar_hydrated),
      ] {
        if entry.path.is_ident(road.as_str()) {
          return road_block(&entry, seat, road, field, errors);
        }
      }
      if let Some(floor) = floor_word(&entry.path) {
        errors.push(named(&entry, floor_is_the_frameworks(floor)));
        return Ok(());
      }
      errors.push(attribute::unknown(
        &entry,
        &format!(
          "unknown entry in a backend block on `{field}` — an ELECTION's skin sets the SDL default \
           its query arguments publish, `{FIRST} = N`; names the two types a request builds, \
           `{QUESTION}(rename = \"…\")` and `{ENGINES}(rename = \"…\")`; names the two a fused \
           answer is read through, `{SIGHTING}(rename = \"…\")` and \
           `{FUSED_KEY_MATCH}(rename = \"…\")`; and names the query fields it mounts, one block \
           per road: {roads}. The Rust-vocabulary numbers beside `{FIRST}` are `{limit}` and \
           `{depth}`, written BARE on the field: a schema's word and a door's word are the same \
           number at two tiers, and neither is spelled in the other's block",
          roads = road_list(),
          limit = NUMBER_WORDS[0],
          depth = NUMBER_WORDS[1],
        ),
        &election_words(),
      ));
      Ok(())
    });
    skins.push(backend);
    walked
  });
  if skins.is_empty() {
    errors.push(syn::Error::new_spanned(
      &meta.path,
      format!(
        "`{GRAPHQL}` on `{field}` names no backend, and a skin is one backend's description — write \
         `{GRAPHQL}({first})`. Without the word this election still publishes every field it would \
         otherwise publish; what the block sets is what THIS backend calls their defaults",
        first = GraphqlKind::ALL[0].as_str(),
      ),
    ));
  }
  walked
}

/// The word this grammar spells its wire block with.
const GRAPHQL: &str = "graphql";

/// The DURABLE-name word, spelled once.
const SLOT: &str = "slot";

/// The refusal `slot` gets when it is not a written name.
const SLOT_SHAPE: &str = "`slot` is the DURABLE name this family's objects are stored under, in a \
                          string literal — `slot = \"poster_frames\"`. The default is \
                          `snake_case(<declaration name>)`, so the word is only written where that \
                          is not what the store already holds";

/// What an author who wrote `slot` on a retrieving kind is told.
///
/// The GRAIN, which is the same answer their own storage block already gets: a slot on these two
/// kinds is `(field × engine)`, so a word at the head could only name one for the whole declaration
/// — coarser than the storage actually is, and there would be no way to say WHICH pairing the name
/// was for.
fn slot_wrong_grain(kind: NodeKind) -> String {
  format!(
    "`slot` names ONE corpus and {article} {noun} owns one per `(field × engine)` PAIRING, so a \
     word at the head has no way to say which. The durable names here are built from the three \
     parts and joined with `__` — `<declaration>__<field>__<engine>` — which is what keeps two \
     pairings apart where a camel-case type name could not. An ARTIFACT FAMILY holds one object per \
     message and has exactly one corpus, which is why the word is that kind's",
    article = kind.article(),
    noun = kind.noun(),
  )
}

/// Refuse a slot name the durable-name type would refuse, at the literal that wrote it.
///
/// `SlotName::new` already asserts this and its refusal is `E0080` at const-evaluation — INSIDE the
/// expansion, where the author cannot see which of their words caused it. Checked here as well so
/// the caret lands on the string, which is the token that moves.
fn refuse_a_malformed_slot(name: &syn::LitStr, errors: &mut Errors) {
  let spelled = name.value();
  let legal = !spelled.is_empty()
    && !spelled.starts_with(|c: char| c.is_ascii_digit())
    && spelled
      .chars()
      .all(|c| c.is_ascii_alphanumeric() || c == '_');
  if !legal {
    errors.push(syn::Error::new_spanned(
      name,
      format!(
        "`{spelled}` is not a slot name — it must be non-empty ASCII `[A-Za-z0-9_]` and must not \
         start with a digit. The name reaches a STORE, where it is a directory or a table, so the \
         alphabet is the narrow one every backend agrees on"
      ),
    ));
  }
}

/// What an artifact family that wrote `graphql(…)` is told.
///
/// TRUTHFUL rather than *it has not arrived*, which is what this sentence used to say for all three
/// kinds and is false for two of them since the fusion doors landed. A blob's refusal is not a wait:
/// the kind mints no wire type at all, and the whole of its wire presence is written by somebody
/// else's expansion.
const BLOB_MINTS_NO_WIRE: &str = "an artifact family mints no wire type of its own, so there is \
                                  nothing here for a backend word to dress. Its wire presence is \
                                  the RECORD's: `locate(<name> = \"path::to::ThisFamily\")` puts \
                                  the address on that record's object, and the position's `data` \
                                  ask puts the bytes beside it — both written into the `#[Object]` \
                                  block the record owns, because a second one on the same type is \
                                  `E0119`. The block opens here the day this kind mints wire of its \
                                  own";

/// The `graphql(…)` block — one entry per backend this declaration is dressed for.
///
/// # The BARE word is refused, and that is the no-unspent-word law rather than strictness
///
/// `graphql` alone names no backend, and a skin is one backend's impls: there is nothing for a
/// bare word to emit. The refusal names the words on offer, which is the whole of what its author
/// is missing.
fn graphql_word(
  meta: &syn::meta::ParseNestedMeta<'_>,
  graphql: &mut Option<IndexGraphql>,
  errors: &mut Errors,
) -> syn::Result<()> {
  let mut backends: Vec<IndexBackend> = Vec::new();
  let walked = attribute::options(meta, |inner| {
    let Some(kind) = crate::parse::graphql_kind(&inner.path) else {
      errors.push(attribute::unknown(
        &inner,
        &format!(
          "unknown backend in `graphql(…)` — this framework renders through {list}, and a word \
           naming none of them names no skin. The types are backend-NEUTRAL: each word adds one \
           backend's impls over the same Rust family, which is why the block holds WORDS rather \
           than a bare `graphql`",
          list = backend_list(),
        ),
        &GraphqlKind::ALL.map(GraphqlKind::as_str),
      ));
      return Ok(());
    };
    if backends.iter().any(|backend| backend.kind == kind) {
      errors.push(syn::Error::new_spanned(
        &inner.path,
        format!(
          "`{kind}` is declared more than once in `graphql(…)` — one block per backend, because a \
           backend has ONE skin and a second word could only re-describe it",
          kind = kind.as_str(),
        ),
      ));
      attribute::skip_entry(&inner);
      return Ok(());
    }
    let mut backend = IndexBackend::of(kind);
    let walked = index_backend(&inner, &mut backend, errors);
    backends.push(backend);
    walked
  });
  if backends.is_empty() {
    errors.push(syn::Error::new_spanned(
      &meta.path,
      format!(
        "`graphql` names no backend, and a wire face is one backend's impls — write \
         `graphql({first})`. Without the word this declaration still emits its WHOLE Rust surface: \
         the doors, the packages, the evidence and the selector are all there, and what the block \
         adds is a schema over them",
        first = GraphqlKind::ALL[0].as_str(),
      ),
    ));
    return walked;
  }
  *graphql = Some(IndexGraphql { backends });
  walked
}

/// ONE backend's block — the SDL names this skin wears.
///
/// # Why the names are HERE and the Rust ones are at the top level
///
/// The axis law, and it is what makes a second backend possible without a redesign: a name is the
/// SKIN's fact, so it belongs to the block that names the skin. Two backends dressing one
/// declaration each rename their own schema, and neither touches the Rust family the two share —
/// that family is re-based by the top-level `rename`, which is refused in here by name so an author
/// who reaches for the wrong axis is told which one they want.
///
/// # Three faces, and a fourth this position cannot reach
///
/// `options` and `question` are the binding table's picks — the packages a parent absorbs and a
/// client fills; `engine` is the `@oneOf` over the typed engines. The FOURTH — `fused`, the evidence
/// a fused answer carries — is refused here, and [`EVIDENCE_HAS_NO_SKIN`] carries the measurement:
/// the TIER's fused door mounts no query field, and the fused answer that IS published belongs to
/// one ELECTION rather than to this block. Every other emitted type is interior to a package a
/// client already has a name for, so it takes the base and nothing finer.
///
/// # The BASE is `prefix` and the faces are `rename`, which is the vocabulary law
///
/// **`rename` names ONE thing verbatim; `prefix` re-stems a FAMILY.** The base names no type
/// literally — `prefix = "clips"` mints `ClipsFuseOptions` and its siblings, and there is no schema
/// name equal to `clips` anywhere in the emission — so `prefix` is what the position honestly is,
/// and the faces below keep `rename` because each one names a real type outright. `rename` AT THE
/// BASE is refused by name, pointing here.
fn index_backend(
  inner: &syn::meta::ParseNestedMeta<'_>,
  backend: &mut IndexBackend,
  errors: &mut Errors,
) -> syn::Result<()> {
  let scope = format!("`{}(…)`", backend.kind.as_str());
  attribute::options(inner, |option| {
    if option.path.is_ident(PREFIX) {
      match value::literal(&option, SKIN_PREFIX) {
        Ok(base) => {
          crate::wire::refuse_invalid_name(&base.value(), &base, errors);
          set_once(
            &mut backend.prefix,
            base,
            &option.path,
            &format!("`{PREFIX}` is declared more than once in {scope} — one option, one value"),
            errors,
          );
        }
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    // THE CORRECTED WORD, refused by name with the distinction rather than left to the near-miss
    // engine — `rename` and `prefix` are five edits apart, so nothing would be offered.
    if option.path.is_ident(RENAME) {
      errors.push(named(&option, base_is_a_prefix(&scope)));
      return Ok(());
    }
    // THE FOURTH FACE, refused by name with the measurement rather than left to the near-miss line.
    // An author who wrote it is asking for something coherent — and the word is LIVE one grain down
    // — so what they are owed is why THIS position has nothing to move and where the word they
    // probably meant lives.
    if option.path.is_ident(FUSED) {
      errors.push(named(&option, EVIDENCE_HAS_NO_SKIN.to_owned()));
      return Ok(());
    }
    // THE SKIN'S OWN NUMBER, beside the skin's own names: `first` is GraphQL's word for how many,
    // so it is written where the schema is described and never at the Rust tier — Q6a's own
    // sentence, *first 是 graphql 的术语*.
    if option.path.is_ident(FIRST) {
      return number(
        &option,
        &mut backend.first,
        FIRST,
        "a backend block",
        errors,
      );
    }
    for (face, slot) in [
      (OPTIONS, &mut backend.options),
      (QUESTION, &mut backend.question),
      (ENGINE, &mut backend.engine),
    ] {
      if option.path.is_ident(face) {
        // The shared block — the same sentences a record's `connection(…)` and `edge(…)` earn, and
        // the same KIND of word inside them: what these name is a type in GraphQL's own flat
        // namespace, so a Rust keyword is an ordinary word and the fence is the wire's.
        let walked = attribute::sdl_name_block(&option, slot, face, errors);
        if let Some(name) = slot.as_ref() {
          crate::wire::refuse_invalid_name(&name.value(), name, errors);
        }
        return walked;
      }
    }
    // LAW 3's FLOOR, at the head as on an election: the framework's own vocabulary is refused by
    // name with the reason, rather than left to a near-miss line that would offer `rename`.
    if let Some(floor) = floor_word(&option.path) {
      errors.push(named(&option, floor_is_the_frameworks(floor)));
      return Ok(());
    }
    errors.push(attribute::unknown(
      &option,
      &format!(
        "unknown entry in {scope} on a derived index — a backend block names what THIS SKIN calls \
         things: `{PREFIX} = \"…\"` re-stems the whole SDL family, and `{OPTIONS}(…)`, \
         `{QUESTION}(…)` and `{ENGINE}(…)` name one face each with a `{RENAME}` row, and \
         `{FIRST} = N` is the SDL default every query argument this skin publishes carries. The \
         RUST family is re-based by the top-level `{RENAME}`, outside this block — a name is the \
         skin's fact, and the bones are one set however many skins dress them; the Rust-vocabulary \
         numbers beside it are `{limit}` and `{depth}` at the head",
        limit = NUMBER_WORDS[0],
        depth = NUMBER_WORDS[1],
      ),
      &[PREFIX, OPTIONS, QUESTION, ENGINE, FIRST],
    ));
    Ok(())
  })
}

/// The rename word, spelled once for both axes' readers.
const RENAME: &str = "rename";

/// The word an SDL family's STEM is written under, spelled once.
///
/// Distinct from [`RENAME`] and the distinction is the vocabulary law: a `rename` row names ONE
/// thing verbatim, and this one re-stems a family whose members it never spells.
const PREFIX: &str = "prefix";

/// What an author who wrote `rename` at the SKIN BASE is told.
///
/// # By NAME, because the near-miss engine cannot reach it
///
/// `crate::suggest`'s cutoff is at most two edits AND half the written word surviving them;
/// `rename` → `prefix` is five edits over six characters, so an unknown-entry refusal would offer
/// nothing and the author would be left reading a vocabulary list for a word they nearly had. The
/// did-you-mean clause is therefore written into this sentence, in the family's own spelling.
///
/// The sentence carries the LAW rather than the substitution alone, because the belief being
/// corrected is about the grammar: an author told only *write `prefix`* would write
/// `options(prefix = "…")` next.
fn base_is_a_prefix(scope: &str) -> String {
  format!(
    "`{RENAME}` names ONE thing verbatim and this position re-stems a FAMILY — `{PREFIX} = \
     \"clips\"` mints `ClipsFuseOptions`, `ClipsFusedEvidence` and their siblings, and no emitted \
     type is called `clips` at all. So the base takes `{PREFIX}` and the FACES take `{RENAME}`, \
     each of those naming one type outright: `{OPTIONS}({RENAME} = \"…\")`, \
     `{QUESTION}({RENAME} = \"…\")` and `{ENGINE}({RENAME} = \"…\")` in {scope}. The RUST family is \
     re-based by the top-level `{RENAME}`, outside this block{suggestion}",
    suggestion = crate::suggest::meant(PREFIX),
  )
}

/// What an artifact family that wrote a top-level `rename` is told.
///
/// TRUTHFUL, and the measurement is pinned: this kind lands NO type in the declaring scope. Its
/// engines are at the head, so it has no `(field × engine)` slot and no slot marker; it elects
/// nothing, so it has no election marker; and it does not retrieve, so it mints no package, no
/// vocabulary and no evidence. A `rename` here would be a word with nothing to move, which is the
/// no-unspent-word law's own case.
///
/// The word it DOES have is `slot = "…"`, and the sentence names it — an author reaching for a name
/// on this kind almost always wants the durable one.
const BLOB_MINTS_NO_TYPE: &str = "an artifact family lands no type in your scope for a `rename` to \
                                  move — its engines are at the HEAD, so it has no \
                                  `(field × engine)` slot and no slot marker; it elects nothing, so \
                                  it has no election marker; and it does not retrieve, so it mints \
                                  no package, no vocabulary and no evidence. The name this kind \
                                  does have is the DURABLE one — `slot = \"…\"`, the directory its \
                                  objects live under. `rename` opens here the day the kind mints a \
                                  type of its own";

/// The faces a backend block may name, as an author writes them — and the fourth, which it may not.
const FUSED: &str = "fused";
const OPTIONS: &str = "options";
const QUESTION: &str = "question";
const ENGINE: &str = "engine";

/// `engines(rename = "…")` — the ELECTION block's own type seat over `<Index><Field>Engines`, the
/// per-leg product a fused read states one floor in.
///
/// Beside [`ENGINE`] rather than sharing it, on the split every neighbouring pair in this file
/// takes: the singular names the `@oneOf` SELECTOR at the head and the plural names the PRODUCT on
/// an election, so one const read by both would be a name whose meaning depended on where it was
/// read. [`QUESTION`] IS shared across the two positions, and the difference is the test: that word
/// means *name the question type* at both grains, and only which type it reaches changes. There is
/// no third reading: the sugar inside `knn(searchable(…))` names a TOWER, so it is spelled
/// [`TOWER`], and a key that borrowed this one would have made the word mean two things.
const ENGINES: &str = "engines";

/// `sighting(rename = "…")` — the ELECTION block's seat over `<Index><Field>Sighting`, the wire
/// UNION a fused answer's evidence list holds.
///
/// The ANSWER side's first seat, beside the two request-side ones, and it is a seat rather than a
/// floor entry for the reason those two are: what a client cannot predict is the TYPE, because the
/// union is minted per election and per declaration. The row word `evidence` that holds a list of
/// them is the floor's, and no word here moves it.
///
/// SINGULAR because the type is one: the union is a SUM over the legs, one arm each, and the arms
/// are derived from the legs' own words rather than seated here — see [`ElectionBackend::sighting`],
/// where the arms' absence is the measurement.
const SIGHTING: &str = "sighting";

/// `fused_key_match(rename = "…")` — the ELECTION block's seat over `<Index><Field>FusedKeyMatch`,
/// the ROW a fused read answers with.
///
/// [`SIGHTING`]'s twin over the other half of one answer, and a seat of its own on the road words'
/// precedent: two types in one namespace need two words or none.
const FUSED_KEY_MATCH: &str = "fused_key_match";

/// **THE FRAMEWORK'S OWN VOCABULARY** — the words a request writes and an answer wears, which no
/// declaration moves at any position.
///
/// # Refused BY NAME, because the author's idea is coherent and the answer is a law
///
/// The 2026-08-16 ruling's third law: the argument words (`question`, `engine`, `engines`, `first`,
/// `depth`, `key`), the answer rows (`score`, `rank`, `evidence`, `streams`, `ordinal`,
/// `contribution`, `node`) and the question's `coordinates` arm are the UNIFORM FLOOR. A client
/// holds ONE vocabulary against every declaration this framework generates — Relay's own precedent,
/// and the documented floor the magic-string law reserves for exactly this shape — so a
/// per-declaration rename would buy one schema's taste at the price of every client's.
///
/// # `entity` LEFT the list on 2026-08-19, and the vacancy is the point
///
/// The 2026-08-18 alignment gave the Match family ONE row word at both tiers — `node`, the address
/// at tier A and the entity at tier B — so `entity` stopped being emitted anywhere; it was kept here
/// for one round as a RESERVED spelling. The R7 retirement struck it, and the behaviour change is
/// stated rather than incidental: `entity(rename = "…")` now earns the UNKNOWN-entry sentence (with
/// this block's own seats listed and a `did you mean` over them) where it used to earn the floor's.
///
/// The reason is what a floor sentence is FOR. It answers an author whose idea is coherent — *I want
/// the answer row called something else* — by naming the vocabulary they are up against. An author
/// writing `entity` today is not up against a vocabulary; they are naming a word this grammar does
/// not have, and the unknown-entry sentence, which lists the seats that DO exist, is the more useful
/// answer. Reserving a spelling forever also costs: every retired word held here is a word the floor
/// sentence has to keep explaining, and the sentence is read by everyone who trips over `score`.
///
/// # What is IN the list is the subset no seat and no better sentence already covers
///
/// `question`, `engines` and `first` are LIVE words in an election block, and `question`, `engine`
/// and `first` at the head — so those reach their own seat before this list is consulted, and what
/// they name is the TYPE behind an argument rather than the argument itself.
///
/// `depth` is left out for a different reason: inside a skin block it is a misplaced BONES number,
/// and the unknown-entry sentence that says where the bones tier is answers the mistake actually
/// being made.
///
/// `evidence` is left out for a third: it is the one floor row that is ALSO a Rust mint with a seat
/// on the other axis — `rename(evidence = "…")` — and the head block already answers it by naming
/// that axis. A floor sentence there would replace a specific truth with a general one.
///
/// # `streams` is in this list AND is a BONES number, and the two never meet
///
/// [`STREAMS`] is `streams = N`, the guard over how many query vectors one request may ask a `_with`
/// road with. This entry is the ANSWER ROW a set hit carries. They share a string because they are
/// one concept — `depth`'s own shape, a bones word and a wire surface — and they cannot collide,
/// because the readers sit at positions that do not overlap: [`numbers_word`] runs at the head and
/// on an election, OUTSIDE every `graphql(…)` block, and [`floor_word`] runs only INSIDE one. A
/// declaration writing `streams = 8` at its head reaches the guard; one writing
/// `graphql(async_graphql(streams(rename = "…")))` reaches this refusal.
///
/// The MEASUREMENT behind the law: every one of these is a string literal in this workspace's own
/// hand-written source — `ingraph::graphql`'s `Match`/`FoldedMatch` rows, the `#[graphql(name = …)]`
/// on each emitted argument, async-graphql's own Relay `node` — and none of them reads a model
/// field. There is no path from a declaration to any of them, which is what makes this refusal a
/// statement of the shape rather than a policy that has to be enforced twice.
const FLOOR_WORDS: [&str; 8] = [
  "score",
  "rank",
  "streams",
  "ordinal",
  "contribution",
  "node",
  "coordinates",
  "key",
];

/// The floor word `path` names, if it names one.
fn floor_word(path: &syn::Path) -> Option<&'static str> {
  FLOOR_WORDS.into_iter().find(|word| path.is_ident(*word))
}

/// What an author who reached for a rename over the framework's own vocabulary is told.
///
/// The sentence names the WHOLE floor rather than the one word written, because the belief being
/// corrected is about the vocabulary and not about that entry: an author who tried to move `score`
/// will try `ordinal` next.
fn floor_is_the_frameworks(word: &'static str) -> String {
  format!(
    "`{word}` is the FRAMEWORK's own word and no declaration moves it. The request's arguments \
     (`question`, `engine`, `engines`, `first`, `depth`, `key`), an answer's rows (`score`, `rank`, \
     `evidence`, `streams`, `ordinal`, `contribution`, `node`) and the question's `coordinates` arm \
     are ONE vocabulary across every declaration this \
     framework generates, so a client written against one schema reads the next — which is the \
     whole of what a uniform floor buys, and Relay's own precedent for buying it. What IS nameable \
     here is the TYPE behind an argument or an answer, because those are minted per declaration and \
     per election and no client could predict them: `{QUESTION}(rename = \"…\")`, \
     `{ENGINES}(rename = \"…\")`, `{SIGHTING}(rename = \"…\")` and \
     `{FUSED_KEY_MATCH}(rename = \"…\")` on an election, `{OPTIONS}(rename = \"…\")`, \
     `{QUESTION}(rename = \"…\")` and `{ENGINE}(rename = \"…\")` at the head. The RUST type \
     behind an answer row moves with the top-level `rename(…)`, which is the other axis entirely"
  )
}

/// Every ROAD word, as a refusal reads them back — the closed five, in [`Field::ALL`]'s order.
fn road_list() -> String {
  Field::ALL
    .iter()
    .map(|road| format!("`{}(rename = \"…\")`", road.as_str()))
    .collect::<Vec<_>>()
    .join(", ")
}

/// EVERY word an election's backend block takes, as the near-miss line measures a typo against them.
///
/// Built from [`Field::ALL`] rather than written out, so a road added to the vocabulary is a road
/// the suggestion engine offers without a second edit — the drift this crate's near-miss round put
/// the list in [`attribute::unknown`]'s signature to prevent.
fn election_words() -> Vec<&'static str> {
  [FIRST, QUESTION, ENGINES, SIGHTING, FUSED_KEY_MATCH]
    .into_iter()
    .chain(Field::ALL.map(Field::as_str))
    .collect()
}

/// What an author who wrote `fused(rename = "…")` at the HEAD is told.
///
/// TRUTHFUL and not a wait-with-no-reason, and the sentence was RE-MEASURED once the fanned road
/// grew an answer face: it used to say *the whole answer side of a fused door is Rust-only*, and
/// that is no longer so. What is still so is narrower and is what the word actually runs into.
///
/// This position names `<Index>FusedEvidence<S₁, …>`, the TIER's fused-door evidence, and the tier's
/// fused pair mounts NO query field — so nothing on its answer side is on a schema for a word to
/// move. One grain down a fused answer IS published, and what carries it is a MINTED WIRE UNION
/// (`<Index><Field>Sighting`, one arm per leg) rather than the evidence enum, which keeps its
/// Rust-only name there too. Those types are per-ELECTION, so a head word over them would be
/// `engine(rename)`'s refused shape — one word over a set.
///
/// The sentence names the ELECTION's own `fused(rename = "…")` because that word is LIVE and is very
/// often what an author at this position wanted: it names the fused QUERY FIELD of one election.
const EVIDENCE_HAS_NO_SKIN: &str = "the evidence a fused door answers with has no schema name to \
                                    move — `<Index>FusedEvidence<S>` is GENERIC in the score, \
                                    because a door is generic over the engine it asked and two \
                                    routes' scores are two currencies, and the tier's fused door \
                                    mounts no query field at all, so nothing on its answer side \
                                    reaches a schema. A FANNED election does publish its fused \
                                    answer — `<Index><Field>Sighting` and its arms — but those are \
                                    minted wire types at the ELECTION's grain, and this block names \
                                    one type outright. What this block CAN name is the request \
                                    side — `options(rename = \"…\")`, `question(rename = \"…\")` \
                                    and `engine(rename = \"…\")`; the FUSED QUERY FIELD of one \
                                    election is named by `fused(rename = \"…\")` in that field's \
                                    own backend block. The word opens here the day the tier's fused \
                                    door mounts a road of its own";

/// The refusal a backend block's `prefix` gets when it is not a written word.
///
/// A STRING and never an ident, on the 2026-08-13 ruling: the word names a stem in GraphQL's own
/// namespace and nothing in Rust, so `type` and `where` are ordinary here. The one fence is the
/// wire's Name grammar, applied at the literal that wrote it.
const SKIN_PREFIX: &str = "a backend block's `prefix` is the STEM its SDL family is built on, in a \
                           string literal — `prefix = \"shotSearch\"` mints \
                           `ShotSearchFuseOptions` and its siblings. It moves no Rust name: the \
                           bones are re-based by the top-level `rename`";

/// The TOP-LEVEL `rename`, in whichever of its two forms it was written.
///
/// # The forms are exclusive, and the grammar is what makes them so
///
/// The `extension` word's precedent: a single fact is a key-value and a structured one is a block,
/// so `rename = "…"` and `rename(…)` cannot both be written at one occurrence, and a SECOND
/// occurrence is refused as a repeat whichever form each took. That is the whole of *value XOR
/// block*, and it costs one refusal rather than a second reader.
fn rename_word(
  meta: &syn::meta::ParseNestedMeta<'_>,
  rename: &mut Option<IndexRename>,
  kind: NodeKind,
  errors: &mut Errors,
) -> syn::Result<()> {
  if attribute::has_value(meta) {
    match value::parse_literal::<syn::Ident>(meta, attribute::TYPE_NAME) {
      Ok(base) => *rename = Some(IndexRename::Base(base)),
      Err(e) => errors.push(e),
    }
    return Ok(());
  }
  if !attribute::has_block(meta) || attribute::empty_group(meta) {
    errors.push(named(meta, rename_says_nothing(kind)));
    return Ok(());
  }
  let mut pieces: Vec<(RenamePiece, syn::Ident)> = Vec::new();
  // WHETHER THE BLOCK WAS EMPTY, which is not the same question as whether it named a mint: a block
  // whose every entry was refused has earned one sentence apiece already, and *says nothing on its
  // own* on top of them would be a cascade from a typo.
  let mut written = false;
  let walked = attribute::options(meta, |option| {
    written = true;
    let Some(piece) = RenamePiece::of(&option.path) else {
      errors.push(attribute::unknown(
        &option,
        &rename_vocabulary(kind),
        &RenamePiece::ALL.map(RenamePiece::as_str),
      ));
      return Ok(());
    };
    if pieces.iter().any(|(named, _)| *named == piece) {
      errors.push(syn::Error::new_spanned(
        &option.path,
        format!(
          "`{piece}` is declared more than once in `rename(…)` — one mint, one name",
          piece = piece.as_str(),
        ),
      ));
      attribute::skip_entry(&option);
      return Ok(());
    }
    match value::parse_literal::<syn::Ident>(&option, attribute::TYPE_NAME) {
      Ok(spelled) => pieces.push((piece, spelled)),
      Err(e) => errors.push(e),
    }
    Ok(())
  });
  if pieces.is_empty() {
    if !written {
      errors.push(syn::Error::new_spanned(
        &meta.path,
        rename_says_nothing(kind),
      ));
    }
    return walked;
  }
  *rename = Some(IndexRename::Pieces(pieces));
  walked
}

/// The refusal a `rename` that named nothing gets — the bare word, the empty block, and a block
/// whose every entry was refused.
fn rename_says_nothing(kind: NodeKind) -> String {
  format!(
    "`rename` says nothing on its own — write `rename = \"NewBase\"` to re-base every type {article} \
     {noun} mints, or `rename(<piece> = \"…\")` to name individual ones. It moves RUST names only: \
     what a schema calls these types is `graphql(<backend>(prefix = \"…\"))`, and this \
     declaration's own struct name is yours and is never touched",
    article = kind.article(),
    noun = kind.noun(),
  )
}

/// The refusal an unknown `rename(…)` entry gets, with the closed vocabulary spelled out.
fn rename_vocabulary(kind: NodeKind) -> String {
  format!(
    "unknown mint in `rename(…)` — the vocabulary is CLOSED and holds the types {article} {noun} \
     has AT MOST ONE of: {list}. The PER-FIELD and PER-SLOT mints — a slot's own options and \
     question, a leg's options, a fold vocabulary, an election marker, a slot marker — are named by \
     no word here, because *which one* would need a field and an engine beside it; `rename = \
     \"NewBase\"` re-bases all of them at once",
    article = kind.article(),
    noun = kind.noun(),
    list = RenamePiece::ALL
      .iter()
      .map(|piece| format!("`{}`", piece.as_str()))
      .collect::<Vec<_>>()
      .join(", "),
  )
}

/// EVERY NAMED MINT, checked against what this declaration actually mints.
///
/// A word names an INDIVIDUAL type, so it only means something where the declaration has one of
/// that type. Read after the model is built, because *does this declaration mint a multi-route
/// package* is a fact about its elections and its engines — the same reason the emitted-name audits
/// beside this one run here.
///
/// The refusal names the type and says why this declaration has none, which is the half an author
/// needs: the word is right and the declaration is the wrong shape for it.
fn named_mints(model: &IndexModel, errors: &mut Errors) {
  let Some(IndexRename::Pieces(pieces)) = &model.rename else {
    return;
  };
  let tier = model.tier();
  for (piece, spelled) in pieces {
    if let Some(why) = tier.unmintable(*piece) {
      errors.push(syn::Error::new_spanned(
        spelled,
        format!(
          "`{piece}` names {what}, and {article} {noun} like this one mints none: {why}",
          piece = piece.as_str(),
          what = piece.what(),
          article = model.kind.article(),
          noun = model.kind.noun(),
        ),
      ));
    }
  }
}

/// Every backend word, as a refusal reads them back.
fn backend_list() -> String {
  GraphqlKind::ALL
    .iter()
    .map(|kind| format!("`{}`", kind.as_str()))
    .collect::<Vec<_>>()
    .join(", ")
}

/// What an author who wrote `embedding(<field>)` is told — the marker that replaced it, named for
/// THIS declaration's kind.
///
/// One sentence per kind rather than one shared one, because the useful half is the successor and
/// the successor differs: a `vector` takes `knn`, a `fulltext` takes `searchable`, and a `blob`
/// elects nothing at all. The old word's own wrong-kind refusal folds in here — it used to tell a
/// full-text declaration that the word was the vector kind's, which is no longer the fact worth
/// having.
fn retired_head_word(kind: NodeKind) -> String {
  let successor = match kind {
    NodeKind::Vector => {
      "an embedding index elects a column by writing `#[ingraph(knn)]` on the field itself, and how \
       that column's answer is DECIDED rides the marker as `#[ingraph(knn(semantics(fold = \
       \"…\")))]`"
    }
    NodeKind::Fulltext => {
      "a full-text index elects a field by writing `#[ingraph(searchable)]` on it — and `knn` was \
       never this kind's word either: coordinates are the `vector` kind's"
    }
    _ => {
      "an artifact family elects nothing under any spelling — it answers an address rather than a \
       ranking, so no field of one is ever run over"
    }
  };
  format!(
    "`embedding(<field>)` has retired — an election is now a MARKER ON THE FIELD it elects: \
     {successor}. The head word named a field from outside it, so every refusal about an election \
     landed on the head rather than on the field; the marker's land on the field's own tokens, and \
     a mis-typed election is reported at the TYPE its author wrote"
  )
}

/// ONE field's ELECTION as its own markers declared it.
///
/// It is `None`-shaped by default, and that default is the payload case: an unmarked field is
/// stored, hydrated, and reached by no query. The whole of the flip is that this is read off the
/// FIELD — so the marker's path is a token of the field's own attribute, and the type it qualifies
/// is the next token along.
#[derive(Default)]
pub(crate) struct Role {
  /// Whether the field wore this kind's election marker.
  ///
  /// A BOOL and not the marker's path: the duplicate refusal lands on the SECOND marker, which is in
  /// hand where it is written, so a stored first one would be a token nothing spends.
  pub(crate) elected: bool,
  /// The ENGINE BLOCKS beside the marker, in written order — where this field is stored.
  ///
  /// Collected during the walk and judged after it, because a marker list has no order: `#[ingraph(
  /// lance, knn)]` writes the engine first, so *an engine on a field that elects nothing* is not a
  /// question the walk can answer while it is still walking.
  pub(crate) engines: Vec<Engine>,
  /// The ELECTION LABEL this field wrote — `embedding` or `list(embedding)` — and [`None`] where it
  /// wrote none.
  ///
  /// Read in the same walk as the marker beside it, because they are one attribute: the label says
  /// how many embeddings the field holds and the marker says the index runs over them, and an author
  /// writes both in one list. Whether a label was REQUIRED is [`elect`]'s question, since only there
  /// is it known whether this field is elected at all.
  pub(crate) label: Option<ElectionLabel>,
  /// `semantics(fold = "…")`'s type, read inside `knn(…)`, and [`None`] where the election declared
  /// none and takes the shipped fold.
  pub(crate) fold: Option<Fold>,
  /// `knn(searchable(tower = "…"))`'s TOWER, and [`None`] where the election named no road.
  ///
  /// A TYPE carried verbatim: nothing here resolves it, and every claim about it is rustc's at the
  /// binding the forged recipe writes.
  pub(crate) tower_road: Option<syn::Type>,
  /// The `fanout` marker's own path, and [`None`] where the word was absent.
  ///
  /// The PATH rather than a bool, unlike [`elected`](Self::elected) above, because the refusal this
  /// one carries lands on the marker AFTER the walk: whether there is anything to fan is a fact
  /// about how many engines the field named, which the last entry may still change.
  pub(crate) fanout: Option<syn::Path>,
  /// THE THREE BONES NUMBERS this field wrote — `limit`, `depth` and `ceiling` at the ELECTION
  /// tier, empty where it wrote none.
  pub(crate) numbers: Numbers,
  /// `graphql(<backend>(first = N))` ON THIS FIELD — the SKIN tier, one entry per backend named.
  pub(crate) skins: Vec<ElectionBackend>,
}

/// The refusal a RETRIEVING declaration that wrote no `dedup(…)` gets.
///
/// # Mandatory, on both retrieving kinds and on every election
///
/// The word picks a MECHANISM, and a mechanism is a BOUNDS choice on this node's key: `hash` asks
/// the key for `Hash + Eq` and `eq` asks it for `PartialEq` alone. A default would make that choice
/// silently, so a key that cannot hash would meet an `E0277` inside an expansion rather than a
/// sentence naming the word it never wrote.
///
/// It is the same word on both roads — the single-vector one, where it picks the membership that
/// collapses one engine stream, and the set one, where it also picks the accumulator the fold runs
/// through. Making it mandatory only where the accumulator lives would crack one word into two laws.
const DEDUP_IS_MANDATORY: &str = "this declaration retrieves and does not say HOW it tells two of \
                                  its keys apart — write `dedup(hash)` or `dedup(eq)` beside \
                                  `upstream(…)`. The word is a BOUND on the key this index carries: \
                                  `dedup(hash)` compares keys by hashing them — key: `Hash + Eq` — \
                                  and `dedup(eq)` walks a seen-list comparing every field — key: \
                                  `PartialEq` alone, which is the escape for a key that cannot \
                                  hash. There is no default, because a bounds choice a declaration \
                                  did not make is one its author meets as an error inside an \
                                  expansion";

/// What an author who reached for the retired question road is told, and WHERE the road went.
///
/// `ask` named a chain of hops that turned a question into this column's coordinates, and it was
/// retired on 2026-08-19 with the rest of the erasure road. The sentence names the successor because
/// the author's idea is not the mistake: they want a question road, and there is one — it is a
/// TOWER's, and it is better at the exact thing this word was worst at.
///
/// The MEASUREMENT behind that claim, and it is why the retirement is a refusal rather than a
/// silence: a chain of N hops has N error types and one `Result` has one, so `ask` ERASED every
/// hop's refusal into a boxed `AskRefusal` carrying the hop's name as a string. A road could say
/// WHICH hop said no and never in what TYPE. `#[ingraph::tower]` mints `<Tower>Error` instead — one
/// arm per step, each carrying that step's own error — so the same refusal is matchable.
///
/// One body, two openers: an author who wrote `via` never had a word at all, and telling them `via`
/// has retired would be false about the grammar they are standing in.
fn road_word_retired(word: &str) -> String {
  let opener = if word == "via" {
    "`via` is not the word, and `ask` is no longer one either"
  } else {
    "`ask` has retired"
  };
  format!(
    "{opener} — a question road is a TOWER's now. Declare the chain with `#[ingraph::tower]`, which \
     mints a `walk` over its steps and a `<Tower>Error` naming which step refused WITH THAT STEP'S \
     OWN error type, then reach a column through it: bind the tower in a `#[ingraph::search]` \
     recipe's `tower(<arm>(type = \"…\"))` arm, or walk it by hand and hand the coordinates to \
     `retrieve_keys_by_<field>`. The SHORT spelling of that first road is written here, one word \
     over: `knn(searchable(tower = \"path::to::Tower\"))` forges the one-member recipe for you, \
     seat and arm and wire field included. What this word did was ERASE every hop's refusal into \
     one boxed name, so a road could say which hop refused and never in what type — which is the \
     whole of what it was replaced for. The RAW road is untouched either way: a caller holding \
     coordinates always called `retrieve_keys_by_<field>` and still does"
  )
}

/// One entry inside `knn(…)`: the `semantics` block, and the two RETIRED road words beside it.
///
/// Both retired words are caught BY NAME rather than left to the unknown-entry sentence, because
/// what an author who wrote either one wants exists and is one declaration away. `attribute::unknown`
/// answers *this position does not take that word*; these two answer *the road moved, and here it
/// is*.
fn road_word(inner: &syn::meta::ParseNestedMeta<'_>, errors: &mut Errors) {
  for retired in ["ask", "via"] {
    if inner.path.is_ident(retired) {
      errors.push(named(inner, road_word_retired(retired)));
      attribute::skip_entry(inner);
      return;
    }
  }

  errors.push(attribute::unknown(
    inner,
    "unknown entry in `knn(…)` — the marker's own block takes `semantics(<kind> = \"…\")`, which is \
     how this election's answer is DECIDED, and `searchable(tower = \"…\")`, which is the TOWER a \
     question is walked through to reach this column. WHICH field the election is over is not \
     written in either: it is the field this marker is on",
    // The sentence and the near-miss vocabulary name ONE set, which is the property that makes a
    // did-you-mean readable: a word the suggestion line offers and the sentence never mentions
    // reads as a typo the position does not take.
    &[SEMANTICS, SEARCHABLE],
  ));
}

/// The `searchable(…)` BLOCK, read inside `knn(…)` — this election's TOWER ROAD.
///
/// It reads ONE word and refuses everything else by name, for the reason the whole sugar exists: the
/// expansion is a `#[ingraph::search]` recipe written for the author, and every knob that recipe has
/// is a knob a hand-written one already spells. A second word here would be this grammar growing a
/// second spelling of a word the recipe owns.
fn searchable_word(
  inner: &syn::meta::ParseNestedMeta<'_>,
  road: &mut Option<syn::Type>,
  errors: &mut Errors,
) {
  if !attribute::has_block(inner) || attribute::empty_group(inner) {
    errors.push(named(inner, SEARCHABLE_NAMES_A_TOWER.to_owned()));
    return;
  }
  let walked = inner.parse_nested_meta(|word| {
    if word.path.is_ident(TOWER) {
      match value::parse_literal::<syn::Type>(&word, TOWER_IS_A_QUOTED_TYPE) {
        Ok(tower) => set_once(road, tower, &word.path, ONE_TOWER_ROAD, errors),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    errors.push(attribute::unknown(
      &word,
      UNKNOWN_SEARCHABLE_ENTRY,
      &[TOWER],
    ));
    Ok(())
  });
  if let Err(e) = walked {
    errors.push(e);
  }
}

/// WHICH fields this declaration is over, read off the markers its fields wore.
///
/// One answer holding both kinds' elections, because the LAW is one law: presence elects, absence is
/// payload, and a declaration that marks nothing is refused by name. Two functions would be two
/// places for that law to drift.
struct Elections {
  /// The `knn`-marked fields, in declared order, each read into the emitter's model.
  embeddings: Vec<Elected>,
  /// The LABELLED fields no marker elects, in declared order — accepted as forward declarations and
  /// audited exactly as an election's label is. See [`IndexModel::labelled`].
  labelled: Vec<Labelled>,
  /// The `searchable`-marked fields, in declared order.
  searchable: Vec<syn::Ident>,
  /// WHERE each of those is written — one entry per election, in the SAME order, built in the same
  /// pass so the two cannot come apart.
  engines: Vec<FieldEngines>,
  /// WHAT NUMBERS each of those wrote — one entry per election that wrote any, in the same order
  /// and built in the same pass, for the engine list's reason.
  ///
  /// A field that wrote NOTHING gets no entry, so the list is exactly what a declaration said and
  /// a chain that finds nothing falls to the container rather than to an empty row.
  numbers: Vec<FieldNumbers>,
}

/// Each field's marker matched against the field it is written on — the step that turns the markers
/// into elections, and the one that refuses a declaration which marked nothing.
///
/// It runs on every kind and answers EMPTY for `blob`: both markers are refused BY NAME there in
/// [`markers`], so there is nothing left to elect and nothing to demand.
///
/// # The two refusals, each at the truest span it has
///
/// 1. **A `knn` field that is not `Embedding<E, N>`** — at the FIELD'S TYPE, which is the token that
///    is actually wrong. The head word could not do this: it named the field from outside, so the
///    refusal landed on the head's own ident and left the reader to find the type themselves.
/// 2. **No marker at all** — at the declaration's own name, since there is no token for it to land
///    on. This is the mandatory posture's tooth, and it fires even where exactly one field could
///    possibly be the subject: see [`Elected`] for why no fallback is offered there.
///
/// The third — the same marker twice on one field — is [`markers`]', refused where the repeated
/// marker arrives, in the ordinary duplicate family every field marker is held to.
///
/// EVERY field is walked even after one of them is refused, so a declaration with two wrong markers
/// hears about both: one compile, the whole declaration's problems, which is this pass's rule
/// throughout.
fn elect(
  columns: &[Column],
  roles: &[Role],
  kind: NodeKind,
  index: &syn::Ident,
  errors: &mut Errors,
) -> Elections {
  let mut elections = Elections {
    embeddings: Vec::new(),
    labelled: Vec::new(),
    searchable: Vec::new(),
    engines: Vec::new(),
    numbers: Vec::new(),
  };
  let Some(marker) = kind.election() else {
    return elections;
  };
  // WHERE this election is written, minted at each site the election itself is recorded — so the two
  // lists are one walk's two answers and cannot fall out of step.
  let stored = |field: &syn::Ident, role: &Role, elections: &mut Elections| {
    // THE SOLE-DEFAULT'S COMPILE-TIME HALF: an election that wrote NO engine block still owns a
    // corpus, and the corpus is labelled with the FIELD's own name.
    //
    // A leg has two facts — a LABEL, which names the corpus, and a RESOURCE, which says where it
    // lives — and only the second is a deployment's. So saying nothing means *this field has a
    // corpus of its own and the deployment says where*: the slot, the marker and the road are all
    // emitted here, and the binding is resolved at launch against the declared catalog
    // (`ResourceCatalog::sole`). Leaving the list empty instead would have made the minimal form
    // `#[ingraph(searchable)]` mint no corpus at all, so a declaration would grow storage the day
    // somebody wrote a word — which is the label deciding a structural fact.
    //
    // The FIELD NAME and not the declaration's, ruled: two elections of one declaration are two
    // corpora, so a shared label would collapse them into one — the exact BM25 collision the slot
    // grain exists to keep out.
    let engines = if role.engines.is_empty() {
      vec![Engine::bare(field.clone())]
    } else {
      role.engines.clone()
    };
    elections.engines.push(FieldEngines {
      field: field.clone(),
      engines,
      fanout: role.fanout.is_some(),
    });
    // THE NUMBERS RIDE THE SAME WALK, and a field that wrote none contributes no row: presence is
    // the enablement here as it is everywhere else in this grammar, so the resolution chain reads
    // an absence rather than a default somebody minted.
    if !role.numbers.is_empty() || !role.skins.is_empty() {
      elections.numbers.push(FieldNumbers {
        field: field.clone(),
        numbers: role.numbers,
        skins: role.skins.clone(),
      });
    }
  };
  for (column, role) in columns.iter().zip(roles) {
    if !role.elected {
      continue;
    }
    if kind == NodeKind::Fulltext {
      elections.searchable.push(column.name.clone());
      stored(&column.name, role, &mut elections);
      continue;
    }
    let name = &column.name;
    let ty = &column.ty;
    // THE LABEL IS MANDATORY on an elected field, for the record label's own reason one family over:
    // a field that participates states its kind, and *how many embeddings this column holds* is a
    // structural fact the expansion acts on. There is no default — a guessed multiplicity is a face
    // emitted or withheld on a coin toss — and there is no type-read either: whether the field even
    // HOLDS coordinates is rustc's, answered through `EmbeddingMarker` at the projections this model
    // is spent on.
    let Some(label) = role.label else {
      errors.push(syn::Error::new_spanned(
        name,
        format!(
          "`{name}` is marked `{marker}` and carries no LABEL — an elected field states how many \
           embeddings it holds, as `#[ingraph(embedding, {marker})]` for one and \
           `#[ingraph(list(embedding), {marker})]` for a set of them. The label is what decides \
           which faces this declaration emits and which doors it grows, and a macro cannot resolve \
           a type to find out; there is no default, because a guessed multiplicity is a door \
           emitted or withheld on a coin toss"
        ),
      ));
      continue;
    };
    // THE LABEL-CONDITIONED REFUSALS: a single embedding has one best per query vector, so there is
    // nothing to fold and no `m` to bound, and the `_with` doors that would spend either word are
    // not emitted for it. Refused rather than ignored — a word nobody reads is a rule its author
    // believes they declared.
    //
    // NEITHER `continue`s, which is `dedup`'s own law at this grain: dropping the election here
    // would leave a one-election declaration electing nothing, and the *does not say WHICH of its
    // fields it indexes* refusal would fire beside this one — one wrong word becoming a cascade of
    // unrelated sentences. The election is carried, the error is sealed before any emission reads
    // it, and what an author sees is the one word they have to fix.
    //
    // The fold arm DID `continue` until 2026-08-18, and what that cost was measured rather than
    // argued: `tests/refusals/a_fold_is_a_sets_word.rs` earned TWO sentences under it and earns one
    // now. Nothing reached it before that fixture — the folds the other fixtures write are near
    // misses refused in `shipped_fold`, so `role.fold` never became `Some` — which is why the twin
    // one word below was written to this law and this one was not.
    if role.fold.is_some() && !label.is_set() {
      errors.push(syn::Error::new_spanned(name, fold_is_a_sets_word(name)));
    }
    if role.numbers.streams.is_some() && !label.is_set() {
      errors.push(syn::Error::new_spanned(name, streams_is_a_sets_word(name)));
    }
    let mut election = Elected::new(name.clone(), label, ty.clone(), role.fold.clone());
    if let Some(tower) = role.tower_road.clone() {
      election = election.asked_through(tower);
    }
    elections.embeddings.push(election);
    stored(name, role, &mut elections);
  }
  // A LABEL ON A FIELD NO MARKER ELECTS is ACCEPTED and carried. The label states a structural fact
  // about the field, and the party that spends it is not only the query side: a storage layer that
  // lays a set out differently from a single vector reads the same fact about a field nothing
  // queries. So it is a declaration made EARLY rather than a word nobody reads — and it is still
  // AUDITED, which is what keeps accepted from meaning unexamined.
  for (column, role) in columns.iter().zip(roles) {
    if let Some(label) = role.label
      && !role.elected
    {
      elections
        .labelled
        .push(Labelled::new(column.name.clone(), label, column.ty.clone()));
    }
  }
  // A declaration with NO FIELDS AT ALL has already been told it indexes nothing, and this would
  // send its author to mark one of the fields that is the thing it does not have.
  if elections.embeddings.is_empty() && elections.searchable.is_empty() && !columns.is_empty() {
    errors.push(syn::Error::new_spanned(
      index,
      format!(
        "`{index}` does not say WHICH of its fields it indexes — {noun} elects at least one, by \
         writing `#[ingraph({marker})]` on the field, and may mark several to elect several. \
         Mandatory even where exactly one field could possibly be the subject: a field's TYPE states \
         its shape, and *this is what the index is over* is a ROLE, which is declared rather than \
         inferred. What no marker elects is ordinary payload — stored, hydrated, and reached by no \
         query. `{index}` declares {fields}",
        noun = match kind {
          NodeKind::Fulltext => "a full-text index",
          _ => "an embedding index",
        },
        fields = declared(columns),
      ),
    ));
  }
  elections
}

/// A declaration's field names, as a refusal quotes them.
///
/// Comma-joined rather than through [`list`], whose `or` reads as a choice between words in a closed
/// vocabulary. These are not a vocabulary — they are what this one struct happens to declare.
fn declared(columns: &[Column]) -> String {
  if columns.is_empty() {
    return "no fields at all".to_owned();
  }
  columns
    .iter()
    .map(|column| format!("`{}`", column.name))
    .collect::<Vec<_>>()
    .join(", ")
}

/// The ONE word inside `dedup(…)`.
///
/// A bare word rather than `= "…"`, because it is a member of a CLOSED framework vocabulary: what
/// it names is one of the framework's own membership implementations, so it is written as a word
/// and refused as a word. Every other closed vocabulary in this grammar is spelled the same way.
///
/// A second word is refused rather than taken as an override, and the refusal says WHY rather than
/// reporting a duplicate: two mechanisms in one block is an author who has not decided, and the
/// choice they are making is a bound on their key.
fn dedup_word(
  inner: &syn::meta::ParseNestedMeta<'_>,
  dedup: &mut Option<Dedup>,
  errors: &mut Errors,
) {
  let Some(word) = inner.path.get_ident() else {
    errors.push(attribute::unknown(
      inner,
      &format!(
        "`dedup(…)` takes ONE word — {words} — and a path with several segments is not one",
        words = list(&Dedup::WORDS),
      ),
      &[],
    ));
    return;
  };
  let chosen = if word == Dedup::Hash.as_str() {
    Dedup::Hash
  } else if word == Dedup::Eq.as_str() {
    Dedup::Eq
  } else {
    errors.push(syn::Error::new_spanned(
      word,
      format!(
        "`{word}` is not a dedup mechanism — the words are {words}. `hash` compares keys by \
         hashing them and asks the key for `Hash + Eq`; `eq` walks a seen-list comparing every \
         field and asks only for `PartialEq`, which is the escape for a key that cannot hash. The \
         vocabulary is the framework's, so a mechanism it does not implement is not a word here{near}",
        words = list(&Dedup::WORDS),
        near = crate::suggest::did_you_mean(&word.to_string(), Dedup::WORDS),
      ),
    ));
    return;
  };
  if let Some(first) = dedup {
    errors.push(syn::Error::new_spanned(
      word,
      format!(
        "`dedup(…)` names ONE mechanism and `{first}` was already named — the word is a BOUND on \
         this index's key, and a declaration that asks for both is asking for neither",
        first = first.as_str(),
      ),
    ));
    return;
  }
  *dedup = Some(chosen);
}

/// A vocabulary as a refusal quotes one: `` `hash` or `eq` ``.
///
/// Shared with the graph root's own `dedup(…)` front end, which refuses the same vocabulary one
/// grain up: the two sentences are byte-identical where the subject is the MECHANISM rather than the
/// declaration, and a second copy of this would be the first place that stopped being true.
pub(crate) fn list(words: &[&str]) -> String {
  words
    .iter()
    .map(|word| format!("`{word}`"))
    .collect::<Vec<_>>()
    .join(" or ")
}

/// One entry inside `upstream(…)`: the upstream, or one of this index's fields naming where it is read
/// from.
fn source_entry(
  inner: &syn::meta::ParseNestedMeta<'_>,
  node: &mut Option<syn::Path>,
  entries: &mut Vec<UpstreamEntry>,
  errors: &mut Errors,
) -> syn::Result<()> {
  if inner.path.is_ident("node") {
    match value::parse_literal::<syn::Path>(
      inner,
      "`node = \"…\"` names the upstream node, as a type path in a string literal",
    ) {
      Ok(path) => set_once(
        node,
        path,
        &inner.path,
        "`node` is declared more than once in `upstream(…)` — one entry names one upstream",
        errors,
      ),
      Err(e) => errors.push(e),
    }
    return Ok(());
  }

  let Some(field) = inner.path.get_ident().cloned() else {
    errors.push(attribute::unknown(
      inner,
      "a projection names ONE of this declaration's fields, so the entry is that field's name — a \
       path with several segments names no field of anything",
      // A projection's word is one of THIS struct's field names, which is not a vocabulary: see
      // `declared`, whose own note says why. `node` is the one framework word here, and it is read
      // above.
      &[],
    ));
    return Ok(());
  };

  // The LIST form, which the ruled grammar has and whose MEANING it does not: several upstream
  // fields reaching one index field need a combining rule — `each`, or a separator to join on — and
  // an emission that picked one would be inventing the answer rather than reading it.
  if inner.input.peek(syn::Token![=]) && inner.input.peek2(syn::token::Bracket) {
    errors.push(named(
      inner,
      format!(
        "`{field} = [\"…\", \"…\"]` reads SEVERAL of the upstream's fields into one of this \
         declaration's, and how they combine is not declared anywhere — one goes in as a list, \
         another joined on a separator, and the two are different documents. That grammar has not \
         arrived; one upstream field is `{field} = \"…\"`"
      ),
    ));
    return Ok(());
  }

  let from = match value::literal(
    inner,
    &format!(
      "`{field} = \"…\"` names the upstream field this one is read out of, in a string literal"
    ),
  ) {
    Ok(literal) => match literal.parse::<syn::Ident>() {
      // The parse RESPANS to the literal, which is the whole reason the string is kept: every error
      // the emitted audit produces about this projection lands where the author wrote it. Pinned by
      // `tests/span_pins.rs`, at the column of the caret `tests/projections/` makes rustc print — a
      // span is observable nowhere else, proc-macro2 holding every location behind a feature.
      Ok(from) => from,
      Err(_) => {
        errors.push(syn::Error::new_spanned(
          &literal,
          format!(
            "`{field} = \"…\"` names ONE field of the upstream, so its value is a field name — a \
             path, an expression or an empty string is not one"
          ),
        ));
        return Ok(());
      }
    },
    Err(e) => {
      errors.push(e);
      return Ok(());
    }
  };

  if entries.iter().any(|entry| entry.field == field) {
    errors.push(syn::Error::new_spanned(
      &inner.path,
      format!(
        "`{field}` is projected more than once — one of this declaration's fields is read out of \
         one of the upstream's"
      ),
    ));
    return Ok(());
  }
  entries.push(UpstreamEntry { field, from });
  Ok(())
}

/// The block's entries matched against the fields they fill — the step that turns two lists of
/// names into the model, and the one that refuses a name belonging to only one of them.
///
/// EVERY field must be projected, and it is the property that makes the emitted audit total: a
/// document is one upstream message indexed, so a field with no entry is a field with no answer to
/// *where does this come from*. The declaration is what says so, and the constructor is where the
/// value actually arrives — the audit checks the claim, it does not build the document.
///
/// It runs BEFORE the missing-`node` bail rather than after it, so a `upstream(…)` that named no
/// upstream still reports what is wrong with its projections. A declaration is walked once and gets
/// every answer the walk could reach.
fn projections(
  block: &UpstreamBlock,
  columns: &[Column],
  kind: NodeKind,
  index: &syn::Ident,
  errors: &mut Errors,
) -> Vec<Projected> {
  for entry in &block.entries {
    if !columns.iter().any(|column| column.name == entry.field) {
      errors.push(syn::Error::new_spanned(
        &entry.field,
        format!(
          "`upstream(…)`'s entries name THIS declaration's fields, and `{}` is not one of \
           `{index}`'s — the entry's own name is the field being filled, and its value is the \
           upstream field it is read out of",
          entry.field,
        ),
      ));
    }
  }
  // A field named `node` has already been refused for colliding with the upstream entry, and
  // reporting it a second time here would send its author to write the entry that cannot exist.
  for column in columns.iter().filter(|column| column.name != "node") {
    if !block.entries.iter().any(|entry| entry.field == column.name) {
      errors.push(syn::Error::new_spanned(
        &column.name,
        format!(
          "`{}` is read out of nothing — every field of {article} {noun} comes from the upstream \
           message the document was derived from, so each one needs its own `upstream(…)` entry: \
           `{} = \"<upstream field>\"`",
          column.name,
          column.name,
          article = kind.article(),
          noun = kind.noun(),
        ),
      ));
    }
  }
  // Ordered by the DECLARATION rather than by the attribute, so the emitted audits read down the
  // struct and the model is the same model however the entries were written.
  columns
    .iter()
    .filter_map(|column| {
      let entry = block
        .entries
        .iter()
        .find(|entry| entry.field == column.name)?;
      Some(Projected {
        field: column.name.clone(),
        from: entry.from.clone(),
        ty: column.ty.clone(),
      })
    })
    .collect()
}

/// The `upstream(…)` block AS WRITTEN.
struct UpstreamBlock {
  /// `node = "…"`, when it was named.
  node: Option<syn::Path>,
  /// The projections, in the order they were written.
  entries: Vec<UpstreamEntry>,
  /// The block's own path, for a refusal about the block rather than an entry inside it.
  at: syn::Path,
}

/// One projection AS WRITTEN — no field of this declaration is known to exist yet.
struct UpstreamEntry {
  /// The entry's own name: the field of this declaration being filled.
  field: syn::Ident,
  /// The upstream field it is read out of, carrying the span of the string that named it.
  from: syn::Ident,
}

/// The field markers: the three PROJECTION words, this kind's ELECTION marker, and a named refusal
/// for the rest.
///
/// The three projections are admitted because this emission SPENDS them — each names one way an
/// accessor hands a field back. The election marker is admitted because it is the whole subject of
/// the declaration: `knn` on a `vector`, `searchable` on a `fulltext`, each claimed here and read in
/// [`elect`]. `id` is refused permanently rather than as a wait: the tier's whole definition is that
/// the key is not its to mint.
///
/// # The ENGINE BLOCKS landed here, on R1's seam and not on a walk of their own
///
/// `#[ingraph(knn, lance, hnsw(ef = 200), fanout)]` — election, engines and liveness, all on the
/// field, all read by the ONE [`Claim`](column::Claim) closure below. What this round added is arms.
/// What it did not add is a second reader for the words this one already claims, which is the whole
/// point of the seam existing.
///
/// # The vocabulary is CLOSED on the framework's side and OPEN past it
///
/// Every word the framework owns is named here — the three projections in the shared walk, `id`,
/// `persist`, the two election markers, `fanout` — and a word outside that set is an ENGINE. It has
/// to be: `hnsw` names an engine this crate has never heard of, and a table of legal engine words
/// would close the surface end users extend.
///
/// The price is stated rather than hidden: on a kind that ELECTS, an unknown word is no longer an
/// unknown-entry refusal, because it is a legal declaration. A misspelt `optionel` becomes an engine
/// nothing binds, and surfaces where the binding is asked for rather than here.
///
/// Two refusals recover most of it and neither is decidable IN the walk, because a marker list has
/// no order — `#[ingraph(lance, knn)]` writes the engine first. So both are made after it, in
/// [`engines_of`]: an engine on a field that elected nothing, and `fanout` with nothing to fan. A
/// kind that elects NOTHING keeps the closed vocabulary whole, refusing any engine word by name.
fn markers(
  attrs: &[syn::Attribute],
  field: &syn::Ident,
  kind: NodeKind,
  errors: &mut Errors,
) -> (Projection, Role) {
  let mut role = Role::default();
  let project = column::projection_markers(attrs, field, errors, |meta, errors| {
    if meta.path.is_ident("id") {
      return column::Claim::Refused(syn::Error::new_spanned(
        &meta.path,
        format!(
          "`{field}` cannot be {article} {noun}'s id, because it mints none — a document is one \
           upstream message indexed, so it is addressed by THAT message's key, which the expansion \
           carries for it. A node that mints an id of its own is an `operator` or a `record`",
          article = kind.article(),
          noun = kind.noun(),
        ),
      ));
    }

    // The two ELECTION markers, each read on the one kind that has it and refused BY NAME on the
    // other two. By name rather than as an unknown entry for the courtesy the retired head word got:
    // an author who wrote one had a coherent idea, and what they need told is which kind carries it.
    //
    // Walked over the KINDS rather than over a table of words, so the vocabulary has one home:
    // `NodeKind::election` is what every refusal here spells and what a third electing kind would
    // arrive through.
    for owner in [NodeKind::Vector, NodeKind::Fulltext] {
      let Some(word) = owner.election() else {
        continue;
      };
      if !meta.path.is_ident(word) {
        continue;
      }
      if kind != owner {
        return column::Claim::Refused(syn::Error::new_spanned(
          &meta.path,
          wrong_kind(word, owner, kind, field),
        ));
      }
      if role.elected {
        // The ORDINARY duplicate family, which is what the head word's own repeat refusal retired
        // into: `projection_markers` says exactly this about a repeated projection word, and a
        // repeated marker is the same mistake about the same field.
        errors.push(syn::Error::new_spanned(
          &meta.path,
          format!("`{word}` is declared more than once on `{field}` — one marker, one field"),
        ));
        attribute::skip_entry(meta);
        return column::Claim::Taken;
      }
      role.elected = true;
      // `searchable` is BARE and takes no block: a full-text election says which field is searched
      // and nothing else. WHICH ENGINE holds it is now answerable and is answered BESIDE the marker
      // rather than inside it — the engine words are their own blocks, which is what keeps one
      // engine's knobs out of the election's grammar. What a search is SCOPED by is still nobody's
      // word here. `knn` carries the question road — see [`ask_word`], which is the head word's
      // reader moved onto the marker.
      if owner == NodeKind::Fulltext {
        if attribute::has_block(meta) || attribute::has_value(meta) {
          errors.push(named(
            meta,
            format!(
              "`{word}` is a BARE marker — it says `{field}` is searched, which is the whole of \
               what a full-text election declares. WHICH ENGINE holds it is written BESIDE the \
               marker, each engine its own block: `#[ingraph({word}, <engine>, <engine>(<knob> = \
               …))]`. What a search is SCOPED by is not this grammar's yet, and a word parsed into a \
               model nothing spends is a promise rather than a rule"
            ),
          ));
        }
        return column::Claim::Taken;
      }
      if let Err(e) = attribute::options(meta, |inner| {
        // The SEMANTICS block rides inside `knn(…)` because it qualifies one ELECTION rather than
        // the declaration, being a fact about one column's answer. `searchable(…)` rides here for
        // the same reason at the other end: a question ROAD reaches one column, not a declaration.
        // The reader beside them is what answers the two retired road words.
        if inner.path.is_ident(SEMANTICS) {
          semantics_word(&inner, &mut role.fold, errors);
          return Ok(());
        }
        if inner.path.is_ident(SEARCHABLE) {
          searchable_word(&inner, &mut role.tower_road, errors);
          return Ok(());
        }
        road_word(&inner, errors);
        Ok(())
      }) {
        errors.push(e);
      }
      return column::Claim::Taken;
    }

    // The ELECTION LABEL, claimed here because it is written in the SAME marker list as the
    // election it qualifies — `#[ingraph(list(embedding), knn, lance)]` is one attribute, and one
    // reader takes every word of it. Refused BY NAME on the kinds that elect no coordinates, for the
    // courtesy `knn` itself gets: an author who wrote one had a coherent idea about the wrong kind.
    if begins_an_election_label(&meta.path) {
      if kind != NodeKind::Vector {
        return column::Claim::Refused(named(
          meta,
          format!(
            "`{field}` is labelled as an embedding field and {article} {noun} elects none — the \
             label says how many embeddings a knn's column holds, and this node runs no knn. The \
             label is the `vector` kind's own",
            article = kind.article(),
            noun = kind.noun(),
          ),
        ));
      }
      if let Some(read) = one_label(meta, field, errors) {
        set_once(
          &mut role.label,
          read,
          &meta.path,
          &format!(
            "`{field}` is labelled more than once — one label, one field. A field holds one \
             embedding or a set of them, and the two are different labels rather than two halves of \
             one"
          ),
          errors,
        );
      }
      return column::Claim::Taken;
    }

    // The LIVENESS marker. Bare, and refused as a block for `searchable`'s reason: what it says is
    // *all of them at once*, which has no knob inside it.
    if meta.path.is_ident(FANOUT) {
      if kind.election().is_none() {
        return column::Claim::Refused(syn::Error::new_spanned(
          &meta.path,
          format!(
            "`{FANOUT}` says every engine `{field}` declared is live at once, and {article} {noun} \
             declares none — it elects nothing, so no field of one is written to an engine at all",
            article = kind.article(),
            noun = kind.noun(),
          ),
        ));
      }
      if attribute::has_block(meta) || attribute::has_value(meta) {
        errors.push(named(
          meta,
          format!(
            "`{FANOUT}` is a BARE marker — it says every engine `{field}` declared is live at once, \
             and *all of them* has no knob inside it. What ONE engine is tuned by is that engine's \
             own block, written beside this word"
          ),
        ));
        return column::Claim::Taken;
      }
      if role.fanout.is_some() {
        errors.push(syn::Error::new_spanned(
          &meta.path,
          format!("`{FANOUT}` is declared more than once on `{field}` — one marker, one field"),
        ));
        return column::Claim::Taken;
      }
      role.fanout = Some(meta.path.clone());
      return column::Claim::Taken;
    }

    // THE ELECTION TIER's numbers, and its skin block. Both are claimed ABOVE the engine catch-all
    // for that position's own law: every word this grammar does not own is an ENGINE's, so a word it
    // does own has to be taken first or `limit = 20` becomes an engine called `limit`.
    if let Some(walked) = numbers_word(meta, &mut role.numbers, &format!("`{field}`"), errors) {
      if let Err(refusal) = walked {
        return column::Claim::Refused(refusal);
      }
      return column::Claim::Taken;
    }
    if meta.path.is_ident(GRAPHQL) {
      if let Err(refusal) = election_skins(meta, &mut role.skins, field, errors) {
        return column::Claim::Refused(refusal);
      }
      return column::Claim::Taken;
    }

    // THE AGGREGATE's two role words at a field, refused by name and ABOVE the engine catch-all for
    // its reason: on a kind that elects, every word this grammar does not own is an ENGINE, so a
    // `measure` read one arm later would become an engine nothing binds.
    for word in [
      ingraph_codegen::aggregate::GROUP,
      ingraph_codegen::aggregate::MEASURE,
    ] {
      if meta.path.is_ident(word) {
        return column::Claim::Refused(syn::Error::new_spanned(
          &meta.path,
          crate::aggregate::wrong_kind(word, kind, crate::aggregate::Written::OnAField),
        ));
      }
    }

    // The RECORD's storage word, refused by name — the teaching refusal ruling 1 asks for. An author
    // who wrote it has the record's shape in mind, and the sentence's useful half is why an index
    // field does not take one.
    if meta.path.is_ident("persist") {
      return column::Claim::Refused(syn::Error::new_spanned(
        &meta.path,
        format!(
          "`persist(…)` is the ROW storage's wrapper and an index field takes none — on a field of \
           {article} {noun} the ENGINE IS THE STORE, so there is no second axis for a wrapper to \
           namespace against and the engines are written BARE beside the marker: \
           `#[ingraph({marker}, <engine>, <engine>(<knob> = …))]`. A node whose messages land in a \
           database is a `record`",
          article = kind.article(),
          noun = kind.noun(),
          marker = kind.election().unwrap_or("…"),
        ),
      ));
    }

    // AN ENGINE BLOCK — every word the framework does not own, which is what an open vocabulary
    // means. The three checks that CAN be made here are made here; the two that depend on the whole
    // field are made after the walk, in `engines_of`.
    let Some(word) = meta.path.get_ident().cloned() else {
      return column::Claim::Refused(attribute::unknown(
        meta,
        "an engine is named by ONE word — `lance`, `tantivy`, `hnsw` — and a path with several \
         segments names no engine. The word is bare because it is a NAME the deployment binds: a \
         path written on a declaration would bind it here, where the engine a build actually \
         compiled is not knowable",
        // #256's D2, on the field side: on a kind that ELECTS this position is open, so a word is
        // never unknown here and there is nothing for a near miss to be near.
        &[],
      ));
    };
    if kind.election().is_none() {
      return column::Claim::Refused(syn::Error::new_spanned(
        &word,
        format!(
          "`{word}` reads as an ENGINE, and {article} {noun} names none on its fields — it elects \
           nothing, so it has no field-scoped index for an engine to hold. Where its artifacts are \
           written is the store layer's{near}",
          article = kind.article(),
          noun = kind.noun(),
          // THE ONE ENGINE POSITION WITH A CLOSED VOCABULARY, and #256's D2 residue recovered
          // exactly where it can be: a kind that elects nothing reads no word as an engine, so what
          // is left on its field is the projection vocabulary — and `optionel`, D2's own example,
          // is answered here instead of at the type layer.
          near = crate::suggest::did_you_mean(&word.to_string(), column::PROJECTIONS),
        ),
      ));
    }
    // A KIND WORD AT AN ELECTION, refused whichever kind it serves — the retirement that pairs with
    // `type =`'s, and the reason it is UNCONDITIONAL where the old rule was kind-guarded.
    //
    // The word used to be a SELF-BINDING label: `tantivy` on a searchable field meant *the engine
    // this framework ships*, bound under its own feature, and the only question worth asking was
    // whether the field's kind matched. That reading is gone. Kind is said ONCE and the place it is
    // said is the resource, so a leg here writes a LABEL — a free word, this slot's name in the
    // fused road's vocabulary — and POINTS at the resource that holds it.
    //
    // Refused rather than re-read as an ordinary label, and the asymmetry is deliberate: every
    // OTHER word at this position is free, so a reader who wrote `tantivy` expecting the old
    // self-binding would otherwise get a label that binds nothing and says so nowhere. This is the
    // one closed half the position has, and it is closed only to say where the word went.
    if let Some(shipped) = EngineKind::of(&word) {
      return column::Claim::Refused(syn::Error::new_spanned(
        &word,
        format!(
          "`{word}` is an engine `ingraph` ships, and an engine is not named at an election any \
           more — kind is said ONCE, at the resource: `#[ingraph::resource({word})] pub struct \
           Store;`. Here `{field}` writes a LABEL of its own and POINTS at that declaration — \
           `{word}_of_mine(resource = \"crate::Store\")` — so the label names this leg in the fused \
           road and the store's kind stays where it was declared. `{word}` holds {serves}",
          serves = shipped.serves().plural(),
        ),
      ));
    }
    if let Some(first) = role.engines.iter().find(|engine| engine.word == word) {
      errors.push(syn::Error::new_spanned(
        &word,
        format!(
          "`{first}` is declared more than once on `{field}` — one block per engine, exactly as \
           one `persist(…)` names a database once. TWO FIELDS sharing an engine repeat the word, \
           each on its own field, and that is two slots rather than a repeat",
          first = first.word,
        ),
      ));
      attribute::skip_entry(meta);
      return column::Claim::Taken;
    }
    // The block's contents are PARTITIONED: the framework's own seven words are read, and everything
    // else is the engine's and is carried untouched. See `engine_block`.
    if attribute::has_value(meta) {
      errors.push(named(
        meta,
        format!(
          "`{word}` is an ENGINE and an engine is declared as a BLOCK — write `{word}` for its \
           defaults, or `{word}(…)` to tune it. `{word} = …` reads as an option of this grammar's, \
           and what goes inside an engine's parentheses is the ENGINE's, bar the {claimed} this \
           grammar claims",
          claimed = BLOCK_WORDS.map(|word| format!("`{word}`")).join(", "),
        ),
      ));
      role.engines.push(Engine::bare(word));
      return column::Claim::Taken;
    }
    role
      .engines
      .push(engine_block(meta, word, field, kind, errors));
    column::Claim::Taken
  });
  (project, role)
}

/// `stored` — the engine KEEPS the original value, retrievable.
const STORED: &str = "stored";

/// `join = "<sep>"` — the values in ONE segment, joined.
const JOIN: &str = "join";

/// `multi` — ONE SEGMENT PER VALUE.
const MULTI: &str = "multi";

/// `resource = "path::To::Resource"` — the RESOURCE this leg is written to.
///
/// NOT one of [`CONVERSION_WORDS`]: those say how a value is read as text and are a full-text
/// declaration's alone, where this says WHICH STORE holds the slot and is asked on both kinds.
const RESOURCE: &str = "resource";

/// `type = "path::To::Engine"` — the word this position used to take, kept ONLY to refuse it.
///
/// # It is a retirement rather than a rename, and the difference is what the refusal says
///
/// The old word named an ENGINE, which put the kind of a store in two places: on the declaration
/// that wrote the type, and on whatever the deployment opened. **Kind is said once, at the
/// resource** — so the position now POINTS at a resource declaration and the engine underneath it
/// is that declaration's own business.
///
/// The word is not accepted as an alias. This framework is unpublished, so a retired spelling has
/// no compatibility to keep, and an alias would leave the two readings — *this leg IS this engine*
/// and *this leg points at this store* — both spellable for a reader to confuse. What it buys
/// instead is one sentence at the exact token, naming the word that replaced it.
const RETIRED_TYPE: &str = "type";

/// `rrf = <bool>` — whether this leg enters the FUSED ROAD of the slot it holds.
///
/// On BOTH kinds for [`RESOURCE`]'s reason: a fan's read half is a leaderboard or it is redundancy,
/// and which of the two it is has nothing to do with whether the store holds documents or
/// coordinates.
///
/// # The VALUE form and not a bare marker
///
/// The default is TRUE, so a bare `rrf` could only turn ON what is already on — a word with no
/// state to change. `rrf = false` is the whole point of the word, and the refusal below says so
/// rather than accepting a marker that means nothing.
const RRF: &str = "rrf";

/// `lanes(zh(accepts(cmn)), en, rest(catch_all))` — the PARTITIONS this leg's corpus is cut into.
///
/// # It lives INSIDE the engine's block, and that placement is the ruling
///
/// A lane exists because ONE ENGINE HAS A PHYSICS — a full-text field has one tokenizer and an
/// immutable schema — rather than because the domain has a concept called *lane*. So the vocabulary
/// was put where the limitation is, inside the block whose engine has it, on
/// `persist(sqlite(type = …))`'s own precedent: a comparison is a fact about a BACKEND, and so is a
/// partition.
///
/// # FULL-TEXT ONLY
///
/// A knn indexes coordinates, which no analyzer reads, and an artifact store holds bytes. Neither
/// has a lane story, so the word is refused BY NAME on the other kind — the courtesy every
/// misplaced-word refusal in this grammar gets, rather than a sweep into the carried half where it
/// would reach an engine as a knob and go silent.
const LANES: &str = "lanes";

/// `accepts(zh_hans, zh_hant, cmn)` — the tags ONE LANE answers beside its own key.
const ACCEPTS: &str = "accepts";

/// `catch_all` — the ONE lane of a roster that answers every tag no other lane has a home for.
const CATCH_ALL: &str = "catch_all";

/// The framework's own words INSIDE ONE LANE, everything else being the engine's and carried.
///
/// The partition the block around it already draws, one grain down, and the division is the
/// ruling's: a lane's EXISTENCE — its key, its aliases, whether it catches strangers — shapes the
/// slot and is therefore read here, and its INSTANCE is a value a deployment builds at boot. So
/// `tokenizer = "…"` is not in this list: it is a word for the backend, carried with `ef = 200` and
/// every other knob.
const LANE_WORDS: [&str; 2] = [ACCEPTS, CATCH_ALL];

/// The CARVED VOCABULARY of an engine block — the framework's own words, everything else being the
/// engine's and carried untouched.
///
/// A list rather than seven scattered `is_ident` calls because a refusal quotes it: the one that
/// tells a `{word} = …` author that an engine is a block, and therefore which words this grammar
/// claimed inside one. It is NOT a near-miss table and there is deliberately no did-you-mean at this
/// position: an entry outside the list is an ENGINE's knob and legal, so a suggestion here would
/// fire on a correct declaration. See `near_miss_tests`' own row for the engine position, which
/// states the same law one grain up.
const BLOCK_WORDS: [&str; 7] = [MULTI, JOIN, "from", STORED, RESOURCE, RRF, LANES];

/// The FULL-TEXT conversion grammar's five words, for the refusal that names them on another kind.
const CONVERSION_WORDS: [&str; 5] = [JOIN, MULTI, STORED, "from", "try_from"];

/// ONE ENGINE BLOCK's contents, PARTITIONED — the framework's own words read, the engine's carried.
///
/// # Why this grammar reads inside a block it declared uninterpretable
///
/// [`Engine::options`] carries an engine's knobs because reading them would mean holding every
/// engine's option set here, and refusing what it could not read would close an open vocabulary
/// through the back door. That argument is about knobs and it still stands. What is read here is
/// not a knob: `stored`, the two shorthands and the conversion legs are FRAMEWORK words with one
/// meaning wherever they appear, and they are written inside the block because the thing they
/// qualify is per-engine — a road's segmentation means different things to different engines, so a
/// field-level one is not expressible. The parentheses are a shared namespace, and seven words of it
/// are the framework's.
///
/// # The direction law, and the leg this face does not have
///
/// *`from` BUILDS the projection the block is about* — the document. `into`/`try_into` are refused
/// BY NAME rather than swept into the unknown-entry family, because an author who wrote one had a
/// coherent idea and what they need told is that a document is never read back.
///
/// # Refused BY NAME on a kind that is not full-text
///
/// The vector kind's blocks take the same shape and none of these words: a knn indexes coordinates,
/// which are not read as text and are never joined. The refusal says which kind carries the word,
/// for the courtesy every other misplaced-word refusal in this pass gets.
fn engine_block(
  meta: &syn::meta::ParseNestedMeta<'_>,
  word: syn::Ident,
  field: &syn::Ident,
  kind: NodeKind,
  errors: &mut Errors,
) -> Engine {
  let word = &word;
  let scope = format!("`{word}(…)` on `{field}`");
  let mut carried = proc_macro2::TokenStream::new();
  let mut from = crate::parse::ConversionSpec::default();
  let mut leaves = crate::parse::ConversionSpec::default();
  let mut join: Option<syn::LitStr> = None;
  let mut multi: Option<syn::Path> = None;
  let mut stored: Option<syn::Path> = None;
  let mut resource: Option<syn::Path> = None;
  let mut rrf: Option<syn::LitBool> = None;
  // THE FAN, and the ENGINE'S HALF of it kept apart. `lanes` is `None` until the word is written —
  // which is what the repeat refusal reads — and `lane_options` is the residue of every lane's own
  // block, re-assembled into the carried tokens once the walk is over so a backend reads
  // `lanes(zh(tokenizer = "…"))` exactly as its author wrote it.
  let mut lanes: Option<(syn::Path, Vec<DeclaredLane>)> = None;
  let mut lane_options: Vec<(syn::Ident, proc_macro2::TokenStream)> = Vec::new();

  if let Err(e) = attribute::options(meta, |inner| {
    // A CONVERSION WORD on a kind whose index holds no document. Answered before anything reads it,
    // so the sentence is about the kind rather than about the shape the word was written in.
    if kind != NodeKind::Fulltext
      && CONVERSION_WORDS
        .iter()
        .any(|conversion| inner.path.is_ident(conversion))
    {
      errors.push(named(
        &inner,
        format!(
          "`{written}` is the FULL-TEXT conversion grammar's, and `{field}` is {article} {noun}'s \
           — the words say how a value is read as the text an engine indexes, and this kind indexes \
           no text. A `knn` column is a coordinate: nothing joins it, nothing renders it, and what \
           it is stored as is the engine's own",
          written = inner.path.to_token_stream(),
          article = kind.article(),
          noun = kind.noun(),
        ),
      ));
      return Ok(());
    }

    // THE FAN. Read BEFORE the pointing road for the conversion family's reason: the sentence an
    // author of a misplaced one earns is about the KIND, and answering it here keeps it off the
    // shape refusals below.
    if inner.path.is_ident(LANES) {
      lanes_block(
        &inner,
        &mut lanes,
        &mut lane_options,
        word,
        field,
        kind,
        &scope,
        errors,
      );
      return Ok(());
    }

    // THE RETIRED WORD, refused BY NAME and before the word that replaced it — an author who wrote
    // it had a coherent idea, and what they need told is that the idea moved rather than that the
    // spelling is unknown. Swept into the carried half it would have reached the engine as a knob
    // and gone silent, which is the one outcome a retirement must not have.
    if inner.path.is_ident(RETIRED_TYPE) {
      errors.push(named(
        &inner,
        format!(
          "`{RETIRED_TYPE} = …` retired — write `{RESOURCE} = \"path::To::Resource\"` instead. The \
           old word named an ENGINE here, which said the KIND of a store twice: once on this \
           declaration and once on whatever the deployment opened. Kind is said ONCE, at the \
           resource — `#[ingraph::resource(tantivy)] pub struct Ft;` — and `{word}` POINTS at that \
           declaration"
        ),
      ));
      return Ok(());
    }

    // THE POINTING ROAD. Asked on BOTH kinds, which is what keeps it out of the conversion list
    // above: a floor and a search input are the STORE's own currencies whether the slot holds
    // documents or coordinates, and neither has a blanket type for a package to fall back on.
    //
    // REFER-QUOTED for this grammar's standing reason, and read through the same
    // `parse_literal::<syn::Path>` every other pointing word in this grammar travels on — a path,
    // written out, resolving where its author wrote it.
    if inner.path.is_ident(RESOURCE) {
      match value::parse_literal::<syn::Path>(
        &inner,
        &format!(
          "`{RESOURCE} = \"path::To::Resource\"` names the RESOURCE `{word}` is written to, as a \
           path in a string literal. It is what lets this slot's package publish a floor in that \
           store's own `Score` — there is no blanket currency for one, so a package pointing at \
           nothing has no `engine` seat at all"
        ),
      ) {
        Ok(path) => set_once(
          &mut resource,
          path,
          &inner.path,
          &format!("`{RESOURCE}` is declared more than once in {scope} — one leg, one store"),
          errors,
        ),
        Err(e) => {
          errors.push(e);
          attribute::skip_entry(&inner);
        }
      }
      return Ok(());
    }

    // THE FUSED-ROAD MEMBERSHIP. Asked on BOTH kinds beside `type`, and for the same division: a
    // fan's read half is a leaderboard or it is redundancy, which is a question about the SLOT
    // rather than about what the store holds.
    if inner.path.is_ident(RRF) {
      match value::boolean(
        &inner,
        &format!(
          "`{RRF}` takes a BOOLEAN written bare — `{RRF} = false`. It says whether `{word}` enters \
           the fused road of `{field}`'s fan: TRUE (the default, and what saying nothing means) \
           puts this leg's ranking into the fold as its own evidence, FALSE writes the leg and \
           leaves it out of the leaderboard — a fan for REDUNDANCY rather than for a leaderboard. \
           There is no bare form, because the default is already the `true` one"
        ),
      ) {
        Ok(flag) => set_once(
          &mut rrf,
          flag,
          &inner.path,
          &format!("`{RRF}` is declared more than once in {scope} — one leg, one membership"),
          errors,
        ),
        Err(e) => {
          errors.push(e);
          attribute::skip_entry(&inner);
        }
      }
      return Ok(());
    }

    // THE STORED MARKER. Bare, for `fanout`'s reason: *keep the value* has no knob inside it.
    if inner.path.is_ident(STORED) {
      if attribute::has_block(&inner) || attribute::has_value(&inner) {
        errors.push(named(
          &inner,
          format!(
            "`{STORED}` is a BARE marker — it says `{word}` keeps `{field}`'s value beside what it \
             indexed, and *keep it* has no knob inside it. HOW an engine stores what it keeps is \
             that engine's own, written as its own knob in this block"
          ),
        ));
        return Ok(());
      }
      set_once(
        &mut stored,
        inner.path.clone(),
        &inner.path,
        &format!("`{STORED}` is declared more than once in {scope} — one marker, one block"),
        errors,
      );
      return Ok(());
    }

    // THE JOIN SHORTHAND, in the VALUE form: the separator is the author's, so there is a value to
    // write and the word alone says nothing.
    if inner.path.is_ident(JOIN) {
      match value::literal(
        &inner,
        &format!(
          "`{JOIN}` takes the SEPARATOR it joins with, in a string literal — `{JOIN} = \", \"`. It \
           is a value rather than a bare word because the separator is the declaration's own \
           choice, and rather than a block because there is nothing else inside it to name"
        ),
      ) {
        Ok(separator) => set_once(
          &mut join,
          separator,
          &inner.path,
          &format!("`{JOIN}` is declared more than once in {scope} — one road, one block"),
          errors,
        ),
        Err(e) => {
          errors.push(e);
          attribute::skip_entry(&inner);
        }
      }
      return Ok(());
    }

    // THE MULTI SHORTHAND. Bare: *each value on its own* has no knob inside it either.
    if inner.path.is_ident(MULTI) {
      if attribute::has_block(&inner) || attribute::has_value(&inner) {
        errors.push(named(
          &inner,
          format!(
            "`{MULTI}` is a BARE marker — it says each of `{field}`'s values reaches `{word}` as its \
             own segment, and *each of them* has no knob inside it. The road that DOES take a value \
             is `{JOIN} = \"<separator>\"`, which puts them in one segment instead"
          ),
        ));
        return Ok(());
      }
      set_once(
        &mut multi,
        inner.path.clone(),
        &inner.path,
        &format!("`{MULTI}` is declared more than once in {scope} — one road, one block"),
        errors,
      );
      return Ok(());
    }

    // THE LEG THIS FACE DOES NOT HAVE, refused by name before the shared reader could accept it.
    for leg in ["into", "try_into"] {
      if inner.path.is_ident(leg) {
        errors.push(named(
          &inner,
          format!(
            "`{leg}` LEAVES the projection a block is about, and a full-text document is never \
             left: it is written and searched, and what a hit hands back is the ADDRESS its key was \
             encoded into, not the text. So this block has one direction and `from` is it — \
             `from = \"path::to::fn\"`, or `try_from = \"…\"` where the conversion can fail"
          ),
        ));
        return Ok(());
      }
    }

    // THE DECLARED ROAD, through the SHIPPED reader — the same four spellings, the same two shapes,
    // the same refusals, so `from` means here what it means everywhere else in this grammar.
    if crate::parse::conversion(
      &inner,
      &mut from,
      &mut leaves,
      &scope,
      crate::parse::Cells::Elsewhere,
      errors,
    ) {
      return Ok(());
    }

    // THE ENGINE'S OWN, carried untouched.
    attribute::carry(&inner, &mut carried);
    Ok(())
  }) {
    errors.push(e);
  }

  let declared = from.resolve(&scope, crate::parse::BUILDS, errors);
  let road = settle_road(join, multi, declared, word, field, &scope, errors);
  // THE ENGINE'S HALF OF THE FAN, RE-ASSEMBLED — appended last, so what a backend reads is the same
  // block its author wrote with the framework's own words taken out of it. A lane whose block held
  // nothing but framework words contributes nothing, which keeps an all-framework `lanes(…)` from
  // carrying an empty shell to an engine that would then have to ignore it.
  carry_lane_options(&mut carried, &lane_options);
  Engine {
    word: word.clone(),
    road,
    stored: stored.is_some(),
    resource,
    options: carried,
    // ABSENT IS TRUE, which is the de-Option law at this word: there is no third state, and the
    // shape a fan had before the word existed is the shape it keeps.
    rrf: rrf.is_none_or(|flag| flag.value()),
    // ABSENT IS EMPTY, which is the same law one word over: a leg that named no lanes takes the
    // roster `Lanes` already defaults to — one lane, keyed `und` — and mints nothing of its own.
    lanes: lanes.map(|(_, declared)| declared).unwrap_or_default(),
  }
}

/// **ONE `lanes(…)` BLOCK** — the roster this leg's corpus is cut into, PARTITIONED like the block
/// around it.
///
/// ```text
/// lanes(en, zh(accepts(zh_hans, cmn), tokenizer = "jieba"), rest(catch_all))
///       │  │       └── the framework's                └── the ENGINE's, carried
///       │  └── a lane KEY, and every entry at this level is one
///       └── a lane with no aliases and no block at all
/// ```
///
/// # Every entry at the top level is a LANE KEY, so there is no near-miss table here
///
/// The vocabulary at this position is the DECLARATION's own — `zh`, `latn`, `rest`, whatever this
/// corpus calls its partitions — so a word that is not one of them is not a misspelling of anything
/// this grammar knows, and a did-you-mean would fire on a correct declaration. It is the engine
/// position's law one grain in, and [`LANE_WORDS`] is where a closed vocabulary does exist: inside
/// ONE LANE, where `accepts` and `catch_all` are the framework's two and everything else is carried.
///
/// # A key is a BARE WORD, and the fold is what makes that enough
///
/// `zh_hant` and not `"zh-Hant"`: a lane key is written as a Rust word so that it can be one, and
/// every comparison the gate makes runs through this crate's ONE fold — which drops `_`, `-` and
/// spaces and ignores ASCII case. So the lane written `zh_hant` is reached by the tag `zh-Hant`,
/// and the two spellings are one word wherever a roster is audited.
#[expect(
  clippy::too_many_arguments,
  reason = "the refusals name the word, the field, the kind and the scope, and each of the four \
            says something the others do not"
)]
fn lanes_block(
  meta: &syn::meta::ParseNestedMeta<'_>,
  lanes: &mut Option<(syn::Path, Vec<DeclaredLane>)>,
  lane_options: &mut Vec<(syn::Ident, proc_macro2::TokenStream)>,
  word: &syn::Ident,
  field: &syn::Ident,
  kind: NodeKind,
  scope: &str,
  errors: &mut Errors,
) {
  // THE KIND, FIRST. A lane is an answer to a full-text engine's physics, so the sentence an author
  // of a misplaced one earns is about the kind rather than about the shape they wrote.
  if kind != NodeKind::Fulltext {
    errors.push(named(
      meta,
      format!(
        "`{LANES}(…)` is the FULL-TEXT kind's, and `{field}` is {article} {noun}'s — a lane exists \
         because a searched field has ONE tokenizer and a schema that cannot change, so a corpus \
         holding several languages is several indexes. {Noun} indexes no text and has no analyzer \
         to vary, so there is nothing here for a partition to be a partition OF",
        article = kind.article(),
        noun = kind.noun(),
        Noun = {
          let noun = kind.noun();
          let mut titled = noun.to_owned();
          titled[..1].make_ascii_uppercase();
          format!("A {titled}")
        },
      ),
    ));
    return;
  }

  if let Some((_, _)) = lanes.as_ref() {
    errors.push(named(
      meta,
      format!(
        "`{LANES}` is declared more than once in {scope} — one corpus, one set of partitions"
      ),
    ));
    return;
  }

  // THE TWO WRONG SHAPES, each with its own sentence. A VALUE reads as though one word could name a
  // partition, and a BARE or EMPTY block claims a fan with nothing in it — which is not the unfanned
  // corpus (that is the word's ABSENCE) but a roster of no lanes, which no document could reach.
  if attribute::has_value(meta) {
    errors.push(named(
      meta,
      format!(
        "`{LANES}` is a BLOCK and not a value — `{LANES}(en, zh(accepts(cmn)), rest(catch_all))`. \
         Each entry is one PARTITION of `{field}`'s corpus, keyed by a bare word, so there is \
         nothing for a single `{LANES} = …` to name"
      ),
    ));
    return;
  }
  if !attribute::has_block(meta) || attribute::empty_group(meta) {
    errors.push(named(
      meta,
      format!(
        "`{LANES}(…)` names at least one lane — `{LANES}(en, zh(accepts(cmn)))`. An EMPTY fan is a \
         corpus no document can reach, and the corpus with one partition is what saying nothing \
         already means: leave `{LANES}` off and `{word}` holds the single undetermined lane it \
         always did"
      ),
    ));
    return;
  }

  let at = meta.path.clone();
  let mut roster: Vec<DeclaredLane> = Vec::new();
  if let Err(e) = meta.parse_nested_meta(|entry| {
    let Some(key) = entry.path.get_ident().cloned() else {
      errors.push(named(
        &entry,
        format!(
          "a lane is keyed by a BARE WORD, and `{written}` is a path — `{LANES}(zh, zh_hant)`. The \
           key is compared through this crate's one fold, which drops `_` and `-` and ignores case, \
           so the tag `zh-Hant` reaches the lane written `zh_hant` without a second spelling \
           anywhere",
          written = entry.path.to_token_stream(),
        ),
      ));
      return Ok(());
    };
    if attribute::has_value(&entry) {
      errors.push(named(
        &entry,
        format!(
          "`{key}` is a LANE and a lane is a WORD, optionally with a block — `{key}` for a lane \
           that answers only its own key, or `{key}(…)` to say more. `{key} = …` reads as an option \
           of this grammar's, and a lane is not one. What goes inside a lane's parentheses is \
           `{word}`'s, bar the {claimed} this grammar claims",
          claimed = LANE_WORDS.map(|claimed| format!("`{claimed}`")).join(" and "),
        ),
      ));
      return Ok(());
    }

    let mut lane = DeclaredLane::of(key.clone());
    let mut accepts: Option<syn::Path> = None;
    let mut residue = proc_macro2::TokenStream::new();
    if let Err(e) = attribute::options(&entry, |option| {
      // THE CATCH-ALL. Bare, for `stored`'s reason: *the strangers go here* has no knob inside it.
      if option.path.is_ident(CATCH_ALL) {
        if attribute::has_block(&option) || attribute::has_value(&option) {
          errors.push(named(
            &option,
            format!(
              "`{CATCH_ALL}` is a BARE marker — it says lane `{key}` answers every tag no other \
               lane has a home for, and *every one of them* has no knob inside it"
            ),
          ));
          return Ok(());
        }
        if lane.catch_all.is_some() {
          errors.push(named(
            &option,
            format!("`{CATCH_ALL}` is declared more than once on lane `{key}` — one lane, one role"),
          ));
          return Ok(());
        }
        lane.catch_all = option.path.get_ident().cloned();
        return Ok(());
      }

      // THE ALIASES. A block, because what goes inside it is a LIST and a list of one is still a
      // list — `accepts(cmn)` and `accepts(zh_hans, zh_hant, cmn)` are one shape.
      if option.path.is_ident(ACCEPTS) {
        if attribute::has_value(&option) || !attribute::has_block(&option) {
          errors.push(named(
            &option,
            format!(
              "`{ACCEPTS}` takes the tags lane `{key}` answers, as bare words in a block — \
               `{ACCEPTS}(zh_hans, zh_hant, cmn)`. A block rather than a value because a lane may \
               accept several, and a list of one is still a list"
            ),
          ));
          return Ok(());
        }
        if attribute::empty_group(&option) {
          errors.push(named(
            &option,
            format!(
              "`{ACCEPTS}()` on lane `{key}` names no tag at all, and a lane already answers its \
               own key — so an empty list is a word with nothing to add. Name the tags, or leave \
               `{ACCEPTS}` off"
            ),
          ));
          return Ok(());
        }
        if let Some(first) = accepts.as_ref() {
          errors.push(syn::Error::new_spanned(
            &option.path,
            format!(
              "`{ACCEPTS}` is declared more than once on lane `{key}` — one lane, one list. The \
               tags of the second belong in the first"
            ),
          ));
          let _ = first;
          attribute::skip_entry(&option);
          return Ok(());
        }
        accepts = Some(option.path.clone());
        return option.parse_nested_meta(|tag| {
          let Some(accepted) = tag.path.get_ident().cloned() else {
            errors.push(named(
              &tag,
              format!(
                "an accepted tag is a BARE WORD, and `{written}` is a path — \
                 `{ACCEPTS}(zh_hans, cmn)`",
                written = tag.path.to_token_stream(),
              ),
            ));
            return Ok(());
          };
          if attribute::has_value(&tag) || attribute::has_block(&tag) {
            errors.push(named(
              &tag,
              format!(
                "`{accepted}` is an accepted TAG and a tag is a bare word — it says which spellings \
                 reach lane `{key}`, and there is nothing inside one to configure"
              ),
            ));
            return Ok(());
          }
          lane.accepts.push(accepted);
          Ok(())
        });
      }

      // THE ENGINE'S OWN, carried — `tokenizer = "…"` and whatever else this backend reads per
      // lane. The block's own partition, one grain down.
      attribute::carry(&option, &mut residue);
      Ok(())
    }) {
      errors.push(e);
    }

    if !residue.is_empty() {
      lane_options.push((key, residue));
    }
    roster.push(lane);
    Ok(())
  }) {
    errors.push(e);
  }

  *lanes = Some((at, roster));
}

/// The ENGINE's half of a `lanes(…)` block, put back into the carried tokens.
///
/// `lanes(zh(tokenizer = "jieba"), rest(tokenizer = "raw"))` — the same word, the same lane keys,
/// and inside each one exactly what this grammar did not read. A lane that carried nothing does not
/// appear, and a block where no lane carried anything is not written at all, so an engine reading
/// these tokens sees a fan only where there was something in it for the engine.
///
/// The spans are the author's own, per [`crate::attribute::carry`]'s standing reason: an engine that
/// refuses one of its knobs refuses it where it was written.
fn carry_lane_options(
  carried: &mut proc_macro2::TokenStream,
  per_lane: &[(syn::Ident, proc_macro2::TokenStream)],
) {
  use proc_macro2::{Delimiter, Group, Punct, Spacing, TokenTree};

  if per_lane.is_empty() {
    return;
  }
  let mut inside = proc_macro2::TokenStream::new();
  for (at, (key, residue)) in per_lane.iter().enumerate() {
    if at > 0 {
      inside.extend(core::iter::once(TokenTree::Punct(Punct::new(
        ',',
        Spacing::Alone,
      ))));
    }
    key.to_tokens(&mut inside);
    inside.extend(core::iter::once(TokenTree::Group(Group::new(
      Delimiter::Parenthesis,
      residue.clone(),
    ))));
  }
  if !carried.is_empty() {
    carried.extend(core::iter::once(TokenTree::Punct(Punct::new(
      ',',
      Spacing::Alone,
    ))));
  }
  carried.extend(core::iter::once(TokenTree::Ident(proc_macro2::Ident::new(
    LANES,
    proc_macro2::Span::call_site(),
  ))));
  carried.extend(core::iter::once(TokenTree::Group(Group::new(
    Delimiter::Parenthesis,
    inside,
  ))));
}

/// The ONE road a block declares, out of the three spellings that can reach it.
///
/// # Two roads is a refusal and not a precedence
///
/// A block that wrote a shorthand AND a `from` described two different documents for one slot, and
/// there is no reading of it that is more likely than the other — picking one would index whichever
/// the emitter happened to prefer and say nothing. The refusal keeps the FROM, so the rest of the
/// pass reads the road that can express the other two.
fn settle_road(
  join: Option<syn::LitStr>,
  multi: Option<syn::Path>,
  declared: Conversion,
  word: &syn::Ident,
  field: &syn::Ident,
  scope: &str,
  errors: &mut Errors,
) -> Road {
  let shorthand = match (join, multi) {
    (Some(separator), None) => Some(Road::Join(separator)),
    (None, Some(_)) => Some(Road::Multi),
    (Some(separator), Some(at)) => {
      errors.push(syn::Error::new_spanned(
        &at,
        format!(
          "`{JOIN}` and `{MULTI}` are both declared in {scope} — they are the two answers to ONE \
           question, and the question is whether a phrase may match ACROSS two of `{field}`'s \
           values. `{JOIN} = {separator:?}` says it may, `{MULTI}` says it may not, and there is no \
           third answer for a road to take",
          separator = separator.value(),
        ),
      ));
      Some(Road::Multi)
    }
    (None, None) => None,
  };
  match (shorthand, declared) {
    (None, Conversion::Default) => Road::Identity,
    (Some(shorthand), Conversion::Default) => shorthand,
    (None, declared) => Road::Declared(declared),
    (Some(shorthand), declared) => {
      errors.push(syn::Error::new_spanned(
        word,
        format!(
          "`{shorthand}` and a declared conversion are both written in {scope} — a slot takes ONE \
           road into its document, and these are two. A shorthand IS a conversion the framework \
           wrote out; keep it where it says what you mean, and keep `from` where it does not",
          shorthand = shorthand.word(),
        ),
      ));
      Road::Declared(declared)
    }
  }
}

/// ONE engine block at a BLOB's head — the field grammar's three walk-time checks, at the coarser
/// grain an artifact family's slot actually has.
///
/// The two checks the field side defers to `engines_of` have no twin here and need none: *this field
/// elected nothing* cannot arise where there is no election, and *there is nothing to fan* is
/// answered by the `fanout` refusal above, which never lets the marker into the model at all.
fn blob_engine(
  meta: &syn::meta::ParseNestedMeta<'_>,
  word: syn::Ident,
  stores: &mut Vec<Engine>,
  errors: &mut Errors,
) {
  // A shipped word is bound already, and to ONE kind of seam. On the other kind it is a category
  // error rather than a portability choice, and it is the one binding question this pass can answer
  // — a free word's binding is the graph root's, two expansions away.
  if let Some(shipped) = EngineKind::of(&word)
    && shipped.serves() != NodeKind::Blob
  {
    errors.push(syn::Error::new_spanned(
      &word,
      format!(
        "`{word}` is the engine `ingraph` ships for {theirs}, and this declaration is an artifact \
         family — the two seams are different traits, so no build binds this word to a store that \
         could hold an object. A store of THIS kind is named by its own word, bound at the graph \
         root with `engines({word}_of_mine = \"path::To::Store\")` unless the framework ships it",
        theirs = shipped.serves().plural(),
      ),
    ));
    attribute::skip_entry(meta);
    return;
  }
  if let Some(first) = stores.iter().find(|engine| engine.word == word) {
    errors.push(syn::Error::new_spanned(
      &word,
      format!(
        "`{first}` is declared more than once — one block per store, exactly as one `persist(…)` \
         names a database once. SEVERAL stores are declared PORTABILITY and the deployment picks \
         one; a repeat names the same store twice and picks nothing",
        first = first.word,
      ),
    ));
    attribute::skip_entry(meta);
    return;
  }
  // The options are the STORE's, so they are carried and not read — `Engine::options`' reason,
  // unchanged by the grain.
  let options = if attribute::has_value(meta) {
    errors.push(named(
      meta,
      format!(
        "`{word}` is a STORE and a store is declared as a BLOCK — write `{word}` for its defaults, \
         or `{word}(…)` to tune it. `{word} = …` reads as an option of this grammar's, and what \
         goes inside a store's parentheses belongs to the store"
      ),
    ));
    proc_macro2::TokenStream::new()
  } else if attribute::has_block(meta) {
    match attribute::verbatim(meta) {
      Ok(options) => options,
      Err(e) => {
        errors.push(e);
        proc_macro2::TokenStream::new()
      }
    }
  } else {
    proc_macro2::TokenStream::new()
  };
  // A blob store holds OBJECTS, not documents, so the conversion grammar has nothing to say here
  // and no word of it is claimed: whatever a store's parentheses hold is that store's own. The
  // word→type road is not claimed either, and for the reason it exists at all: it types a RETRIEVE
  // package, and an artifact family is addressed rather than ranked — it mints no package for a
  // floor to sit in.
  stores.push(Engine {
    options,
    ..Engine::bare(word)
  });
}

/// `extension` in whichever of its written forms — the STATIC one, the BLOCK one, and the two
/// spellings the design refused.
fn extension_word(
  meta: &syn::meta::ParseNestedMeta<'_>,
  extension: &mut Option<Extension>,
  errors: &mut Errors,
) {
  if attribute::has_value(meta) {
    // The BARE ARRAY, refused by name. It is not a syntax slip: an author writing it has a family
    // with several suffixes in mind, and what the list cannot say is WHICH ONE entry 42 gets.
    if meta.input.peek(syn::Token![=]) && meta.input.peek2(syn::token::Bracket) {
      errors.push(named(
        meta,
        "`extension = [\"…\", \"…\"]` lists suffixes and says nothing about which one an entry \
         takes — a set is not a decision, and a family whose addresses end differently has to name \
         what decides. That is the block form: `extension(from = \"<column>\", any_of = [\"…\"])` \
         for a string column, or `extension(from(field = \"<column>\", type = \"path::To::Enum\"))` \
         for an enum one"
          .to_owned(),
      ));
      attribute::skip_entry(meta);
      return;
    }
    match value::literal(
      meta,
      "`extension = \"png\"` is ONE suffix for the whole family, in a string literal",
    ) {
      Ok(suffix) => {
        if extension::admissible_suffix(&suffix.value()) {
          *extension = Some(Extension::Static(suffix));
        } else {
          errors.push(inadmissible_suffix(&suffix));
        }
      }
      Err(e) => errors.push(e),
    }
    return;
  }
  if !attribute::has_block(meta) {
    errors.push(named(
      meta,
      "`extension` says nothing on its own — write `extension = \"png\"` for a family whose \
       addresses all end alike, LEAVE IT OUT for extensionless storage, or `extension(from = …)` \
       to decide the suffix per entry off a column"
        .to_owned(),
    ));
    return;
  }
  // The parenthesized SINGLE VALUE, refused by name: a single fact is a key-value everywhere else in
  // this grammar, and two spellings of one fact is the drift surface the one-spelling law closes.
  if starts_with_literal(meta) {
    errors.push(named(
      meta,
      "`extension(\"png\")` is a single fact written as a block — this grammar writes one of those \
       as a key-value: `extension = \"png\"`. The parentheses are for the form that has structure, \
       where a column decides the suffix per entry"
        .to_owned(),
    ));
    attribute::skip_entry(meta);
    return;
  }

  let mut source = None;
  let mut variants: Vec<syn::LitStr> = Vec::new();
  let mut any_of: Vec<syn::LitStr> = Vec::new();
  let mut with = None;
  let walked = attribute::options(meta, |inner| {
    extension_entry(
      &inner,
      &mut source,
      &mut variants,
      &mut any_of,
      &mut with,
      errors,
    )
  });
  if let Err(e) = walked {
    errors.push(e);
    return;
  }
  let Some(source) = source else {
    errors.push(syn::Error::new_spanned(
      &meta.path,
      "`extension(…)` decides a suffix off a COLUMN and `from` is where it names one — \
       `from = \"<column>\"` for a string column, or `from(field = \"<column>\", type = \
       \"path::To::Enum\")` for an enum one. A block with no column has nothing to decide by",
    ));
    return;
  };
  *extension = Some(Extension::Column(ColumnExtension {
    source,
    variants,
    any_of,
    with,
  }));
}

/// ONE entry inside `extension(…)`.
fn extension_entry(
  inner: &syn::meta::ParseNestedMeta<'_>,
  source: &mut Option<ExtensionSource>,
  variants: &mut Vec<syn::LitStr>,
  any_of: &mut Vec<syn::LitStr>,
  with: &mut Option<syn::Path>,
  errors: &mut Errors,
) -> syn::Result<()> {
  if inner.path.is_ident("from") {
    // `from` is DUAL-MODE, and the two modes are told apart by the SPELLING rather than by anything
    // inferred: `from = "…"` MEANS a string column and `from(…)` means one whose type is named.
    // Key-即-意图 — reading a label tree to guess which an author meant would make one spelling mean
    // two things in two declarations.
    let read = if attribute::has_block(inner) {
      enum_road(inner, errors)
    } else {
      value::literal(
        inner,
        "`from = \"<column>\"` names the entity's own STRING column, in a string literal — an enum \
         column is `from(field = \"<column>\", type = \"path::To::Enum\")`, its type written out",
      )
      .and_then(|literal| {
        // The RAW-IDENT tolerance: an entity's column may be legally called `r#type`, and the word
        // the schema and the database know it by is `type` — so both spellings name it.
        value::named_field(&literal, FROM_NAMES_A_FIELD).map(|field| ExtensionSource::Text { field })
      })
      // Both failures answer with the same sentence, exactly as they did before the tolerance
      // landed.
      .map_err(|e| syn::Error::new(e.span(), FROM_NAMES_A_FIELD))
      .map_or_else(
        |e| {
          errors.push(e);
          None
        },
        Some,
      )
    };
    if let Some(read) = read {
      set_once(
        source,
        read,
        &inner.path,
        "`from` is declared more than once — one suffix is decided by one column",
        errors,
      );
    }
    return Ok(());
  }

  if inner.path.is_ident("variants") {
    return fence(inner, variants, "variants", errors);
  }
  if inner.path.is_ident("any_of") {
    return fence(inner, any_of, "any_of", errors);
  }

  if inner.path.is_ident("with") {
    match value::parse_literal::<syn::Path>(
      inner,
      "`with = \"path::to::fn\"` names the function that renders a suffix, as a path in a string \
       literal — it takes the COLUMN VALUE and answers the suffix, which is what lets ONE function \
       serve the write lane and the read resolver alike",
    ) {
      Ok(path) => set_once(
        with,
        path,
        &inner.path,
        "`with` is declared more than once — one column is rendered one way",
        errors,
      ),
      Err(e) => errors.push(e),
    }
    return Ok(());
  }

  errors.push(attribute::unknown(
    inner,
    "unknown entry in `extension(…)` — it takes `from` (the column), `variants` (which of the \
     column's values are admitted), `any_of` (which suffixes may come out) and `with` (the \
     author's own render). Four keys, each one meaning",
    &["from", "variants", "any_of", "with"],
  ));
  Ok(())
}

/// The refusal both halves of the string road's `from` answer with — a missing or unquoted value,
/// and a string that names no field under either spelling.
const FROM_NAMES_A_FIELD: &str =
  "`from = \"<column>\"` names ONE of the entity's fields, so the string holds a field name";

/// The refusal both halves of the enum road's `field` answer with — a missing or unquoted value,
/// and a string that names no field under either spelling.
const FIELD_NAMES_A_FIELD: &str =
  "`field = \"<column>\"` names ONE of the entity's fields, so the string holds a field name";

/// `from(field = "…", type = "…")` — the enum road, whose type is written out.
fn enum_road(
  inner: &syn::meta::ParseNestedMeta<'_>,
  errors: &mut Errors,
) -> Option<ExtensionSource> {
  let mut field = None;
  let mut ty = None;
  let walked = attribute::options(inner, |entry| {
    if entry.path.is_ident("field") {
      // The enum road's half of the RAW-IDENT tolerance, the same law as `from = "…"`'s: the
      // column this names is one of somebody's struct fields, and a keyword is an ordinary name
      // for one.
      match value::literal(
        &entry,
        "`field = \"<column>\"` names the entity's own column, in a string literal",
      )
      .and_then(|literal| value::named_field(&literal, FIELD_NAMES_A_FIELD))
      {
        Ok(read) => set_once(
          &mut field,
          read,
          &entry.path,
          "`field` is declared more than once in `from(…)` — one suffix is decided by one column",
          errors,
        ),
        // Both failures answer with the same sentence, exactly as they did before the tolerance
        // landed: what a reader needs told is what the value has to BE.
        Err(e) => errors.push(syn::Error::new(e.span(), FIELD_NAMES_A_FIELD)),
      }
      return Ok(());
    }
    if entry.path.is_ident("type") {
      // `type` is a keyword; syn's nested-meta path parser takes it with `Ident::parse_any`, so it
      // arrives as an ordinary one-segment path — the same road `crate` travels on the head.
      match value::parse_literal::<syn::Path>(
        &entry,
        "`type = \"path::To::Enum\"` names the column's own type, as a path in a string literal — \
         it is written out rather than inferred, so the same spelling never means two things",
      ) {
        Ok(path) => set_once(
          &mut ty,
          path,
          &entry.path,
          "`type` is declared more than once in `from(…)` — one column has one type",
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    errors.push(attribute::unknown(
      &entry,
      "unknown entry in `from(…)` — the enum road takes `field` (the column) and `type` (its own \
       type), and nothing else. A STRING column is the shorter spelling, `from = \"<column>\"`",
      &["field", "type"],
    ));
    Ok(())
  });
  if let Err(e) = walked {
    errors.push(e);
    return None;
  }
  match (field, ty) {
    (Some(field), Some(ty)) => Some(ExtensionSource::Enumerated { field, ty }),
    (field, ty) => {
      let missing = if field.is_none() { "field" } else { "type" };
      errors.push(syn::Error::new_spanned(
        &inner.path,
        format!(
          "`from(…)` is the ENUM road and it needs both halves — `{missing}` is not written. The \
           column is `field = \"<column>\"` and its type is `type = \"path::To::Enum\"`; a string \
           column takes the shorter spelling `from = \"<column>\"` instead"
        ),
      ));
      let _ = ty;
      None
    }
  }
}

/// One of the two fence lists — `variants` (input) or `any_of` (output).
fn fence(
  inner: &syn::meta::ParseNestedMeta<'_>,
  into: &mut Vec<syn::LitStr>,
  word: &str,
  errors: &mut Errors,
) -> syn::Result<()> {
  if !into.is_empty() {
    errors.push(syn::Error::new_spanned(
      &inner.path,
      format!("`{word}` is declared more than once — one fence is one set"),
    ));
    attribute::skip_entry(inner);
    return Ok(());
  }
  match value::literals(
    inner,
    &format!("`{word} = [\"…\", \"…\"]` is a list of string literals"),
  ) {
    Ok(read) if read.is_empty() => errors.push(syn::Error::new_spanned(
      &inner.path,
      format!(
        "`{word} = []` fences nothing in — an empty set admits no value at all, which is a family \
         that can store nothing. Leave the word out to say there is no fence"
      ),
    )),
    Ok(read) => *into = read,
    Err(e) => errors.push(e),
  }
  Ok(())
}

/// The judgements a fence pair can only be given once the WHOLE block has been read.
///
/// Both are about words meeting each other rather than about either alone, so neither is answerable
/// inside the walk: `variants` may be written before `from`, and `any_of`'s obligation depends on
/// which road `from` took.
fn extension_fences(column: &ColumnExtension, errors: &mut Errors) {
  match &column.source {
    ExtensionSource::Text { field } => {
      if column.any_of.is_empty() {
        errors.push(syn::Error::new_spanned(
          field,
          "a STRING column needs `any_of` — nothing about a `String` bounds what it holds, so the \
           set of suffixes this family can produce is otherwise unstated, and an address ending in \
           whatever a row happened to contain is not an address anybody can fence. An ENUM column \
           needs no such word: its own variants are the set",
        ));
      }
      if let Some(first) = column.variants.first() {
        errors.push(syn::Error::new_spanned(
          first,
          "`variants` fences the INPUT by naming a type's variants, and a string column has none — \
           what a `String` may hold is not a list this grammar can write. The output fence is \
           `any_of`, which a string column already carries",
        ));
      }
    }
    ExtensionSource::Enumerated { ty, .. } => {
      // The PREFIX check, which is the half this expansion can make: a variant path names the type
      // its `from` named, or it names some other type's. Whether the variant EXISTS is rustc's, and
      // it answers by resolving the emitted reference at the string's own span.
      let prefix = quote::quote!(#ty).to_string().replace(' ', "");
      for variant in &column.variants {
        let written = variant.value().replace(' ', "");
        if !written.starts_with(&format!("{prefix}::")) {
          errors.push(syn::Error::new_spanned(
            variant,
            format!(
              "`{written}` is not a variant of `{prefix}` — `variants` fences the column `from` \
               named, so every entry is a FULL path under that type. A variant of some other enum \
               is not a value this column can hold"
            ),
          ));
        }
      }
    }
  }
  for suffix in &column.any_of {
    if !extension::admissible_suffix(&suffix.value()) {
      errors.push(inadmissible_suffix(suffix));
    }
  }
}

/// What a suffix no address could end with is told.
fn inadmissible_suffix(suffix: &syn::LitStr) -> syn::Error {
  syn::Error::new_spanned(
    suffix,
    format!(
      "`{written}` cannot end an address — a suffix is the tail of ONE name, so it is not empty, \
       holds no path separator, and is neither `.` nor `..`. Each of those would invent a directory \
       level the key never declared",
      written = suffix.value(),
    ),
  )
}

/// Whether a block's contents START with a literal — the `extension("png")` shape, told apart from
/// `extension(from = …)` without consuming either.
fn starts_with_literal(meta: &syn::meta::ParseNestedMeta<'_>) -> bool {
  let fork = meta.input.fork();
  let content = match (|| {
    let content;
    syn::parenthesized!(content in fork);
    syn::Result::Ok(content)
  })() {
    Ok(content) => content,
    Err(_) => return false,
  };
  content.peek(syn::Lit)
}

/// The FANOUT marker's word, spelled once.
const FANOUT: &str = "fanout";

/// ONE field's engines, judged against the election beside them — the two refusals the walk could
/// not make while it was still walking.
///
/// A marker list has no order, so neither *this field elected nothing* nor *there is nothing to fan*
/// is answerable inside the closure: `#[ingraph(lance, knn)]` and `#[ingraph(fanout, lance, hnsw)]`
/// are both legal, and both put the deciding word last. The walk therefore COLLECTS and this judges,
/// which is the same division `elect` already draws for the election itself.
///
/// It runs on every field, elected or not, because the first refusal is exactly about the ones that
/// are not.
fn engines_of(field: &syn::Ident, role: &mut Role, kind: NodeKind, errors: &mut Errors) {
  if !role.elected {
    // AN ENGINE ON PAYLOAD. The field is stored and hydrated and reached by no query, so there is no
    // index for an engine to be the store of — the author declared a home for something that is not
    // going anywhere. The refusal names the marker, because writing it is the OTHER repair and
    // usually the one meant.
    for engine in &role.engines {
      errors.push(syn::Error::new_spanned(
        &engine.word,
        format!(
          "`{field}` names `{word}` and is not elected, so there is no index for that engine to \
           hold — an unmarked field is payload: stored, hydrated, and reached by no query. Mark it \
           `#[ingraph({marker})]` to give it an index, or drop `{word}` and the field stays exactly \
           where it is",
          word = engine.word,
          marker = kind.election().unwrap_or("…"),
        ),
      ));
    }
    if let Some(at) = &role.fanout {
      errors.push(syn::Error::new_spanned(
        at,
        format!(
          "`{field}` is marked `{FANOUT}` and is not elected — the marker says every engine this \
           field declared is live at once, and a field the index does not index declares none. \
           `#[ingraph({marker})]` is what elects it",
          marker = kind.election().unwrap_or("…"),
        ),
      ));
    }
    role.engines.clear();
    role.fanout = None;
    return;
  }
  // NOTHING TO FAN. One engine is not a fan and no engine is not a declaration — the marker's whole
  // content is *all of them*, and *all of them* over fewer than two is the single-write default
  // spelled at length. Refused rather than accepted as a no-op, because a word that means nothing
  // where it is written is a rule its author believes they declared.
  if let Some(at) = &role.fanout
    && role.engines.len() < 2
  {
    errors.push(syn::Error::new_spanned(
      at,
      match role.engines.first() {
        Some(only) => format!(
          "`{field}` declares ONE engine — `{only}` — and `{FANOUT}` has nothing to fan between. \
           The marker makes every declared engine live AT ONCE; with one engine that is what \
           already happens, and the word would be a promise rather than a rule. Name a second \
           engine beside `{only}`, or drop the marker",
          only = only.word,
        ),
        None => format!(
          "`{field}` declares NO engine, so `{FANOUT}` has nothing to fan — the marker makes every \
           engine a field declared live at once, and this field named none. Engines are written \
           BARE beside the election: `#[ingraph({marker}, <engine>, <engine>)]`",
          marker = kind.election().unwrap_or("…"),
        ),
      },
    ));
    role.fanout = None;
  }
}

/// What an election marker written on the wrong KIND of declaration is told.
///
/// It is the retired head word's own wrong-kind refusal, re-aimed: the sentence used to be about
/// `embedding(…)` on the declaration and is now about the marker on a field, so it lands on the
/// marker the author wrote and names the field it was written on. Both markers share it, because the
/// mistake is one mistake read from two sides.
fn wrong_kind(word: &str, owner: NodeKind, kind: NodeKind, field: &syn::Ident) -> String {
  let runs = match word {
    "knn" => "a knn over coordinates",
    _ => "a search over text",
  };
  let instead = match kind {
    NodeKind::Fulltext => {
      "it searches the TEXT its `searchable` fields hold, which is a different question from \
       nearness"
    }
    NodeKind::Vector => {
      "it runs a knn over the coordinates its `knn` fields hold, and coordinates are not text"
    }
    _ => "it answers an address rather than a ranking, so no field of one is run over at all",
  };
  format!(
    "`{word}` elects `{field}` into {runs}, and {article} {noun} runs none — {instead}. The marker \
     is the `{owner}` kind's own",
    article = kind.article(),
    noun = kind.noun(),
    owner = owner.as_str(),
  )
}

/// The container word an election's label writes, and the word it does NOT.
///
/// `list` is the ORDERED, duplicate-bearing container, which is what a set election IS: its members
/// are stored under ORDINALS, and the walk that mints them is the field's own iteration order. `set`
/// in this grammar's collection vocabulary promises unordered-and-deduplicated, which the structure
/// does not have — so it is refused BY NAME and stays reserved for a true unordered container.
const LIST: &str = "list";

/// The near miss the container refusal is written for.
const SET: &str = "set";

/// The VALUE word an election's label is built from, at the top level or inside the container.
const EMBEDDING: &str = "embedding";

/// Whether an entry BEGINS an election label — asked before the reader runs, so an entry that is not
/// one falls through to the field's own projection words and to their refusal.
fn begins_an_election_label(path: &syn::Path) -> bool {
  path.is_ident(EMBEDDING) || path.is_ident(LIST) || path.is_ident(SET)
}

/// The refusal `semantics(fold = …)` gets on a SINGLE election.
fn fold_is_a_sets_word(field: &syn::Ident) -> String {
  format!(
    "`{field}` is labelled `embedding` and `semantics(fold = …)` is the SET election's word — a \
     single embedding has ONE best per query vector, so there is nothing for a fold to fold. The \
     `_with` door that spends a fold is emitted for `list(embedding)` alone, which is why the two \
     facts are one label apart: label the field `list(embedding)` if it carries several, or take \
     the word off"
  )
}

/// The refusal `streams = N` gets on a SINGLE election — [`fold_is_a_sets_word`]'s twin on the
/// protective axis, one word over and for that word's reason.
fn streams_is_a_sets_word(field: &syn::Ident) -> String {
  format!(
    "`{field}` is labelled `embedding` and `{STREAMS} = N` guards the SET election's `_with` road — \
     it bounds how many query vectors ONE REQUEST may ask with, and a single embedding's question \
     is one point, which is a count nothing can inflate. There is no `_with` road here for the \
     guard to stand on: label the field `list(embedding)` if it carries several, or take the word \
     off. What bounds a single-vector road is `{CEILING} = N`, which caps the DEPTH a request may \
     ask for rather than the number of questions"
  )
}

/// The `semantics(…)` BLOCK, read inside `knn(…)` — the wrapper that walks its keys.
fn semantics_word(
  inner: &syn::meta::ParseNestedMeta<'_>,
  fold: &mut Option<Fold>,
  errors: &mut Errors,
) {
  if attribute::has_value(inner) || !attribute::has_block(inner) || attribute::empty_group(inner) {
    errors.push(named(inner, SEMANTICS_IS_KEYED.to_owned()));
    attribute::skip_entry(inner);
    return;
  }
  if let Err(e) = inner.parse_nested_meta(|kind| {
    semantics_kind(&kind, fold, errors);
    Ok(())
  }) {
    errors.push(e);
  }
}

/// ONE entry inside `semantics(…)`: the semantic KIND, and the type that implements it.
///
/// # The key is CLOSED and the value is OPEN, which is the crossing this family is built on
///
/// A *semantics* is a KIND of decision a query makes, and this framework knows which kinds it has
/// doors for — v1 has one, the FOLD. What implements a kind is a type nobody can enumerate, so the
/// key is refused against a vocabulary and the value is carried verbatim for rustc to resolve.
fn semantics_kind(
  kind: &syn::meta::ParseNestedMeta<'_>,
  fold: &mut Option<Fold>,
  errors: &mut Errors,
) {
  if !kind.path.is_ident(FOLD) {
    errors.push(attribute::unknown(kind, UNKNOWN_SEMANTIC_KIND, &[FOLD]));
    attribute::skip_entry(kind);
    return;
  }
  // THE SHORTHAND, told from the custom by the SHAPE of the value: a framework citizen rides BARE
  // in parentheses, exactly as `dedup(hash)` does one family over, and a type the declaring crate
  // owns is QUOTED, exactly as `ask` and `node` are. Mint bare, refer quoted — so which half of the
  // crossing an author is on is legible without a rule they have to remember.
  if attribute::has_block(kind) {
    let walked = kind.parse_nested_meta(|word| {
      shipped_fold(&word, fold, errors);
      Ok(())
    });
    if let Err(e) = walked {
      errors.push(e);
    }
    return;
  }
  match value::parse_literal::<syn::Path>(kind, FOLD_IS_A_QUOTED_PATH) {
    Ok(path) => set_once(fold, Fold::Custom(path), &kind.path, ONE_FOLD, errors),
    Err(e) => errors.push(e),
  }
}

/// ONE WORD inside `fold(…)`: a shipped citizen, or one of the three refusals a near miss gets.
///
/// # The vocabulary is the DEFAULT-ABLE citizens, and the two near misses are refused BY NAME
///
/// The emission builds a declared fold through [`Default`], holding a word and no value, so a
/// citizen reachable by word is one that can be built from nothing. `weighted` cannot — its weights
/// are checked against a query the declaration cannot see — and `mean` is not a citizen at all. Both
/// are told what they ARE rather than that they are unknown, because an author who wrote either had
/// a coherent idea and needs the road to it.
fn shipped_fold(
  word: &syn::meta::ParseNestedMeta<'_>,
  fold: &mut Option<Fold>,
  errors: &mut Errors,
) {
  let Some(spelled) = word.path.get_ident() else {
    errors.push(attribute::unknown(word, &unknown_citizen(), &[]));
    attribute::skip_entry(word);
    return;
  };
  if attribute::has_value(word) || attribute::has_block(word) {
    errors.push(named(word, CITIZEN_IS_A_BARE_WORD.to_owned()));
    attribute::skip_entry(word);
    return;
  }
  attribute::skip_entry(word);
  let spelled = spelled.to_string();
  if spelled == MEAN {
    errors.push(syn::Error::new_spanned(&word.path, MEAN_IS_WITHDRAWN));
    return;
  }
  if spelled == WEIGHTED {
    errors.push(syn::Error::new_spanned(&word.path, WEIGHTED_IS_CONSTRUCTED));
    return;
  }
  let Some(shipped) = Fold::shipped(&spelled) else {
    errors.push(attribute::unknown(word, &unknown_citizen(), &Fold::WORDS));
    return;
  };
  set_once(fold, shipped, &word.path, ONE_FOLD, errors);
}

/// The refusal a SECOND fold gets, however the two were spelled — a word beside a path, two words,
/// or two paths.
const ONE_FOLD: &str = "`fold` is declared more than once on one election — a column has ONE \
                        declaration-level fold, and a caller that wants another passes it at the \
                        query";

/// The withdrawn word, refused by name.
const MEAN: &str = "mean";

/// The citizen that cannot be defaulted, refused by name.
const WEIGHTED: &str = "weighted";

/// What `fold(mean)` is told.
const MEAN_IS_WITHDRAWN: &str = "`mean` is WITHDRAWN and is not a shipped fold — dividing by `m` \
                                 and dividing by how many query vectors this entity actually \
                                 answered are different semantics, and v1 does not bake a \
                                 contestable one. A fold that divides is one you write: it is \
                                 handed every slot INCLUDING the empty ones, so it can see which \
                                 questions went unanswered and own its own divisor. Write it and \
                                 name it here as `fold = \"app::MyMean\"`";

/// What `fold(weighted)` is told.
const WEIGHTED_IS_CONSTRUCTED: &str = "`weighted` ships and cannot be named here — its weights are \
                                       checked AT CONSTRUCTION against the query they weight \
                                       (`Weighted::for_query(&query, weights)`), and a declaration \
                                       has no query to check them against. A shorthand names a \
                                       fold this expansion can build from nothing, which is what \
                                       `Default` means; pass a `Weighted` at the query instead, \
                                       where its arity is a fact somebody can state";

/// The refusal an unknown word inside `fold(…)` gets.
fn unknown_citizen() -> String {
  format!(
    "unknown fold in `fold(…)` — the shorthand names one of the framework's own, and the words are \
     {words}. A fold this framework does not ship is named by PATH instead, as \
     `fold = \"app::MyFold\"`, which is the same mint-bare/refer-quoted split every word in this \
     grammar is under",
    words = list(&Fold::WORDS),
  )
}

/// The refusal a shorthand word carrying anything gets.
const CITIZEN_IS_A_BARE_WORD: &str = "a shipped fold is named by a BARE WORD — `fold(sum)` — \
                                      because it is a member of a closed framework vocabulary, and \
                                      a word with a value or a block is not one. A fold that takes \
                                      arguments is a type you construct and pass at the query";

/// The `semantics(…)` word, which qualifies an election exactly as [`SEARCHABLE`] does.
const SEMANTICS: &str = "semantics";

/// The SUGAR word inside `knn(…)`: this column is reachable by a question, through a tower.
///
/// # The spelling is the fulltext marker's, and that is the point rather than a collision
///
/// `#[ingraph(searchable, words)]` on a text column says *a question can reach this field*, and
/// needs no crossing to say it — the question IS text. A vector column says the same thing and DOES
/// need a crossing, because a question is not coordinates. So the word is one word with one meaning
/// in two positions, and what it takes in each is exactly the difference between them: nothing on
/// the kind that needs none, a tower on the kind that does.
///
/// The alternative was to revive `ask`, which spelled a question road until 2026-08-19. It stays
/// buried: the tombstone beside it is a MEASURED refusal — a chain of N hops erased N error types
/// into one boxed name — and a word that came back with a new expansion would make its own history
/// unreadable, while its refusal, which names the tower road, is the sentence this word answers.
const SEARCHABLE: &str = "searchable";

/// The SUGAR block's ONE key: `searchable(tower = "path::to::Tower")`.
///
/// The key names the KIND OF ITS VALUE, which is why it is not [`QUESTION`]: what an author writes
/// here is a TOWER, and `question` at every other position in this grammar names the question TYPE.
/// A key borrowed from the seat that names a different kind would be the one word carrying two
/// meanings, and the [`ENGINES`] doc is where that law is written down.
///
/// It is also the RECIPE's own word for a bound tower — `tower(<arm>(type = "…"))` in
/// `#[ingraph::search]` — so the sugar and the declaration it forges spell the same thing the same
/// way, which is what a short spelling of a longer one owes its reader.
const TOWER: &str = "tower";

/// The refusal a bare `searchable` inside `knn(…)` gets.
///
/// It states the DIFFERENCE from the fulltext marker rather than the shape alone, because an author
/// who wrote the bare word here wrote the word they know: it is bare over text and it cannot be bare
/// over coordinates, and the sentence is the reason rather than the rule.
const SEARCHABLE_NAMES_A_TOWER: &str = "`searchable` inside `knn(…)` names the TOWER a question is walked through to reach this column — \
   write `knn(searchable(tower = \"path::to::Tower\"))`. It is BARE on a full-text election \
   because a question is already text there and the crossing is the identity; coordinates are not \
   text, so this position has one thing to say and the word says it. What the tower is asked and \
   what it answers are its own `#[ingraph::tower]` declaration's, read through it rather than \
   restated here";

/// The refusal an unknown entry inside `searchable(…)` gets.
const UNKNOWN_SEARCHABLE_ENTRY: &str = "unknown entry in `searchable(…)` — it takes `tower = \"path::to::Tower\"` and nothing else. \
   Every other knob a search has is the RECIPE's, and this word's whole expansion is a \
   `#[ingraph::search]` one: write that recipe by hand the moment a second knob is wanted, and this \
   word stops being the shorter spelling of it";

/// The refusal a second `tower` inside one `searchable(…)` gets.
const ONE_TOWER_ROAD: &str = "`tower` is declared more than once — one election is reached by one \
                              road. A column a SECOND tower also answers is a second \
                              `#[ingraph::search]` recipe, written by hand, because two roads into \
                              one column are two members and two arms rather than two words here";

/// The refusal a `tower` that is not a quoted type gets — MINT BARE, REFER QUOTED.
const TOWER_IS_A_QUOTED_TYPE: &str = "`tower = \"path::to::Tower\"` names the tower that walks a question into this column's \
   coordinates. It is QUOTED because the word names a type this declaration did not mint, which is \
   the law `fold` and `node` are written under; whether that type IS a tower, and whether what it \
   answers meets these coordinates, are rustc's at the binding the expansion writes";

/// The one KIND this vocabulary has: how `m` per-query bests become one score.
const FOLD: &str = "fold";

/// The refusal `semantics` gets when it is written without its key.
const SEMANTICS_IS_KEYED: &str = "`semantics(…)` takes a semantic KIND and the type implementing \
                                  it — `semantics(fold = \"app::MyFold\")`. The key is the kind, \
                                  because a query makes more than one kind of decision and each \
                                  names its own contract; the value is a type, because what \
                                  implements one is not this framework's to enumerate";

/// The refusal an unknown KIND gets.
const UNKNOWN_SEMANTIC_KIND: &str = "unknown entry in `semantics(…)` — the kinds are `fold`, and \
                                     that is the whole vocabulary today: it names HOW the `m` \
                                     per-query bests of a set query become one score. A second kind \
                                     arrives as a second key beside it";

/// The refusal a bare or wrongly-shaped fold gets — MINT BARE, REFER QUOTED.
const FOLD_IS_A_QUOTED_PATH: &str = "`fold = \"app::MyFold\"` names the type that folds this \
                                     election's set queries. It is QUOTED because it refers to a \
                                     type this declaration did not mint, which is the same law \
                                     `ask` and `node` are written under. The type implements \
                                     `FoldSemantics<Score>` and `Default`, and a type that does \
                                     neither is refused by rustc at the path written here";

/// ONE label as written, shape-checked — the whole grammar behind one door.
fn one_label(
  meta: &syn::meta::ParseNestedMeta<'_>,
  field: &syn::Ident,
  errors: &mut Errors,
) -> Option<ElectionLabel> {
  if meta.path.is_ident(SET) {
    errors.push(named(meta, set_is_reserved(field)));
    attribute::skip_entry(meta);
    return None;
  }
  if meta.path.is_ident(EMBEDDING) {
    // A VALUE word carrying an element — the record grammar's own refusal, one vocabulary over.
    if attribute::has_block(meta) && !attribute::empty_group(meta) {
      errors.push(named(
        meta,
        format!(
          "`{EMBEDDING}` names ONE embedding and one embedding has no elements — an element label \
           belongs to the container word, as in `{LIST}({EMBEDDING})`"
        ),
      ));
      attribute::skip_entry(meta);
      return None;
    }
    if attribute::has_value(meta) {
      errors.push(named(meta, BARE_LABEL.to_owned()));
      attribute::skip_entry(meta);
      return None;
    }
    attribute::skip_entry(meta);
    return Some(ElectionLabel::Embedding);
  }
  if attribute::has_value(meta) {
    errors.push(named(meta, BARE_LABEL.to_owned()));
    attribute::skip_entry(meta);
    return None;
  }
  // A bare container, and an empty `()`, are the same declaration: a level with no element.
  if !attribute::has_block(meta) || attribute::empty_group(meta) {
    errors.push(named(
      meta,
      format!(
        "`{LIST}` names a COLLECTION and a collection has elements — write the element's own label \
         inside it, as in `{LIST}({EMBEDDING})`. Every level of a label names its family"
      ),
    ));
    attribute::skip_entry(meta);
    return None;
  }
  let mut held: Option<ElectionLabel> = None;
  let mut extra = false;
  let walked = meta.parse_nested_meta(|inner| {
    let read = if inner.path.is_ident(LIST) || inner.path.is_ident(SET) {
      // The one refusal for the one mistake: the inner word's own complaint would be a second
      // sentence about the same tokens, and it is not the one that answers.
      errors.push(named(&inner, NESTED_CONTAINER.to_owned()));
      attribute::skip_entry(&inner);
      None
    } else if inner.path.is_ident(EMBEDDING) {
      one_label(&inner, field, errors)
    } else {
      errors.push(attribute::unknown(
        &inner,
        ELEMENT_IS_AN_EMBEDDING,
        &[EMBEDDING],
      ));
      attribute::skip_entry(&inner);
      None
    };
    match (read, &held) {
      (Some(read), None) => held = Some(read),
      (Some(_), Some(_)) => extra = true,
      (None, _) => {}
    }
    Ok(())
  });
  if let Err(e) = walked {
    errors.push(e);
  }
  if extra {
    errors.push(named(
      meta,
      format!("`{LIST}(…)` holds ONE element label — a container of two families is not a column"),
    ));
  }
  held.map(|_| ElectionLabel::List)
}

/// The refusal a label written with a VALUE gets.
const BARE_LABEL: &str = "an election's label is a WORD rather than an assignment — write                          `embedding` or `list(embedding)`, which is the same spelling a record's                          field uses for its own kind";

/// The refusal a nested container gets, inherited from the record label grammar's own.
const NESTED_CONTAINER: &str = "no backend carries a collection of collections — an election's                                 members are stored one row apiece under `(owner, ordinal)`, and a                                 set of sets has no second ordinal to be stored under. The element                                 of `list(…)` is `embedding`";

/// The refusal an unknown element word gets.
const ELEMENT_IS_AN_EMBEDDING: &str = "the element of an election's container is `embedding` — the                                        vocabulary here has two words, `embedding` and                                        `list(embedding)`, because a knn runs over coordinates and                                        the only question left is how many of them one entity holds";

/// The refusal `set(embedding)` gets — the near miss, told apart from the word it nearly is.
fn set_is_reserved(field: &syn::Ident) -> String {
  format!(
    "`{SET}` is not the container word — `{field}` holds an ORDERED, duplicate-bearing collection, \
     because its members are stored under ORDINALS minted by walking the field itself, and \
     `{SET}(…)` in this grammar promises unordered and deduplicated. Write `{LIST}({EMBEDDING})`. \
     The word `{SET}` stays reserved for a true unordered container"
  )
}

/// Two of an index's fields, or one of them and a name the emission fixes, reaching ONE method.
///
/// A record's rule in this tier's terms: a column reaches an accessor through a derived shape, so a
/// field called `key` reaches `key_ref` and collides with the borrow of the carried key, and a
/// `copy` field called `new` collides with the constructor. Both would be duplicate definitions
/// inside the expansion, at a span the declaration cannot edit.
///
/// The fixed names are not two, and the engine grammar is why this sentence used to say they were:
/// a `fanout`-marked `title` mints `fan_title`, an election on `image` mints `get_image` and
/// `retrieve_similar_by_image`, a set election mints `fold_by_image`, and every one of them lands on
/// the declaration's own type beside the accessors. WHICH names those are is
/// [`IndexModel::emitted_methods`]'s, asked rather than listed here for the record tier's own
/// reason: a list kept on this side would be a second copy of what the emitter writes, and two
/// copies of a derived-name list is how one of them drifts.
fn emitted_methods(model: &IndexModel, errors: &mut Errors) {
  let mut taken: Vec<&Emitted> = Vec::new();
  for emitted in &model.emitted_methods() {
    // Keyed by the OWNING TYPE as well as the name, now that the roster carries the fuse family:
    // `Options::new` beside `Query::new` is two types' constructors, not a duplicate. Every row of
    // the declaration's own namespace keeps `owner_name = index`, so their rule is unchanged.
    if let Some(first) = taken
      .iter()
      .find(|seen| seen.owner_name == emitted.owner_name && seen.name == emitted.name)
    {
      let why = format!(
        "`{owner}` would declare `{name}` twice — {this}, and {that} already reaches it. rustc \
         reports that duplicate inside the expansion, where nothing names the field that caused it",
        owner = emitted.owner_name,
        name = emitted.name,
        this = emitted.origin,
        that = first.origin,
      );
      // At a DECLARED token, which a method's own ident is not: every derived name is built through
      // `format_ident!`, whose span is the call site — the very span `E0592` already reports at.
      // The FIRST's column stands in where the second is a name the emitter fixed, which is the
      // ordinary shape now that the fixed names outnumber the declared ones: a field spelled like a
      // door is reported at the field, whichever of the two the walk reached second.
      errors.push(
        match emitted.origin.column().or_else(|| first.origin.column()) {
          Some(at) => syn::Error::new_spanned(at, why),
          None => syn::Error::new_spanned(&emitted.owner_name, why),
        },
      );
    }
    taken.push(emitted);
  }
}

/// Two of an index's MARKERS reaching one name — [`emitted_methods`] one level up, and the level
/// where the collision is not a declaration's spelling but the JOIN.
///
/// # What collides, and why no rename opens or closes it
///
/// A slot marker is `<Index><Field><Engine>` in upper camel case, and camel case has no separator:
/// field `a` × engine `b_c` and field `a_b` × engine `c` are two slots with one marker. The election
/// markers are `<Index>By<Field>` and stand in the same scope, so a field called `by` storing to an
/// engine called `image` mints exactly the marker an election on `image` mints. Each is `E0428` —
/// *the name is defined multiple times* — reported inside the expansion, naming two items the author
/// never wrote.
///
/// The durable slot NAME has the same three parts and is `__`-joined, so it keeps the boundary and
/// stays distinct; a TYPE cannot take that join and remain camel case, which is why this is a
/// refusal rather than a respelling. [`IndexModel::emitted_types`] carries that measurement.
///
/// # The sentence names BOTH mints
///
/// A message saying only *a slot's marker is already a slot's marker* would leave an author holding
/// two identical names and no way to tell which pairs made them — so the role each marker arrives
/// with carries its own field and engine, and the caret sits on the FIELD, which is the token that
/// can move. An engine word names a real engine and is not the author's to rename.
fn emitted_types(model: &IndexModel, errors: &mut Errors) {
  let mut taken: Vec<Declared> = Vec::new();
  for declared in model.emitted_types() {
    if let Some(first) = taken.iter().find(|seen| seen.name == declared.name) {
      let why = format!(
        "`{name}` would be {this}, and it is already {that} — a marker joins its parts in upper \
         camel case, which keeps no boundary between them, so two different pairings can mint one \
         name. The durable slot names stay apart (`__`-joined) and the TYPES cannot, so rename the \
         field",
        name = declared.name,
        this = declared.role,
        that = first.role,
      );
      // The candidate's own field, and the first's where a role ever arrives without one. Both
      // markers answer today; the index's own ident is the floor rather than a case, so that a role
      // added to that enumeration later cannot silently lose its caret to the macro's call site.
      let at = declared
        .role
        .at()
        .or_else(|| first.role.at())
        .unwrap_or(&model.index);
      errors.push(syn::Error::new_spanned(at, why));
    }
    taken.push(declared);
  }
}

/// Derived indexes are concrete, for the reason every declaration in this family is: a field's type
/// is read straight off the declaration, and a type parameter has none until it is substituted.
fn concrete(generics: &syn::Generics, kind: NodeKind, errors: &mut Errors) {
  let why = format!(
    "generic {plural} are not supported — the declaration must be concrete, because a field's type \
     is read straight off it and is what the projection audit checks against",
    plural = kind.plural(),
  );
  if !generics.params.is_empty() {
    errors.push(syn::Error::new_spanned(generics, why));
  } else if let Some(clause) = &generics.where_clause {
    errors.push(syn::Error::new_spanned(clause, why));
  }
}

/// The declaration's named fields — the only shape a derived index may take, since a projection
/// names the field it fills.
fn named_fields(input: &syn::DeriveInput, kind: NodeKind) -> syn::Result<&syn::FieldsNamed> {
  match &input.data {
    syn::Data::Struct(data) => match &data.fields {
      syn::Fields::Named(named) => Ok(named),
      syn::Fields::Unnamed(_) | syn::Fields::Unit => Err(syn::Error::new_spanned(
        &input.ident,
        format!(
          "{article} {noun} must be a struct with named fields — `upstream(…)` fills a field BY NAME, \
           and a positional one has none to be filled by",
          article = kind.article(),
          noun = kind.noun(),
        ),
      )),
    },
    syn::Data::Enum(_) | syn::Data::Union(_) => Err(syn::Error::new_spanned(
      &input.ident,
      format!(
        "`#[ingraph::{macro}]` supports structs only",
        r#macro = kind.as_str(),
      ),
    )),
  }
}