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
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
//! A decorated declaration in, a [`RecordModel`] out — and every rule checked on the way.
//!
//! The record-level grammar is ONE BLOCK PER EMITTED TYPE, options inside — with the STORE WORDS
//! bare beside them, storage being the record's essence rather than one of its axes:
//!
//! ```text
//! #[ingraph(
//!   crate = "path::to::ingraph",                                 // governs all emission
//!   lineage(fields(media_id, video_id), rename = "TrackScope"),  // the lineage type
//!   key(rename = "TrackAddress"),                                // the key type
//!   table = "video_tracks", sqlite, postgres(schema = "public"), // the stored rows
//!   graphql(async_graphql, output(rename = "Track")),            // the wire face
//! )]
//! ```
//!
//! `key(…)` has no `fields`, because `key = lineage ⊕ id` is a law rather than a declaration. And
//! there is NO flat shorthand: `lineage(a, b)` is refused. A dual grammar would mean two parse
//! paths, two error surfaces, and a genuine reading ambiguity the day a struct has a field called
//! `fields`.
//!
//! # FUSION: several upstreams, one of them the parent
//!
//! A node driven by one upstream and descending from nothing writes `subscribe = "path::To::Node"`.
//! A node that JOINS several writes one `upstream(…)` entry apiece, and exactly one of them carries
//! the bare word `key`:
//!
//! ```text
//! #[ingraph::operator(
//!   upstream(node = "media::Frame", key),                    // the designated key parent
//!   upstream(node = "asr::Segment"),                         // joined, and contributing no identity
//!   lineage(fields(media_id, frame(source = "id"))),       // the parent's key, mirrored
//! )]
//! ```
//!
//! The macro's own argument list is the container holding THESE entries — the identity ones. The
//! node's INTAKE has a container of its own, `subscribe(…)`, and the two are different questions
//! rather than two spellings of one: these say where a key comes from, and those say how messages
//! arrive.
//!
//! **The mirror is DECLARED, not injected**, and the boundary is *indexes inject, records declare*.
//! A derived index's key has one consumer, so its expansion mints the carried field and the
//! declaration never spells it. A fusing node's lineage columns are query surface — filters name
//! them, cursors carry them, foreign keys point at them — and a column a user's query spells is one
//! that user's declaration must have spelled. What the derive adds is the CHECK, emitted as an
//! equation from the parent's key to this node's lineage; see [`RecordModel::key_parent`] for the
//! three errors it turns a wrong claim into.
//!
//! The per-field `source = "…"` is written only where the names diverge, and same-name columns map
//! free. It exists because one divergence is forced: a parent's key ends in ITS id, and `id` is a
//! name this node's own id already holds — so the column takes the domain's word for what it means
//! here (`frame`) and says which parent field it equals.
//!
//! Provenance of the upstreams that are NOT the parent is opt-in, spelled as ordinary `ref = "…"`
//! fields. Nothing is derived from the topology: a column exists because a field carried a marker.
//!
//! **The verb rule: `from` BUILDS the projection a block is about, `into` LEAVES it** — relative to
//! the projection, never to the domain. So `<db>(from)` is domain → row (a write) and `<db>(into)`
//! is row → domain (a read), which is what the emitted `impl From<Record> for Row` says literally.
//! One rule across every family beats one convention per family.
//!
//! The STORE WORDS are the one head vocabulary whose entries are themselves blocks: each names a
//! DATABASE, and the set of them is the storage selection. Two scopes, therefore — the head's own
//! and each database's — and one rule deciding which an option belongs to — an option is COMMON only if every database ingraph could support has it, so
//! `table` and `rename` are common while `indexed`, `schema`, `collection`, `type` and the
//! conversions are each one database's. A per-database option written in the common scope is
//! refused by name rather than accepted and applied to all four.
//!
//! Which scope an option belongs to is a fact about the OPTION and not about the field carrying it,
//! so a KEY field's block is read by those same two rules. The key type's columns are RUST fields
//! carrying the record's declared types, and a stored name and a stored type are the ROW's — so
//! there is nothing on a key for a database's `rename` or `type` to contradict.
//!
//! # THE CONTAINER DECLARES AND A BARE FIELD PARTICIPATES; words only SUBTRACT
//!
//! One law at both faces. A record IS rows, so its data fields ARE the row: a field writing nothing
//! is a column in every database the head names. A declaration naming a wire backend has said what
//! it publishes — everything it holds — so a field writing nothing is a field on every face it
//! declared. What a field writes is a REFINEMENT of a place it already has, or a SUBTRACTION from
//! it; no word grants one.
//!
//! That inverts a per-field explicitness this grammar carried out of the era when one macro served
//! every tier. `persist` and `graphql` were participation MARKERS then, and both are retired at the
//! field seat: a word that grants what silence already grants costs the next reader a lookup and
//! answers it with nothing. Their refining vocabularies survive whole — the storage words at the
//! field's own level, where the head writes its own, and the wire words inside `graphql(…)`.
//!
//! What the inversion cannot do is turn silence into a DECLARED absence, and that is a fact the read
//! side needs: a row missing a field the record declares cannot rebuild one, so the reverse
//! conversion is not emitted, `Record<Db>` has no row to raise, and the whole SQL query face goes
//! with it. A record holding an engine-resident `Embedding` is the shape that measured it (#296's
//! letter 12).
//!
//! `skip` is the word that turns the silence into a declaration — *this field is not a column, and
//! here is what a read supplies instead* — so the row carries every field it is answerable for and
//! the query face survives. One seat on the storage axis, two on the wire:
//!
//! ```text
//! #[ingraph(skip)]                                // no column in ANY persisted database
//! #[ingraph(graphql(skip))]                       // absent from every wire backend
//! #[ingraph(graphql(async_graphql(skip)))]        // absent from THAT backend
//! ```
//!
//! The storage seat takes the FILL, and the spelling is **serde's own, verbatim**:
//! `#[ingraph(skip(default = "path::to::fn"))]`, where the path is a `fn() -> T`. Written bare, the
//! fill is `Default::default()` — `E0277` at the `skip` word where the field's type has none. The
//! precedent is serde's for the reason a precedent is ever taken: an author who has written
//! `#[serde(default = "…")]` has already learnt this grammar, and a second spelling of one idea is a
//! second thing to remember. The WIRE seats take no fill, a field the schema never names having no
//! read to supply.
//!
//! # There is NO per-database skip, and a per-database shape is a SECOND RECORD
//!
//! A record is ONE STORAGE SHAPE across every database it declares: a column is in all of them or in
//! none. The word therefore has no `<db>(skip)` seat, and the two spellings that would ask for one —
//! `<db>(skip)`, and a bare `<db>` naming FEWER databases than the head does — are refused by name
//! rather than read as one.
//!
//! Where two stores really want different columns, the difference is the GRAPH's to state and not a
//! field word's — declare a SECOND RECORD as a PARALLEL SUBSCRIBER of the same upstream, lean in one
//! store and fat in the other, each uniform across its own. That is the storage-as-co-subscriber
//! doctrine read at the record grain, and it is the answer: a per-field per-database word would put
//! a topology decision inside a column, where nothing about the pipeline could see it.
//!
//! What each axis removes is its own. The storage word takes the column out of the ROW, the
//! statement and the comparison; the wire word takes the field out of the OUTPUT OBJECT, the FILTER
//! and the ORDER-BY's SCHEMA — every vocabulary a CLIENT could name it in, because a column a client
//! cannot read but can order by is one it reads back a page at a time. The order-by's Rust TYPE
//! keeps every stored column, a Rust caller being no client. Identity is unskippable on both axes:
//! an address whose step is missing addresses nothing.
//!
//! The STORE WORDS are the record's ONE storage, and the reason is a topology one: one node holds
//! one storage, so an index over these rows and a store of artifacts beside them are each a node of
//! their own with a macro of their own. Every spelling of the three that left — `fulltext(…)`,
//! `vector(…)`, `blob(…)` and their field markers — is refused BY THAT REASON, see
//! [`owns_one_storage`], because an author who wrote one has a concrete idea and the useful
//! answer is which declaration now carries it. Those three macros SHIP — see [`crate::index`] — so
//! the refusals name a declaration that exists rather than a round to wait for. What stays is the
//! row: a `Vec<u8>` COLUMN is a value this record persists, spelled `bytes`, and it is not the
//! artifact family.
//!
//! They sit BARE at the head, where they used to sit inside a wrapper, and the
//! principle is the ladder's: storage is a record's ESSENCE — a record IS rows, which is the whole
//! of what separates it from an `entity` — and an essence sits bare where an OPTIONAL axis takes a
//! block. `graphql(…)` is optional and keeps its parentheses. A record naming NO store is refused,
//! and the wrapper is refused by name carrying the migration.
//!
//! A store word is refused the same way on a node that holds no rows: THIS pass serves the three
//! node kinds that MINT an id — `operator`, `entity` and `record` — and only the last has rows, which
//! [`NodeKind::holds_rows`] answers. The three that carry a borrowed key have a pass of their own,
//! for the reason their key is different: there is no `id`, no `*Key` and no `*Lineage` to parse.
//!
//! The progress ledger has NO block, because it carries nothing the rest of the declaration has not
//! already said. One would name DATABASES and nothing else, and it has none to choose: a ledger's
//! control tables live in the row store's pool, so the hosts ARE the store words. What is left
//! is existence, and that is derived too — a ledger certifies the unit's close, which every stored
//! record has. Writing the block is refused BY THAT REASON rather than as an unknown word: an author
//! who writes one has a concrete idea, and the useful answer is where the idea is already recorded.
//!
//! A PUBLISHED FIELD OF A ROW-HOLDING NODE NEEDS A STORED COLUMN, because a wire field with no
//! stored column cannot be populated by a read. See [`stored_in`]. With both participations inverted
//! there is exactly one way to reach it: `skip` beside a face the field never left. That pair is
//! refused BY NAME — stored nowhere and yet on the schema would answer every read with `null` — and
//! `graphql(skip)` is what withdraws the field from the face as well. The rule is asked of a node
//! that HOLDS ROWS and of no other: a rowless tier answers out of the value itself and has no column
//! for the question to be about. The refusal carries its own census pin; the day a declaration can
//! name a function that COMPUTES a published field, it is what to lift.
//!
//! Hand-rolled over `syn` 3 rather than delegated to `darling`, which is still on `syn` 2: two
//! `syn` majors inside one parsing crate is the worse trade. What that costs is the property a
//! hand-rolled parser loses first — one pass reporting EVERY offending attribute instead of
//! stopping at the first — so [`Errors`] carries it explicitly, on `syn::Error::combine`.

use ingraph_codegen::prelude::*;
use quote::{ToTokens as _, format_ident};
// `parse_any`/`unraw`, which is how the `enum` marker word is read: see `marker`.
use syn::ext::IdentExt as _;

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

/// 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,
  options: &[syn::Attribute],
  kind: NodeKind,
) -> syn::Result<RecordModel> {
  let record = &input.ident;
  let mut errors = Errors::default();
  // The macro's own arguments carry the declaration's options; an `#[ingraph(…)]` beside it is the
  // derive's spelling and is a named migration rather than a thing nobody reads.
  crate::host::refuse_a_moved_option_block(&input.attrs, &mut errors);
  let Options {
    krate,
    key_rename,
    lineage: lineage_block,
    persist: persist_block,
    graphql: graphql_block,
    derived: derived_block,
    locate: locate_block,
    implements,
    subscribe,
    subscribe_at,
    subscriptions,
    products,
    polls,
    teardown,
    asynchronous,
    streaming,
    autonomous,
    attributed,
    options: options_type,
    remote,
    construction,
    upstreams,
    errors: mut declared_errors,
    tracing,
    receipt,
  } = record_options(options, kind, &mut errors);
  concrete(&input.generics, kind, &mut errors);
  // THE REWRITE'S OWN CHECKS, before a field is read: the item this macro is about to REPLACE may
  // not carry a representation of its own, and a manifest field may not carry an attribute the
  // rewrite has nowhere to put. See [`crate::remote`], which owns both sentences.
  if remote.is_some() {
    crate::remote::refuse_a_representation(&input.attrs, &mut errors);
  }

  let key_name = key_rename
    .clone()
    .unwrap_or_else(|| default_key_name(record));
  let lineage_rename = lineage_block
    .as_ref()
    .and_then(|block| block.rename.clone());
  let lineage_name = lineage_block.as_ref().map(|_| {
    lineage_rename
      .clone()
      .unwrap_or_else(|| default_lineage_name(record))
  });

  let fields = match named_fields(input, kind) {
    Ok(fields) => fields,
    Err(terminal) => return Err(errors.seal(terminal)),
  };

  // Every field's markers, gathered once — the scoped renames are needed long after the walk.
  let mut marked: Vec<(&syn::Field, Markers)> = Vec::new();
  let mut id: Option<&syn::Field> = None;
  for field in &fields.named {
    if field.ident.is_none() {
      continue;
    }
    let markers = field_markers(&field.attrs, kind, &mut errors);
    if remote.is_some() {
      crate::remote::refuse_an_unplaceable_attribute(field, &mut errors);
    }
    if markers.id.is_some() {
      match id {
        Some(first) => errors.push(syn::Error::new_spanned(
          field.ident.as_ref().expect("a named field"),
          format!(
            "{article} {noun} needs exactly one `#[ingraph(id)]` field; `{}` already carries it",
            first.ident.as_ref().expect("a named field"),
            article = kind.article(),
            noun = kind.noun(),
          ),
        )),
        None => id = Some(field),
      }
    }
    marked.push((field, markers));
  }
  let of = |name: &syn::Ident| {
    marked
      .iter()
      .find(|(field, _)| field.ident.as_ref() == Some(name))
  };

  // The DESIGNATED KEY PARENT, settled before the path is walked: whether a lineage field may carry
  // a mirror at all is decided by whether this node fuses, and the sentence for one that does not
  // has to name the boundary rather than the word.
  let parent = key_parent(record, kind, &upstreams, subscribe_at.as_ref(), &mut errors);
  // The two topology declarations, settled beside the identity one: the fan-in the container shapes,
  // and the products this node puts on its edges.
  let subscriptions = fan_in(record, subscriptions, &mut errors);
  let products = declared_products(record, products, &mut errors);
  let polls = poll_sources(record, polls, &mut errors);
  // THE FACE WORD's two cross-word rules, read once the whole attribute has been walked: which
  // KINDS may wear the streaming pair, and which word on the buffered side cannot stand beside
  // it. Neither is answerable inside the walk — a `poll(…)` entry may be written after the word
  // that refuses it, and a walk that refused at the token would report the pair only in one of
  // the two orders an author can type it in.
  streaming_word(kind, streaming.as_ref(), polls.as_ref(), &mut errors);
  autonomous_word(kind, autonomous.as_ref(), streaming.as_ref(), &mut errors);

  // The lineage path, still in the RECORD's own terms — the two scopes name it separately below.
  // Each step carries the parent-key field it mirrors, which is the record field's own name unless
  // `source = "…"` said otherwise.
  let mut path: Vec<(&syn::Field, syn::Ident)> = Vec::new();
  for LineageField { name, from } in lineage_block.into_iter().flat_map(|block| block.fields) {
    if from.is_some() && parent.is_none() {
      errors.push(syn::Error::new_spanned(
        &name,
        format!(
          "`{name}(source = \"…\")` maps a column onto a field of the PARENT's key, and {article} \
           {noun} that does not fuse has no designated parent to map onto — its lineage is its own \
           columns. The designation is `upstream(node = \"path::To::Upstream\", key)`",
          article = kind.article(),
          noun = kind.noun(),
        ),
      ));
    }
    if id.is_some_and(|field| field.ident.as_ref() == Some(&name)) {
      errors.push(syn::Error::new_spanned(
        &name,
        format!(
          "the `#[ingraph(id)]` field `{name}` cannot also be a lineage field — a key is \
           lineage ⊕ the id, and the id is already its last column"
        ),
      ));
    } else if path
      .iter()
      .any(|(field, _)| field.ident.as_ref() == Some(&name))
    {
      errors.push(syn::Error::new_spanned(
        &name,
        format!("`{name}` is named twice in `lineage(fields(…))` — a lineage field is one column"),
      ));
    } else if let Some((field, _)) = of(&name) {
      path.push((field, from.unwrap_or(name)));
    } else {
      errors.push(syn::Error::new_spanned(
        &name,
        format!("`lineage(fields(…))` names fields of this struct — `{name}` is not one"),
      ));
    }
  }
  let steps: Vec<&syn::Ident> = path
    .iter()
    .map(|(field, _)| field.ident.as_ref().expect("a named field"))
    .collect();

  // The ADDRESS's own sources, gathered here because here is where the two halves are known: the
  // `id` marker and the lineage walk. The storage pass reads it so that a step whose narrowing has
  // already been refused by name is not told a second time that its read has no answer — one
  // mistake, one sentence.
  let mut address: Vec<syn::Ident> = Vec::new();

  // A scoped rename names a column in ONE emitted type, so it needs that type to have a column to
  // name. Unlike `copy` — which gained a subject the day the record's own impl was emitted — these
  // can never gain one: a data column's rename will be its own scope when the persisted row is emitted.
  for (field, markers) in &marked {
    let name = field.ident.as_ref().expect("a named field");
    let in_key = id.is_some_and(|id| id.ident.as_ref() == Some(name)) || steps.contains(&name);
    if in_key {
      address.push(name.clone());
    }
    let in_lineage = steps.contains(&name);
    if let Some(rename) = &markers.key
      && !in_key
    {
      errors.push(no_subject(
        &rename.at,
        name,
        "key",
        "the `#[ingraph(id)]` field and the fields named in `lineage(fields(…))`",
      ));
    }
    if let Some(rename) = &markers.lineage
      && !in_lineage
    {
      errors.push(no_subject(
        &rename.at,
        name,
        "lineage",
        "the fields named in `lineage(fields(…))`",
      ));
    }
    // THE LABEL IS AN OVERRIDE, and the mandatory rule that stood here is gone.
    //
    // It read *a field that is stored or exposed names the interpretation its type is read under*,
    // and its subject was the set of fields carrying `persist` — which is now every data field a
    // record has. Kept, it would have demanded a word on all of them; and the word it demanded is
    // one the TYPE already answers: `filter_of` resolves an unlabelled column through
    // `<T as DefaultMarker>::Marker`, whose own doc calls itself *the INFERENCE, and it is what
    // keeps the common case free of annotation*. A type with no row there is `E0277` NAMING that
    // type, which is a better report than a macro error naming a field.
    //
    // What was lost with it is nothing: the sentence's teaching half — an `Embedding` is
    // ENGINE-RESIDENT and wears `skip` — is a note on `Carrier`'s own
    // `#[diagnostic::on_unimplemented]`, written there first and duplicated here. The refusal now
    // arrives at the trait that knows it, at the type it is about.
    //
    // What STAYS is the exemption's other side, and the one cell the expansion genuinely cannot
    // infer. A key-side column writes no label at all, its vocabulary being the sealed `Id` trait,
    // and a label on one is refused by name. The cell is `sortable`, where the word orders
    // a COLLECTION and only a declaration can say a column is one — see
    // [`refuse_a_storage_word_no_label_can_order`], which used to defer to the rule deleted here and
    // answers for itself now.
    if let (Some(label), true) = (&markers.label, in_key) {
      errors.push(label.refuse(key_side_label(name)));
    }
    refuse_a_storage_word_no_label_can_order(markers, in_key, &mut errors);
    refuse_a_skip_the_record_cannot_survive(markers, name, in_key, in_lineage, &mut errors);
  }

  // One column per scope, each under the name ITS type gives it.
  let projections: Vec<(syn::Ident, Projection)> = marked
    .iter()
    .map(|(field, markers)| {
      let name = field.ident.clone().expect("a named field");
      let projection = markers.projection(&name, &mut errors);
      (name, projection)
    })
    .collect();
  let projection = |name: &syn::Ident| {
    projections
      .iter()
      .find(|(marked, _)| marked == name)
      .map_or(Projection::Borrowed, |(_, projection)| *projection)
  };

  let column = |field: &syn::Field, scope: Scope| {
    let source = field.ident.clone().expect("a named field");
    let markers = of(&source).map(|(_, markers)| markers);
    let rename = markers.and_then(|markers| match scope {
      Scope::Key => markers.key.as_ref(),
      Scope::Lineage => markers.lineage.as_ref(),
    });
    Column {
      name: rename.map_or_else(|| source.clone(), |rename| rename.name.clone()),
      project: projection(&source),
      ty: field.ty.clone(),
      source,
    }
  };

  let key_path: Vec<Column> = path
    .iter()
    .map(|(field, _)| column(field, Scope::Key))
    .collect();
  let lineage_columns: Vec<Column> = path
    .iter()
    .map(|(field, _)| column(field, Scope::Lineage))
    .collect();
  let key_id = id.map(|field| column(field, Scope::Key));

  // The MIRROR list, built from the settled lineage columns so the equation names the type the way
  // the type is emitted: a `lineage(rename = "…")` moved the column, and the struct literal has to
  // write the name it moved to.
  let mirrors: Vec<Mirror> = lineage_columns
    .iter()
    .zip(&path)
    .map(|(column, (_, from))| Mirror {
      column: column.name.clone(),
      from: from.clone(),
    })
    .collect();

  // The ALIAS namespaces this declaration's own names are held out of, settled once: the union of
  // every database's declared prefix, plus the framework's wherever one still defaults. It is built
  // HERE because the key and lineage columns below are the first names checked against it, and it is
  // read again at the row's own columns and tables — one fence, so a name refused in one scope
  // cannot be accepted in another.
  let fence = alias::Fence::over(
    persist_block
      .iter()
      .flat_map(|block| block.databases.iter())
      .map(|db| db.aliases.prefix.as_deref()),
  );

  // Both checks are on the EFFECTIVE name, per scope: a rename walks past a check on the field's
  // Rust name, and it is the emitted name that reaches a `CREATE TABLE`.
  for (type_name, columns) in [
    (key_name.to_string(), key_path.iter().chain(key_id.as_ref())),
    (
      lineage_name
        .as_ref()
        .map_or_else(String::new, ToString::to_string),
      lineage_columns.iter().chain(None),
    ),
  ] {
    if type_name.is_empty() {
      continue;
    }
    let mut taken: Vec<&syn::Ident> = Vec::new();
    for column in columns {
      column::refuse_framework_namespace(&fence, &column.name, &mut errors);
      if taken.contains(&&column.name) {
        errors.push(syn::Error::new_spanned(
          &column.name,
          format!(
            "`{type_name}` would have two columns called `{}` — a rename is scoped to one type, \
             and within it every column needs its own name",
            column.name
          ),
        ));
      }
      taken.push(&column.name);
    }
  }

  let (Some(id), Some(key_id)) = (id, key_id) else {
    return Err(errors.seal(syn::Error::new_spanned(
      record,
      format!(
        "{article} {noun} needs exactly one `#[ingraph(id)]` field; this struct declares none",
        article = kind.article(),
        noun = kind.noun(),
      ),
    )));
  };
  let id_name = id.ident.clone().expect("a named field");

  // EVERY field, in declared order: the record gets an inherent impl of its own, so a data field
  // reaches emission too. Identity-bearing ones — the id and each lineage step — get getters only.
  // The record keeps its own Rust names; a scoped rename never touches them.
  // A fusion whose lineage block is missing has nothing to check its parent against, and the
  // equation is the whole of what the designation buys — so the two are declared together or
  // neither is. Reported here rather than at `key_parent`, which runs before the block is resolved.
  let upstreams = match parent {
    Some(Mode::Fused { parent, others }) if mirrors.is_empty() => {
      errors.push(syn::Error::new_spanned(
        record,
        format!(
          "{article} {noun} that designates a key parent has no lineage to check against — its \
           lineage IS that parent's key, mirrored column by column, so the block naming the columns \
           is `lineage(fields(…))` and a fusion writes one. Where a column's name differs from the \
           parent's, `<field>(source = \"…\")` maps it",
          article = kind.article(),
          noun = kind.noun(),
        ),
      ));
      let _ = (parent, others);
      None
    }
    Some(Mode::Fused { parent, others }) => Some(Upstreams::Fused(Fusion {
      parent,
      others,
      mirrors,
    })),
    // A FAN-IN's ancestry is not columns, so a `lineage(fields(…))` beside it names a path this
    // node does not have. Refused rather than merged: the two shapes answer the same question, and
    // a declaration carrying both has said which upstream every row descends from AND that it
    // depends on the row.
    Some(Mode::Fanned(fanned)) => {
      if !mirrors.is_empty() {
        errors.push(syn::Error::new_spanned(
          record,
          format!(
            "{article} {noun} drawing from several upstreams with none designated `key` has its \
             ancestry decided per ROW — each row descends from whichever upstream produced it — so \
             its lineage is a CHOICE among them and `lineage(fields(…))` names a path it does not \
             have. Designate one upstream with `key` to make the upstreams JOIN, whose lineage is \
             that parent's key and is spelled by that block",
            article = kind.article(),
            noun = kind.noun(),
          ),
        ));
      }
      Some(Upstreams::Fanned(fanned))
    }
    None => None,
  };

  let own = marked
    .iter()
    .map(|(field, markers)| {
      let name = field.ident.clone().expect("a named field");
      let identity = name == id_name || steps.contains(&&name);
      if identity {
        crate::attribute::refuse_a_conditional_identity(field, &mut errors);
      }
      if markers.reference().is_some() {
        crate::attribute::refuse_a_conditional_reference(field, &mut errors);
      }
      Field {
        column: Column {
          project: projection(&name),
          ty: field.ty.clone(),
          source: name.clone(),
          name,
        },
        identity,
        marker: markers.label.as_ref().map(Written::marker),
        sortable: markers.storage.sortable.is_some(),
        indexed: markers.storage.indexed.is_some(),
        reference: markers.reference(),
        skip: markers.skip.as_ref().map(SkipField::fill),
        // Gathered in the REWRITE mode alone, where the field the author documented is about to
        // stop existing — see [`crate::remote::docs`], and [`Field::docs`] for where they land.
        docs: if remote.is_some() {
          crate::remote::docs(field)
        } else {
          Vec::new()
        },
        // Gathered in BOTH modes. A `#[cfg]` on an ordinary field reaches the ECHOED field already
        // — the host forwards it — and reached nothing else, which is the orphan column this seat
        // is here to close; a manifest field's reached nothing at all.
        condition: crate::attribute::condition(field, remote.is_some(), &mut errors),
        build: markers.build.clone().unwrap_or_default(),
      }
    })
    .collect();

  // THE CONSTRUCTION SUITE's two CROSS-SEAT rules, checked here because neither can be checked at
  // the walk that reads its words: one asks whether the declaration wraps anything, and the words
  // it judges are on the fields; the other asks whether a field's argument list exists, and what
  // answers is on the declaration.
  crate::construct::refuse_without_a_remote(
    remote.as_ref(),
    construction
      .as_ref()
      .and_then(|written| written.at.as_ref()),
    marked
      .iter()
      .filter_map(|(_, markers)| markers.build.as_ref()?.at.clone()),
    kind.noun(),
    &mut errors,
  );
  // The DEFAULT LAW is the absent word's meaning rather than an absence — see `Construction` — so a
  // declaration that described no protocol carries the value that emits what the rewrite mode
  // always emitted.
  let construction = construction.unwrap_or_default();
  let described: Vec<(syn::Ident, Build)> = marked
    .iter()
    .filter_map(|(field, markers)| {
      Some((
        field.ident.clone().expect("a named field"),
        markers.build.clone()?,
      ))
    })
    .collect();
  crate::construct::refuse_a_homeless_argument(&construction, &described, &mut errors);

  // The PERSIST cells, read off the record-level database blocks before they are consumed: a row's
  // own conversions and the wire crossings all answer per (crossing, database), and this is the one
  // that is spelled inside `persist(…)` rather than inside `graphql(…)`.
  for database in persist_block.iter().flat_map(|block| &block.databases) {
    // BOTH legs' cells are admitted, and each types one impl: `try_into` types the row's
    // `TryFrom<Row> for E`, which every query lane spends, and `try_from` types the
    // `TryFrom<E> for Row` the write lane crosses through. The second was a named refuse-until
    // while nothing stored a record; `query::sql::write` is the consumer it was waiting for.
    for (leg, cell) in [
      (Crossing::PersistRead, database.into.cell.clone()),
      (Crossing::PersistWrite, database.from.cell.clone()),
    ] {
      if let Some(path) = cell {
        declared_errors.push(BackendError {
          crossing: leg,
          kind: database.kind,
          path,
        });
      }
    }
  }
  let persist = persist_model(
    record,
    kind,
    persist_block,
    &fence,
    &marked,
    &address,
    &mut errors,
  );
  // A FAN-IN's rows are the SPLIT LAYOUT, and the STORAGE half of it ships: `ingraph`'s descriptor
  // carries the discriminant and one provenance table per upstream, the DDL renders the foreign key
  // that ties them, and the write lane stores the common row and the one matching provenance row
  // inside one transaction. What has not arrived is the READ, and the refusal says which read and
  // why it is not an optimisation — see the fixture, which carries the measurement.
  if upstreams.as_ref().and_then(Upstreams::fanned).is_some() && persist.is_some() {
    errors.push(syn::Error::new_spanned(
      record,
      format!(
        "{article} {noun} drawing from several independent upstreams stores its rows in the SPLIT \
         LAYOUT — one common table holding the id, the discriminant and the uniform payload, and \
         one provenance table per upstream holding that variant's ancestors — and the READ that \
         raises a common row back into a {noun} has not arrived. Its ancestry is a CHOICE among the \
         upstreams, and a choice has no empty state to decode into: a collection's row starts out \
         empty and a second statement fills it, where this one has nothing to start out as, so the \
         provenance read is what makes the row constructible rather than a way to make it complete. \
         Designate one upstream with `key` to make the upstreams JOIN, whose lineage is columns of \
         the row itself and ships today",
        article = kind.article(),
        noun = kind.noun(),
      ),
    ));
  }

  let progress = progress_model(persist.as_ref());

  // The ORDER-BY's name is settled BEFORE the wire face, because the type is no longer one of its
  // own: an ordering term is mechanical from the stored columns and its lowering is pure SQL, so a
  // persist-only record has one. What still lives inside `graphql(…)` is the RENAME — the word has
  // always been written there, and moving it would break every declaration that spells one — so
  // this reads the block for the override and defaults from the record's own base name.
  let order_by = order_by_name(record, graphql_block.as_ref());

  // THE SENDING FACE'S OWN WORD, kept before the block is consumed — the model carries the resolved
  // NAME and not the literal that wrote it, and the mints-none audit below needs a span to land a
  // caret on. Whether the face exists at all is a fact about the KEY, which is settled further down,
  // so the two halves of that question meet after the model is built.
  let key_argument_at = graphql_block
    .as_ref()
    .and_then(|block| block.key_argument.clone());
  let graphql = graphql_model(
    record,
    kind,
    graphql_block,
    persist.as_ref(),
    &marked,
    &mut errors,
  );

  let derived = derived_model(derived_block, &marked, &mut errors);
  // AFTER the reverse positions and not beside them, because the artifact positions are checked
  // against the words those settled on — see [`locate_model`], whose header says why the settled
  // list rather than the declared block.
  let artifacts = locate_model(locate_block, &marked, &derived, &mut errors);

  // A FAN-IN's ancestry is one value rather than a set of columns, so the two the declaration would
  // otherwise have supplied are minted here: the lineage type is a CHOICE over the upstreams, and
  // the key's leading column is that choice. The record's own field holding it is the ECHO's — see
  // `fanned_lineage` — which is why it is not among `own` below and gets no accessor family.
  let (lineage, key_path) = match upstreams.as_ref().and_then(Upstreams::fanned) {
    Some(fanned) => {
      let name = lineage_rename
        .clone()
        .unwrap_or_else(|| default_lineage_name(record));
      let column = Column {
        name: fanned_lineage_column(),
        source: fanned_lineage(&EmissionPrefix::default()),
        ty: syn::parse_quote!(#name),
        project: Projection::Borrowed,
      };
      if key_path
        .iter()
        .chain([&key_id])
        .any(|taken| taken.name == column.name)
      {
        errors.push(syn::Error::new_spanned(
          record,
          format!(
            "`{key_name}` would have two columns called `{}` — one is this {noun}'s ancestry, which \
             is a CHOICE among the upstreams it draws from and takes that name in every key. Rename \
             the other, or the type through `key(rename = \"…\")`",
            column.name,
            noun = kind.noun(),
          ),
        ));
      }
      (
        Some(Lineage {
          name,
          shape: Shape::Kinds(fanned.kinds.clone()),
        }),
        vec![column],
      )
    }
    None => (
      lineage_name.map(|name| Lineage {
        name,
        shape: Shape::Path(lineage_columns),
      }),
      key_path,
    ),
  };

  // A FAN-IN's ancestry is a field the ECHO mints — see `fanned_lineage` — and a rewrite has no
  // field list to mint it into: the item the compiler sees is one unnamed position holding the
  // wrapped type. Refused here, where both facts are settled, rather than left to fail as a
  // positional struct the injection quietly declined to touch.
  if remote.is_some() && upstreams.as_ref().and_then(Upstreams::fanned).is_some() {
    errors.push(syn::Error::new_spanned(
      record,
      format!(
        "{article} {noun} that WRAPS a foreign type cannot also draw from several independent \
         upstreams — a fan-in's ancestry is a CHOICE among them, carried in a field this macro \
         mints, and a transparent wrapper's one position is the wrapped type. Designate one \
         upstream with `key`, whose lineage is columns the manifest already names",
        article = kind.article(),
        noun = kind.noun(),
      ),
    ));
  }

  let model = RecordModel {
    prefix: EmissionPrefix::default(),
    record: record.clone(),
    kind,
    vis: input.vis.clone(),
    krate,
    remote,
    construction,
    key: Key {
      name: key_name,
      path: key_path,
      id: key_id,
    },
    lineage,
    fields: own,
    persist,
    order_by,
    progress,
    graphql,
    derived,
    artifacts,
    implements,
    subscribe,
    subscriptions,
    products,
    polls,
    teardown,
    asynchronous,
    streaming,
    autonomous,
    attributed,
    options: options_type,
    upstreams,
    errors: declared_errors,
    tracing,
    receipt,
  };
  // The three checks that read the SETTLED model rather than the declaration: which types an
  // emission declares, what each one's methods are called, and what its root fields are called are
  // facts about the emission — so each is asked of the thing that will be emitted. Types first,
  // because a scope-level clash is the coarser of the three.
  emitted_names(&model, &mut errors);
  emitted_methods(&model, &mut errors);
  derived_plural(&model, &mut errors);
  key_faces(&model, key_argument_at.as_ref(), &mut errors);
  errors.into_result(model)
}

/// **THE `stream` WORD's TWO CROSS-WORD RULES** — which kinds may wear the streaming pair, and the
/// buffered-only word that cannot stand beside it.
///
/// Both are read AFTER the walk rather than at the token, because both are about a PAIR of words and
/// an author may type a pair in either order: a rule enforced at the first word would fire for
/// `stream, poll(…)` and stay silent for `poll(…), stream`, which is one rule with two behaviours.
///
/// The sentences are the FACE-SELECTION LAW's, because that is the question an author is actually
/// being asked: the face is chosen by the fan-out one delivered item produces — bounded in the input
/// is the buffered pair, growing with the input's length is the streaming one — and both refusals
/// below are a declaration having answered it in a place the answer cannot be performed.
fn streaming_word(
  kind: NodeKind,
  streaming: Option<&syn::Path>,
  polls: Option<&Polls>,
  errors: &mut Errors,
) {
  let Some(word) = streaming else {
    return;
  };
  // RULE ONE: the pair is the COMPUTE seam's, and only the compute macro opens it. Every other kind
  // publishes an address, and the storing ones land rows through a write lane of their own — which
  // is a seat the lane that drives a streaming body does not carry, so a declaration mounted there
  // would claim a durability its mount cannot perform.
  if !matches!(kind, NodeKind::Operator) {
    errors.push(syn::Error::new_spanned(
      word,
      format!(
        "`stream` is an `operator`'s word, and {article} {noun} may not write it. The streaming \
         pair is the COMPUTE seam's other pair — a body whose per-item fan-out GROWS WITH THE \
         INPUT, streamed out through a bounded `Feed` over one delivery's whole life — and what \
         drives one is a lane holding a warm set and a downstream set, with no write lane in it. \
         Declare the streaming half as an `operator` and let {article} {noun} subscribe to what it \
         emits",
        article = kind.article(),
        noun = kind.noun(),
      ),
    ));
  }
  // RULE TWO: the buffered-only word. A tick is delivered to the node's OWN value, which the
  // resident lends per tick — that is what `light` names and what a mounted handler is routed
  // through. A stream-faced node has no such value to lend: its bodies are the lane's warm set,
  // handed out one per delivery and owned by that delivery's run for its whole life.
  if let Some(polls) = polls {
    for clock in &polls.entries {
      errors.push(syn::Error::new_spanned(
        &clock.name,
        "`poll(…)` is the BUFFERED pair's word and cannot stand beside `stream`. A tick is one \
         call against the node's own value, which the driver LENDS for that call — and a \
         stream-faced node has no value to lend: its bodies are the lane's warm set, and each one \
         is owned by a delivery's run for that delivery's whole life. The face is chosen by the \
         FAN-OUT one delivered item produces, so a node that both streams and wakes on a clock is \
         two nodes: drop `stream` here, or move the clock onto a node of its own"
          .to_owned(),
      ));
    }
  }
}

/// **THE `autonomous` WORD's TWO CROSS-WORD RULES** — which kinds may wear the third kind, and the
/// word on the same axis that cannot stand beside it.
///
/// Both are read AFTER the walk for [`streaming_word`]'s reason, which is that both are about a
/// PAIR of words and an author may type a pair in either order: a rule enforced at the first word
/// would fire for `autonomous, stream` and stay silent for `stream, autonomous`.
///
/// The sentences are the FACE-SELECTION LAW's three rows, because that is the question an author is
/// actually being asked — the framework drives a bounded body, the lane drives a whole-file one and
/// keeps its books, and a node that has to own its select order, its intake gating or its ack
/// timing takes the wheel.
fn autonomous_word(
  kind: NodeKind,
  autonomous: Option<&syn::Path>,
  streaming: Option<&syn::Path>,
  errors: &mut Errors,
) {
  let Some(word) = autonomous else {
    return;
  };
  // RULE ONE: the kind is the COMPUTE seam's, exactly as the streaming pair is, and for the same
  // reason one kind over. Every other kind publishes an address and the storing ones land rows
  // through a write lane of their own — a seat an autonomous mount does not carry, because such a
  // node publishes through its own downstream set and lands nothing of its own. A declaration
  // mounted there would claim a durability its mount cannot perform.
  if !matches!(kind, NodeKind::Operator) {
    errors.push(syn::Error::new_spanned(
      word,
      format!(
        "`autonomous` is an `operator`'s word, and {article} {noun} may not write it. The \
         autonomous kind is the COMPUTE seam's third one — a body that owns its own loop over its \
         inbound edges, its downstream set and its stop — and what mounts one is a thread with no \
         write lane in it. Declare the autonomous half as an `operator` and let {article} {noun} \
         subscribe to what it emits",
        article = kind.article(),
        noun = kind.noun(),
      ),
    ));
  }
  // RULE TWO: ONE DECLARATION, ONE KIND. The two words are values of the SAME axis rather than two
  // axes that multiply — which `async` is, and which is why `autonomous, async` costs no third word
  // — so a declaration carrying both has answered the face-selection law twice, in two ways that
  // name two different mounts.
  if let Some(stream) = streaming {
    errors.push(syn::Error::new_spanned(
      stream,
      "`stream` and `autonomous` are values of ONE axis, and a declaration wears exactly one kind. \
       `stream` is the face where one delivery is one whole life and the per-delivery parallelism \
       AND the fate bookkeeping are the FRAMEWORK's — a demux, whose lane holds the warm set, the \
       admission bound and the dead-letter. `autonomous` is take-the-wheel-keep-the-books: the \
       node owns its select order, its arm priority, its intake gating, its ack timing and its own \
       workers. Write whichever one this body is, and put `async` beside it where the body awaits"
        .to_owned(),
    ));
  }
}

/// **THE ADDRESS'S TWO SEATS, CHECKED AGAINST THE FACES THIS RECORD ACTUALLY MINTS** — the
/// mints-none audit at `key(input(rename))` and `key(output(rename))`.
///
/// # Seats may sit EMPTY; written words must point at something MINTED
///
/// An unwritten seat costs nothing. A written one that reaches no emitted name is a swallowed
/// authoring error, and this is the position where one is reachable: a ROOT's address crosses inward
/// as its ID and mints no argument object at all, so `key(input(rename = "…"))` on one names a type
/// that is never emitted and its author's schema publishes `get(id: …)` unchanged.
///
/// # The OUTPUT seat is AUDITED and found always-spent, which is not the same as unaudited
///
/// `emit::wire`'s `key_output_face` is written unconditionally for every record whose `graphql(…)`
/// block names a backend, and a block naming none is already refused by name in [`graphql_model`] —
/// so there is no shape in which the word is reachable and the object is absent. A key always has at
/// least one column, an id being mandatory, so the empty-object question the input face answers
/// never arises for it. The seat therefore takes no clause here, and the measurement is written down
/// rather than left as a gap a later reader would have to re-derive.
///
/// # It is the KEY that decides, so it is asked of the settled model
///
/// `Key::compound` is the one predicate the emitter forks on, so this asks exactly it — a face
/// without a type, or a type without a face, is not a state either side can reach on its own.
fn key_faces(model: &RecordModel, argument: Option<&syn::LitStr>, errors: &mut Errors) {
  let Some(written) = argument else {
    return;
  };
  if model.key.compound() {
    return;
  }
  errors.push(syn::Error::new_spanned(
    written,
    format!(
      "`input` names the object a client SENDS this address in, and `{record}` is a ROOT: its \
       address is its id alone, so it crosses inward as that id's own wire form and no `KeyInput` \
       type is minted for a word to move. What a client sends is `{record_lower}(id: …)`, whose \
       argument type is the id column's own. The word opens where the record has a LINEAGE — a \
       compound address is a product a client has to name — and `output(rename = \"…\")` beside it \
       names the object an address is READ back in, which every record has",
      record = model.record,
      record_lower = {
        use heck::ToLowerCamelCase as _;
        model.record.to_string().to_lower_camel_case()
      },
    ),
  ));
}

/// Which emitted type a field-level block is naming a column in.
#[derive(Clone, Copy)]
enum Scope {
  Key,
  Lineage,
}

/// A multi-upstream declaration with its MODE settled: which upstream the identity descends from, or
/// that none was designated and the upstreams are independent.
///
/// Separate from [`Upstreams`] because a fusion's MIRRORS are not known yet — the lineage block has to
/// be resolved against the struct's fields first, and whether a lineage field may carry a mirror at
/// all is decided by which of these two it is.
enum Mode {
  /// `key` on one entry: the upstreams join. The designated parent, and the ones joined beside it.
  Fused {
    parent: syn::Path,
    others: Vec<syn::Path>,
  },
  /// No `key`: the upstreams are independent, and each one is a variant of this node's lineage.
  Fanned(FanIn),
}

/// The `upstream(…)` entries read as ONE declaration: whether an upstream carries `key`, and every way
/// that question can be answered wrongly.
///
/// # `key` is the LINEAGE-MODE SELECTOR, and that is the whole of what it decides
///
/// Written, the upstreams JOIN: their messages jointly make one output, whose identity descends from
/// the designated parent, and this node's lineage mirrors that parent's key column for column.
/// Absent, the upstreams are INDEPENDENT: each one's messages make their own outputs, the payload is
/// uniform, and what varies is WHICH upstream a row came from — so the lineage becomes a choice
/// among them rather than a path through one.
///
/// Neither is refused, and neither is a fallback for the other. A declaration that omits the word
/// has said something, and it is the commoner topology of the two.
///
/// # Why one entry is enough to be either
///
/// Nothing here requires TWO upstreams. What `upstream(…)` adds over `subscribe = "…"` is the MODE,
/// and a node with one upstream that wants its lineage checked against that upstream's key wants
/// exactly the same equation a three-upstream fusion does. So the short form stays what it has
/// always been — an edge, and no claim about identity — and the long form is the one that makes a
/// claim, at whatever arity.
///
/// # The two spellings are not interchangeable
///
/// A declaration writing both is refused rather than merged. `subscribe` names an edge and says
/// nothing about identity; `upstream(…)` names an edge and says which of the two shapes this node's
/// ancestry has. Merging them would leave the most important fact about a node's identity depending
/// on which of two words an author reached for first.
fn key_parent(
  record: &syn::Ident,
  kind: NodeKind,
  upstreams: &[UpstreamBlock],
  subscribe: Option<&syn::Path>,
  errors: &mut Errors,
) -> Option<Mode> {
  if upstreams.is_empty() {
    return None;
  }
  if let Some(subscribe) = subscribe {
    errors.push(syn::Error::new_spanned(
      subscribe,
      format!(
        "`{record}` names its upstreams twice — `upstream(…)` beside `subscribe`. One node \
         has one spelling of its edge: `subscribe` names the fan-in, in the short form for a node \
         driven by one upstream or in the container form for a node drawing from several, and \
         `upstream(…)` at the top level is the form that also designates which upstream this \
         {noun}'s identity comes from",
        noun = kind.noun(),
      ),
    ));
  }

  let mut designated: Option<&UpstreamBlock> = None;
  for source in upstreams {
    if source.node.is_none() {
      errors.push(syn::Error::new_spanned(
        &source.at,
        "`upstream(…)` needs `node = \"path::To::Upstream\"` — an entry with no upstream names \
         nothing, and `key` beside it would designate nothing",
      ));
    }
    let Some(key) = &source.key else { continue };
    match designated {
      // Spanned at the SECOND designation, and both are named: which of two is wrong is the
      // author's to decide, and a message that picked one would be guessing.
      Some(first) => errors.push(syn::Error::new_spanned(
        key,
        format!(
          "two upstreams are designated `key`, and {article} {noun} descends from ONE — its \
           lineage is that upstream's key, and a lineage cannot be two paths at once. `{}` already \
           carries the designation; the other upstream's provenance is an ordinary `ref = \"…\"` \
           field, which is opt-in and says which column holds it",
          first
            .node
            .as_ref()
            .map_or_else(|| "the entry above".to_owned(), path_text),
          article = kind.article(),
          noun = kind.noun(),
        ),
      )),
      None => designated = Some(source),
    }
  }

  let Some(source) = designated else {
    return fanned(record, upstreams, errors).map(Mode::Fanned);
  };
  Some(Mode::Fused {
    parent: source.node.clone()?,
    others: upstreams
      .iter()
      .filter(|other| !core::ptr::eq(*other, source))
      .filter_map(|other| other.node.clone())
      .collect(),
  })
}

/// The upstreams of a node that designated none of them — one lineage VARIANT apiece.
///
/// # The variant's name is READ OFF the path, never declared
///
/// `upstream(node = "asr::Segment")` is the `Segment` variant. The path is what a reader has in front
/// of them, so a second word naming the same thing would be a second place for it to drift; and the
/// word is what the discriminant IS everywhere it is spelled — a directory under a blob's slot, a
/// column in a row, a field in an engine — so minting it once here is what keeps those one
/// vocabulary.
///
/// Two upstreams whose last segments agree are refused HERE, naming both. Left alone they would be
/// two variants of one name inside the emitted enum, which is `E0428` at a span the declaration
/// cannot edit — and the fix is a rename this grammar has no word for, so the useful answer is the
/// one that names the collision.
fn fanned(record: &syn::Ident, upstreams: &[UpstreamBlock], errors: &mut Errors) -> Option<FanIn> {
  let mut kinds: Vec<Kind> = Vec::new();
  for source in upstreams {
    let Some(node) = source.node.clone() else {
      continue;
    };
    let variant = node
      .segments
      .last()
      .expect("a path has at least one segment")
      .ident
      .clone();
    if let Some(first) = kinds.iter().find(|kind| kind.variant == variant) {
      errors.push(syn::Error::new_spanned(
        &source.at,
        format!(
          "`{record}` draws from two upstreams whose names agree — `{}` and `{}` both end in \
           `{variant}`, and that word is what names the variant this one's rows descend from. It is \
           read off the path rather than declared, so a reader of a stored address can find the \
           upstream it came from; two upstreams cannot share it",
          path_text(&first.node),
          path_text(&node),
        ),
      ));
      continue;
    }
    kinds.push(Kind { node, variant });
  }
  (!kinds.is_empty()).then_some(FanIn { kinds })
}

/// A path as an author would read it back — for a refusal naming a declaration the author wrote in a
/// string.
fn path_text(path: &syn::Path) -> String {
  path
    .segments
    .iter()
    .map(|segment| segment.ident.to_string())
    .collect::<Vec<_>>()
    .join("::")
}

/// A scoped rename on a field that scope has no column for.
fn no_subject(at: &syn::Path, field: &syn::Ident, scope: &str, reaches: &str) -> syn::Error {
  syn::Error::new_spanned(
    at,
    format!(
      "`{scope}(rename = \"…\")` names `{field}`'s column in the `{scope}` type, and `{field}` \
       has none there — only {reaches} reach it. A data column's rename will be its own scope \
       once the persisted row is emitted; it is not this one."
    ),
  )
}

/// The record-level `#[ingraph(…)]` grammar, as written.
struct Options {
  /// `crate = "…"`, or `::ingraph`.
  krate: syn::Path,
  /// `key(rename = "…")`, if it was named.
  key_rename: Option<syn::Ident>,
  /// The `lineage(…)` block, or `None` when the record is a root and omitted it.
  lineage: Option<LineageBlock>,
  /// The STORE WORDS as written, or `None` when the declaration named none.
  ///
  /// `None` is a refusal on a `record` and the ordinary state on every other kind — see
  /// [`persist_model`], which is where the two are told apart.
  persist: Option<PersistBlock>,
  /// The `graphql(…)` block, or `None` when the record has no wire face.
  graphql: Option<GraphqlBlock>,
  /// The `derived(…)` block, or `None` when nothing was declared to point back.
  derived: Option<DerivedBlock>,
  /// The `locate(…)` block, or `None` when no artifact family was declared to be addressable from
  /// here.
  locate: Option<LocateBlock>,
  /// `implements(…)` — the interfaces this record declares itself a member of, in the order they
  /// were written.
  implements: Vec<syn::Path>,
  /// `subscribe = "path::To::Upstream"` — the node whose messages drive this one.
  subscribe: Option<syn::Path>,
  /// WHERE the word `subscribe` was written, in either spelling — the span a refusal about the
  /// edge's declaration reports at, and the slot the said-it-twice rule counts.
  subscribe_at: Option<syn::Path>,
  /// The `subscribe(…)` container, when the declaration wrote one.
  subscriptions: Option<SubscribeBlock>,
  /// The `emits` word, when the declaration named its products.
  products: Option<EmitsWord>,
  /// The `poll(…)` entries, in the order they were written. Empty where the declaration wrote none.
  polls: Vec<PollBlock>,
  /// `teardown` — whether the declaration opted its constructed value into the shutdown's goodbye.
  teardown: bool,
  /// `async` — the MODE WORD, kept as its path so the audit it buys can be spanned at it.
  asynchronous: Option<syn::Path>,
  /// `stream` — the FACE WORD, kept as its path for the same reason. A different axis from
  /// [`asynchronous`](Self::asynchronous): this picks the PAIR, that picks which half of it.
  streaming: Option<syn::Path>,
  /// `autonomous` — the PAIR axis's THIRD value, kept as its path for the same reason. It is
  /// [`streaming`](Self::streaming)'s own axis rather than a fourth one: a declaration wears
  /// exactly ONE kind, so the two words are refused together.
  autonomous: Option<syn::Path>,
  /// `attributed` — whether the declaration opted its OUTPUTS into the framework's root projection.
  ///
  /// A `bool` on [`teardown`](Self::teardown)'s own road, and for its reason: the walk holds the
  /// path while it runs, because that is what the said-it-twice rule reports at, and nothing
  /// downstream blames the word back — so the presence alone is what leaves the parser.
  attributed: bool,
  /// `options = "…"` — the type a deployment's section for this node deserializes into, or `None`
  /// where the declaration wrote none and the node is configured by `()`.
  options: Option<syn::Path>,
  /// `remote = "…"` — the foreign type this declaration is a TRANSPARENT WRAPPER over, or `None`
  /// for the ordinary declaration that IS its fields.
  remote: Option<syn::Path>,
  /// `builder(…)` — HOW that foreign type is built, or `None` where the declaration described no
  /// protocol and takes the default law. See [`crate::construct`].
  construction: Option<Construction>,
  /// The `upstream(…)` entries — a FUSION's upstreams, in the order they were written. Empty where
  /// the declaration wrote none.
  upstreams: Vec<UpstreamBlock>,
  /// `error(…)` — the declared type per (crossing, database) cell, in the order written.
  errors: Vec<BackendError>,
  /// `tracing(level = …)` — the level this node's spans open at, or `None` where it wrote no word.
  tracing: Option<TracingLevel>,
  /// `receipt = "…"` — the value this node hands back to an acked give's producer, or `None` where
  /// the declaration wrote none and the node states no receipt at all.
  receipt: Option<syn::Path>,
}

/// The `derived(…)` block: every REVERSE position the record declares.
struct DerivedBlock {
  /// The entries inside it, in the order they were written.
  entries: Vec<DerivedEntry>,
  /// The block's own path, for a refusal about the block rather than an entry inside it.
  at: syn::Path,
}

/// One reverse position AS WRITTEN.
struct DerivedEntry {
  /// The position's name — the entry's own word, which is also the span a refusal about this
  /// position reports at.
  name: syn::Ident,
  /// The record that points back, as the declaration spelled it.
  source: syn::Path,
  /// `field = "…"`, where the full form named one.
  field: Option<syn::LitStr>,
}

/// The `locate(…)` block: every ARTIFACT FAMILY this record answers an address for.
///
/// [`DerivedBlock`]'s shape exactly, and that is the ruling rather than a convenience: the word is a
/// reverse-container sibling of `derived(…)`, so it joins `derived`'s own reader and every mechanism
/// the two share — the said-it-twice count, the entry-level repeat, the assembly's empty-block
/// refusal, the one-namespace-per-face collision — is one mechanism written once. A second reader
/// would be how the two words come to refuse the same mistake in two voices.
struct LocateBlock {
  /// The entries inside it, in the order they were written.
  entries: Vec<LocateEntry>,
  /// The block's own path, for a refusal about the block rather than an entry inside it.
  at: syn::Path,
}

/// One artifact position AS WRITTEN.
///
/// The same TWO FORMS [`DerivedEntry`] has, and what the full form carries is the difference between
/// the two words. A reverse position's full form says WHICH of a source's `ref` columns it means; an
/// artifact family has exactly one upstream and so has nothing of that kind to say. What its full
/// form says instead is that this position ASKS FOR THE BYTES — the word the family's own `data`
/// permits — and whether the ADDRESS it answers is signed for as non-null.
struct LocateEntry {
  /// The family's name — the entry's own word, which is also the span a refusal about this position
  /// reports at.
  name: syn::Ident,
  /// The blob node this position addresses, as the declaration spelled it.
  family: syn::Path,
  /// The `data` ask, where the full form wrote one.
  data: Option<LocateData>,
  /// `required` — whether the ADDRESS field is `BlobLocation!` rather than `BlobLocation`.
  ///
  /// [`LocateData::required`] at the position's own grain, and the two are independent: a
  /// store-mediated position publishes up to two fields, so a declaration may sign for either, both
  /// or neither. See [`REQUIRED`], where the one meaning both spellings carry is written down.
  required: bool,
}

/// The `data` ask inside one artifact position's full form, AS WRITTEN.
///
/// # The ASK is here and the PERMIT is on the family, and both words are real
///
/// A GraphQL field's presence is decided by the expansion that writes the `#[Object]` block, which
/// is the ENTITY's — so a family's own `data` word cannot put a field anywhere. What it can do is
/// bind `ArtifactData`, and what THIS word does is ask for the field that spends it. A position
/// asking where the family never permitted is `E0277` at the projection, carrying that trait's own
/// sentence, which points both ways: write `data` on the family, or drop it from the ask.
struct LocateData {
  /// The word itself, for a refusal about the ask rather than about the position.
  at: syn::Path,
  /// `data = "thumbBytes"` — the wire field's name, written explicitly.
  ///
  /// [`None`] is the DEFAULT rather than the absence of an answer: the field is `<domain-word>Data`,
  /// resolved at the face where the framework's one camelCase authority lives, so nothing here mints
  /// a second naming rule.
  rename: Option<syn::LitStr>,
  /// `data(required)` — whether the emitted field is `String!` rather than `String`.
  ///
  /// A ONE-WAY word: nullable is the shipped answer because it is the true one — an artifact is
  /// written asynchronously after the entity exists, and reading it is a round trip against somebody
  /// else's store — and non-null is the author's informed signature that their deployment is not
  /// like that. There is no inverse word, because not writing this one IS the inverse. See
  /// [`REQUIRED`], where the one meaning both grains carry is written down.
  required: bool,
}

/// The `graphql(…)` block: which backends render the record, and what the schema calls it.
struct GraphqlBlock {
  /// The backends named inside it, in the order they were written.
  backends: Vec<BackendBlock>,
  /// `output(rename = "…")` — what the emitted OUTPUT type is called, in both faces.
  output: Option<syn::Ident>,
  /// `key(rename = "…")` — the BASE the address face is built on, in Rust and in the schema.
  key: Option<syn::Ident>,
  /// `key(output(rename = "…"))` — what the SCHEMA calls the address OBJECT, overriding what the
  /// base above derives.
  ///
  /// A [`syn::LitStr`] where its base is a [`syn::Ident`], and the split is the axis: the base names
  /// a type the declaring scope holds, and this names one in GraphQL's flat namespace — where a Rust
  /// keyword is an ordinary word, per the 2026-08-13 ruling. It shares its kind and its fence with
  /// [`Self::connection`] two fields down.
  key_object: Option<syn::LitStr>,
  /// `key(input(rename = "…"))` — what the SCHEMA calls the address ARGUMENT object, by its
  /// neighbour's kind and its neighbour's fence.
  key_argument: Option<syn::LitStr>,
  /// `filter(rename = "…")`.
  filter: Option<syn::Ident>,
  /// `order_by(rename = "…")`.
  order_by: Option<syn::Ident>,
  /// `connection(rename = "…")` — what the SDL calls the page object.
  ///
  /// The same BLOCK its four neighbours write, which is what the ruling asked for in so many words —
  /// *mirroring the block's existing rename entries* — through [`attribute::sdl_name_block`] rather
  /// than [`attribute::rename_block`], because what it names is a SCHEMA type and not a Rust one.
  ///
  /// The LITERAL rather than an ident, and that is the 2026-08-13 ruling: *graphql 和 db 那边 type
  /// 和其他的 rust 关键词都不是问题, 所以我们应该想办法支持*. `connection(rename = "type")` is a
  /// legal GraphQL name — GraphQL's own keywords are contextual — and an ident parse was refusing it
  /// for a Rust reason no schema has. It shares the kind and the slot type of
  /// [`Self::plural`](GraphqlBlock::plural), which is the same fact one field down.
  connection: Option<syn::LitStr>,
  /// `edge(rename = "…")` — what the SDL calls one element of that page. Its neighbour's kind and
  /// its neighbour's fence.
  edge: Option<syn::LitStr>,
  /// `rename = "…"` — the base the emitted Rust types suffix.
  rename: Option<syn::Ident>,
  /// `plural = "…"` — this entity's PLURAL, as the declaration corrected it.
  ///
  /// The LITERAL rather than its contents, for [`value::literal`]'s reason: it carries the span a
  /// refusal about the word reports at, and the word is not Rust — it is a WIRE word, so there is
  /// nothing here to re-parse into an ident.
  plural: Option<syn::LitStr>,
  /// The block's own path, for a refusal about the block as a whole.
  at: syn::Path,
}

/// One GraphQL backend's block inside the record's `graphql(…)`.
struct BackendBlock {
  kind: GraphqlKind,
  /// `rename = "…"` — what the emitted OUTPUT type is called.
  ///
  /// Kept because the grammar takes it, and unread because the emitted types are ONE per record:
  /// the SDL is identical whichever Rust library serves it, so a second backend adds cfg-gated
  /// derives to the same types rather than a second set. It reaches the model the day that changes.
  rename: Option<syn::Ident>,
  /// `attrs(…)`, verbatim.
  attrs: Option<proc_macro2::TokenStream>,
}

/// A field's `graphql(…)`: the wire field it becomes, and each backend's refinements.
///
/// Under the inversion a field HAS a wire place without writing one word, so this is a refinement of
/// a place rather than the grant of one — see [`WireField::unrefined`], which is the shape a silent
/// field is read through.
struct WireField {
  /// The marker's own path — the span a refusal about this field's wire face reports at.
  at: syn::Path,
  /// `rename = "…"` — the field's name in the SCHEMA.
  rename: Option<syn::LitStr>,
  /// `type = "…"` — the ONE wire form, serving both positions and every database.
  ty: Option<syn::Type>,
  /// `output(<db>(…))` — the crossings from each database's row field onto the wire.
  output: Vec<WireLeg>,
  /// `input(comparison(<db>(…)))` — the crossings from the wire form into each database's row.
  comparison: Vec<WireLeg>,
  /// `skip` — this field is absent from EVERY wire backend's vocabulary.
  ///
  /// BARE, and it takes no fill: the storage word supplies a value a raise needs, and a field the
  /// wire never publishes has nothing to supply.
  skip: Option<syn::Path>,
  /// The per-backend blocks, in the order they were written.
  per_backend: Vec<FieldBackend>,
}

impl WireField {
  /// The refinement a field that wrote NO wire word makes: none.
  ///
  /// Its `at` is the field's own name, which is the only token such a field wrote — and the right
  /// one, because every refusal reading this shape is about the field rather than about a word.
  fn unrefined(field: &syn::Ident) -> Self {
    Self {
      at: syn::Path::from(field.clone()),
      rename: None,
      ty: None,
      output: Vec::new(),
      comparison: Vec::new(),
      skip: None,
      per_backend: Vec::new(),
    }
  }
}

/// ONE database's leg of a field's wire crossing, as written.
///
/// The DIRECTION is the block's, not the entry's: an `output(…)` leg is written with `from`, because
/// a wire value is BUILT from a row, and an `input(comparison(…))` leg with `into`, because a wire
/// value LEAVES for one. The verb rule, applied to a crossing rather than to a projection.
fn wire_legs(
  inner: &syn::meta::ParseNestedMeta<'_>,
  legs: &mut Vec<WireLeg>,
  scope: &str,
  direction: Direction,
  errors: &mut Errors,
) -> syn::Result<()> {
  attribute::options(inner, |db| {
    let Some(kind) = database_kind(&db.path) else {
      // `field` is the one non-database word a reader plausibly writes here: this block's word is
      // `output`, and the OUTPUT MEMBER's own knob is spelled inside a backend's own `output(…)`.
      // Named rather than swept up, so the sentence can point at the block that takes it.
      if db.path.is_ident("field") {
        errors.push(named(
          &db,
          format!(
            "`field` names the OUTPUT OBJECT's accessor for a field, and this block is the \
             row-to-wire CROSSING — write `graphql(<backend>(output(field = \"…\")))`. `{scope}`'s \
             own entries are per database, because a crossing has a row on one side of it."
          ),
        ));
        return Ok(());
      }
      errors.push(attribute::unknown(
        &db,
        &format!(
          "unknown entry in `{scope}` — a leg opens the DATABASE's block whose row it crosses, \
           because a row is one database's: {list}",
          list = shipped(DatabaseKind::ALL.into_iter().map(DatabaseKind::as_str)),
        ),
        &DatabaseKind::ALL.map(DatabaseKind::as_str),
      ));
      return Ok(());
    };
    if legs.iter().any(|leg| leg.kind == kind) {
      errors.push(syn::Error::new_spanned(
        &db.path,
        format!(
          "`{kind}` is declared more than once in `{scope}` — one leg per database",
          kind = kind.as_str()
        ),
      ));
    }
    let (mut builds, mut leaves) = (ConversionSpec::default(), ConversionSpec::default());
    let walked = attribute::options(&db, |option| {
      let wrong = if direction.plain == "from" {
        [("into", "try_into")]
      } else {
        [("from", "try_from")]
      };
      for (plain, fallible) in wrong {
        if option.path.is_ident(plain) || option.path.is_ident(fallible) {
          errors.push(named(
            &option,
            format!(
              "`{scope}` takes `{}`/`{}` — `from` BUILDS the projection its block is about and \
               `into` LEAVES it, so an output leg is written with `from` and an input one with \
               `into`",
              direction.plain, direction.fallible
            ),
          ));
          return Ok(());
        }
      }
      if conversion(
        &option,
        &mut builds,
        &mut leaves,
        scope,
        Cells::Elsewhere,
        errors,
      ) {
        return Ok(());
      }
      errors.push(attribute::unknown(
        &option,
        &format!(
          "unknown entry in `{scope}`'s `{kind}` block — a leg is the conversion and nothing else: \
           `{}`/`{}`, in the short form or the structured one",
          direction.plain,
          direction.fallible,
          kind = kind.as_str()
        ),
        &[direction.plain, direction.fallible],
      ));
      Ok(())
    });
    let spec = if direction.plain == "from" {
      &builds
    } else {
      &leaves
    };
    let conversion = spec.resolve(
      &format!("`{scope}`'s `{}` leg", kind.as_str()),
      direction,
      errors,
    );
    if matches!(conversion, Conversion::Default) {
      errors.push(syn::Error::new_spanned(
        &db.path,
        format!(
          "`{kind}` names no conversion in `{scope}` — a leg exists to REPLACE the default chain, \
           so an empty one says nothing the absence of the block does not already say",
          kind = kind.as_str()
        ),
      ));
    } else {
      legs.push(WireLeg { kind, conversion });
    }
    walked
  })
}

/// The refusal when a field's label is not something this grammar can read at all.
///
/// The subject is the LABEL rather than the marker it resolves to: what a declaration writes is a
/// label, and what it reaches is a marker. The words are read off [`Label::ALL`] rather than spelled
/// into the sentence, for the reason every sentence here reads them off: a hand-written list is a
/// second copy of the vocabulary, and a copy is a thing that can fall behind the enum while still
/// compiling.
fn label_shape() -> String {
  format!(
    "a field's label is the interpretation its type is read under — write {list}, a collection's \
     element inside it (`list(string)`), or any other marker's path in a string literal",
    list = shipped(Label::ALL.into_iter().map(Label::as_str)),
  )
}

/// The refusal `graphql(marker = …)` gets — the spelling a field's own word replaces.
///
/// It names what to WRITE instead, read off the value the declaration already has: a field is a
/// migration away from compiling, and the word it was writing is the word it keeps. The value is
/// read off a FORK, so the entry is still whole for the skip that follows the refusal.
fn marker_is_the_older_spelling(meta: &syn::meta::ParseNestedMeta<'_>) -> String {
  let Some(write) = written_instead(meta) else {
    return format!(
      "`marker` is not an option — a field's label is its own word, at the TOP level beside \
       `persist` and `graphql`: {list}, a collection's element inside it (`list(string)`), or \
       `label = \"a::marker::Path\"`",
      list = shipped(Label::ALL.into_iter().map(Label::as_str)),
    );
  };
  format!(
    "`marker` is not an option — a field's label is its own word, at the TOP level: write \
     `{write}` beside `persist` and `graphql`, where this went inside `graphql(…)`. A label is a \
     fact about the field's KIND rather than about one of its faces, and it feeds storage as surely \
     as it feeds the filter."
  )
}

/// The label a `marker = …` was writing, spelled as a declaration writes one now.
///
/// `None` when the value is not something this grammar reads, which is the one case the migration
/// has nothing specific to offer — the general sentence lists the words instead.
fn written_instead(meta: &syn::meta::ParseNestedMeta<'_>) -> Option<String> {
  let fork = meta.input.fork();
  fork.parse::<syn::Token![=]>().ok()?;
  if fork.peek(syn::LitStr) {
    let path = fork.parse::<syn::LitStr>().ok()?;
    return Some(format!("label = {:?}", path.value()));
  }
  let word = syn::Ident::parse_any(&fork).ok()?.unraw();
  let label = Label::ALL
    .into_iter()
    .find(|label| word == label.as_str())?;
  // A collection word carries its element now, and the migration says so rather than offering a
  // spelling the grammar would refuse for being bare.
  Some(if label.collection() {
    format!("{word}(<the element's own word>)")
  } else {
    word.to_string()
  })
}

/// The refusal an unknown ELEMENT word gets, which has one door fewer than the field's own.
///
/// A collection's element is one of the framework's words and nothing else — the custom escape is
/// the FIELD's, and an element-level one is reserved — so the sentence that offers the string
/// literal must not be the sentence a reader gets here.
fn unknown_element(word: &syn::Ident) -> String {
  format!(
    "`{word}` is not an interpretation this framework names — a collection's element is one of \
     {list}, and an element-level custom marker is reserved",
    list = shipped(Label::ALL.into_iter().map(Label::as_str)),
  )
}

/// The field-level option naming a marker by PATH — the custom escape, and the general form every
/// word is short for.
const LABEL: &str = "label";

/// The field-level word naming the record a column REFERS to.
///
/// A Rust keyword, and the word anyway: syn's nested-meta path parser takes an entry with
/// `Ident::parse_any`, so it arrives here as an ordinary one-segment path exactly as `crate` does,
/// and what rustc reserves for its own grammar has nothing to say about a relation.
const REFERS: &str = "ref";

/// The refusal a `ref` this grammar cannot read gets. It shows BOTH forms, because which one an
/// author wants depends on whether the relation needs more than a target.
const REF_SHAPE: &str = "`ref` names the record a field refers to — write \
                         `ref = \"path::to::Type\"`, or `ref(type = \"path::to::Type\")` where the \
                         relation needs more than a target. The path is a TYPE PATH in a string \
                         literal, and it resolves in the declaring scope.";

/// The refusal `ref(type = …)`'s value gets when it is not a path.
const REF_TYPE: &str = "`type` names the record this field refers to, as a type path in a string \
                        literal";

/// The refusal a `derived(…)` entry this grammar cannot read gets. Both forms again, and the
/// entry's NAME is the position rather than the source — which is the half a reader gets wrong.
const DERIVED_SHAPE: &str = "a reverse position is `<name> = \"path::to::Source\"`, or \
                             `<name>(type = \"path::to::Source\", field = \"…\")` where the source \
                             refers to this record through more than one field. The NAME is what \
                             this record calls the position; the path is the record that points \
                             back.";

/// The refusal a `locate(…)` entry this grammar cannot read gets. BOTH forms, exactly as its sibling
/// shows both, and the sentence says which half is which for [`DERIVED_SHAPE`]'s reason — the NAME
/// is the half a reader gets backwards.
const LOCATE_SHAPE: &str = "an artifact position is `<name> = \"path::to::Family\"`, or \
                            `<name>(family = \"path::to::Family\", data)` where the position also \
                            asks for the bytes. The NAME is the word this record answers the \
                            address under; the path is the `#[ingraph::blob]` node that holds the \
                            artifacts — the TYPE, not a field inside it.";

/// The refusal an artifact position's full form gets when it named no family.
///
/// Its own sentence rather than [`LOCATE_SHAPE`]: an author who wrote `<name>(data)` has the FORM
/// right and left out the one option that is not optional, so the useful answer names that option
/// rather than restating both spellings of the entry.
const LOCATE_FAMILY_MISSING: &str = "an artifact position's full form names the family it addresses \
                                     — write `family = \"path::to::Family\"` inside it. A position \
                                     that asks for nothing else is spelled `<name> = \
                                     \"path::to::Family\"`.";

/// The refusal an artifact position's `family` gets when it is not a path.
const LOCATE_FAMILY: &str = "`family` names the `#[ingraph::blob]` node this position addresses, as \
                             a type path in a string literal";

/// The refusal an unknown option inside an artifact position's full form gets, with the three words
/// it takes.
const LOCATE_OPTIONS: &str = "unknown entry in an artifact position — it takes `family = \"…\"`, \
                              the `data` ask, and `required`, which publishes the ADDRESS as \
                              `BlobLocation!`. There is no word for the nullable form: it is what \
                              you get by leaving `required` out";

/// The words an artifact position's full form takes, for the near-miss line.
///
/// Written once and spent at every refusal inside the form, so a word added here cannot be added to
/// the vocabulary a typo is measured against and forgotten at the sentence, or the other way round.
const LOCATE_WORDS: [&str; 3] = ["family", "data", REQUIRED];

/// The refusal `derived(…)`'s OWN option words get inside an artifact position's full form.
///
/// Answered BY NAME rather than through [`LOCATE_OPTIONS`], and for the reason the old whole-form
/// refusal gave: these are real words of the sibling this position shares a reader with, so their
/// author is asking for something coherent rather than making a shape mistake. `type` is `family`
/// under the other word's spelling — one value, two names, and this face has to pick one — and
/// `field` is answered before it can be asked, an artifact family being derived from exactly one
/// upstream.
const LOCATE_SIBLINGS_WORDS: &str = "`type` and `field` are `derived(…)`'s option words. An \
                                     artifact position names its family with `family = \
                                     \"path::to::Family\"`, and it is derived from ONE upstream — \
                                     so there is no second `ref` column for a `field` to select.";

/// The refusal the `data` ask gets when it carries anything but a name.
///
/// The word is BARE on the family's own head and MAY CARRY A VALUE here, and the asymmetry is what
/// the two words are: the family's is a PERMISSION, which is a yes with nothing to say about a
/// schema, and this one is an ASK, which mints a wire field and may therefore be told what to call
/// it.
const LOCATE_DATA_SHAPE: &str = "the `data` ask is written bare, `data = \"thumbBytes\"` to name \
                                 the wire field, or `data(rename = \"…\", required)` to say both. \
                                 The default name is `<name>Data`, off this position's own word.";

/// The refusal a `data(rename = …)` whose value is not a written word gets.
///
/// Its own sentence rather than [`LOCATE_DATA_SHAPE`]: an author inside the block has the FORM right
/// and one entry wrong, so restating all three spellings would bury the useful half.
const LOCATE_DATA_RENAME: &str = "`rename` names the wire field, in a string literal — \
                                  `data(rename = \"thumbBytes\")`";

/// The refusal an unknown entry inside a `data(…)` ask gets.
const LOCATE_DATA_OPTIONS: &str = "unknown entry in a `data(…)` ask — it takes `rename = \"…\"`, \
                                   which names the wire field, and `required`, which makes it \
                                   `String!`. There is no word for the nullable form: it is what \
                                   you get by leaving `required` out";

/// The words a `data(…)` ask takes, for the near-miss line.
const LOCATE_DATA_WORDS: [&str; 2] = ["rename", REQUIRED];

/// The one-way non-null word, spelled once for both STORE-MEDIATED positions that take it.
///
/// # ONE WORD, ONE MEANING, TWO POSITIONS
///
/// The ADDRESS and the BYTES are both nullable by default and both take this word as the author's
/// INFORMED SIGNATURE — *in my deployment this is present by read time* — which promotes the emitted
/// field to `BlobLocation!` and `String!` respectively. Nullable is the DEFAULT TRUTH at either:
/// artifacts are written by the indexing pipeline asynchronously after the entity exists, so *not
/// yet generated* is a normal state and a field that says so is telling the truth.
///
/// The word is therefore ONE-WAY at both — there is no `nullable`, because not writing this is what
/// nullable means — and the two positions share this spelling, [`LOCATE_REQUIRED_IS_BARE`] and the
/// repeat sentence for the same reason every shared word shares its refusals: two voices for one
/// mistake is how a grammar comes to mean two things by one word.
const REQUIRED: &str = "required";

/// The refusal `required` gets when it carries anything, at either position that takes it.
const LOCATE_REQUIRED_IS_BARE: &str = "`required` is a BARE word — write it and the field is \
                                       non-null, leave it out and it is nullable. There is nothing \
                                       for it to carry, and there is no inverse word either: \
                                       nullable is what not writing this one means";

/// The refusal a MULTI-SEGMENT left side gets, and the reason it is not [`LOCATE_SHAPE`]: an author
/// who writes `locate(media::Cover = "…")` has read the entry backwards in a specific way, believing
/// the left side refers to the family, and the useful answer names what the left side actually is.
const LOCATE_MINTS_ITS_OWN_WORD: &str = "the left side of an artifact position is a WORD this \
                                         record mints — `thumb`, `cover`, `poster` — and a path \
                                         has nowhere to be minted from. The TYPE goes on the \
                                         right, in a string literal: `cover = \
                                         \"path::to::Family\"`.";

/// The family this grammar RESERVES a word for and ships no filter behind.
const MAP: &str = "map";

/// The refusal `map` gets, and it is a reservation rather than an unknown word: an author who
/// writes one has a concrete idea, and the useful answer is that the word is spoken for.
const MAP_RESERVED: &str = "`map` is RESERVED with the map family — this framework ships no map \
                            filter for a label to name, so the word arrives with the filter rather \
                            than before it";

/// The refusal an element-level custom marker gets. Reserved rather than unknown, for [`MAP`]'s
/// reason: nobody has asked for one, and the day somebody does the escape has a shape to take.
const ELEMENT_CUSTOM: &str = "an element-level custom marker is RESERVED — a collection's element \
                              is one of the framework's words, and \
                              `label = \"a::marker::Path\"` is the FIELD's escape";

/// The refusal a nested COLLECTION gets, and the measurement behind it: SQL edge elements have no
/// `Vec<_>` carrier, and no MongoDB carrier row produces a `Bson::Array`.
const NESTED_COLLECTION: &str = "no backend carries a collection of collections — a nested \
                                 collection is a filter-face composition only";

/// The STORAGE word a persisted collection may write on the field:
/// `#[ingraph(list(scalar), sortable)]`.
///
/// It says nothing about what the collection HOLDS — the element label already does — and everything
/// about how the row carrying it is ORDERED: a database that keeps the collection in a table of its
/// own mirrors its order into a companion column beside the row, and a term over it becomes the
/// statement's where it was a remainder.
///
/// A DIALECT-FREE word, beside the per-database blocks rather than inside one, because it
/// is ONE intent from which each database derives its own mechanism: a dialect storing the
/// collection as a native array already orders it and mints nothing, the ones storing edge rows mint
/// the companion, and a document store is a remainder either way. A per-database seat would
/// double-book with the per-database storage word and let one declaration ask two databases for two
/// different orders of the same written question.
///
/// `pub(crate)` because the INTERFACE grammar refuses the same word at its own storage seat, and one
/// spelling is what keeps the two front ends talking about one word.
pub(crate) const SORTABLE: &str = "sortable";

/// The ACCESS word a persisted collection may write on the field:
/// `#[ingraph(list(scalar), indexed)]`.
///
/// # What it buys, and what already existed
///
/// A collection's elements live in a table of their own, keyed on the row. The index the framework
/// DERIVES over one leads on the KEY — `(key…, value…)` — so it answers *does THIS row's list hold
/// `dog`*, which is the correlated membership probe a filter over a known row makes. It cannot
/// answer the other direction: *which rows' lists hold `dog`*, entered from a value the caller has
/// and a row it has not, which is what a label search over a whole library is. A set's primary key
/// leads on the key too, so a set is in the same position.
///
/// The word puts a SECOND index on that table with the columns in the other order — `(value…,
/// key…)` — and on SQLite it makes the element column case-tolerant, so `dog` typed by a person
/// finds the `Dog` a model wrote without either being rewritten. It is OPT-IN because the cost is
/// real and one-directional: a structure maintained on every element written, and — where the fold
/// applies — a set holding `Dog` and `dog` as ONE element.
///
/// # It sits at the FIELD, beside [`SORTABLE`], and the two reasons are not the same weight
///
/// The first is that word's: ONE intent from which each database derives its own mechanism — a
/// second index where the collection is a second table, a GIN index where it rides an array column
/// of the row — so a per-database seat would double-book with `edge`, which already says which of
/// those a database does.
///
/// The second is heavier and is this word's alone. The SQLite path FOLDS CASE, and a fold is visible
/// in a SET's own identity: a collection indexed on one database and not another would hold one
/// element in one store and two in the other, off a single written declaration. A per-database seat
/// is therefore not merely redundant here but a way to write a record that means two different
/// things — the trap [`refuse_unique_on_a_collection`]'s own note names one word over.
///
/// A `set(…)` takes the word where [`SORTABLE`] is a list's alone: an order is what a set declares
/// it has not got, and a membership is exactly what a set has.
pub(crate) const INDEXED: &str = "indexed";

/// The refusal `indexed` gets at the FIELD on anything that is not a collection — a REDIRECT, the
/// word having a real seat one namespace in.
///
/// A single column's index is a per-DATABASE choice: nothing about one is visible to a client, so a
/// declaration may reasonably want it on the store that serves the queries and not on the one that
/// takes the writes. A COLLECTION's is not — see [`INDEXED`], where the case fold makes the word
/// semantic — so the two seats answer two questions and this sentence is what tells them apart.
///
/// It replaces what this seat used to answer for the word, which was [`misplaced`]'s PER-DATABASE
/// sentence: the same redirect, in a sentence that also says why a collection's is different.
const INDEXED_NEEDS_A_COLLECTION_WORD: &str = "`indexed` at the FIELD is a COLLECTION's word — it puts a second index on the elements' own \
   table, leading on the VALUE where the derived one leads on the key, so that *which rows hold \
   this element* is a seek rather than a scan. A single column's index is a PER-DATABASE choice and \
   is written in that database's own block, as `#[ingraph(sqlite(indexed))]`: nothing about one is \
   visible to a client, so a declaration may want it in one store and not the next. Write a \
   collection word here (`#[ingraph(list(scalar), indexed)]`), or move this one into a block.";

/// The refusal `indexed` gets beside `label = "a::marker::Path"`, for [`SORTABLE_READS_NO_PATH`]'s
/// reason: a path is a name and not a family, so nothing on the field says there are elements.
const INDEXED_READS_NO_PATH: &str = "`label = \"…\"` names a marker this grammar cannot classify — a path is a name here, not a family \
   — and `indexed` is a COLLECTION's word, so nothing on this field says there are elements for a \
   second index to lead on. A collection declares itself with `list(…)` or `set(…)`; a single \
   column's index is its database's own block, as `#[ingraph(sqlite(indexed))]`";

/// The refusal a repeated `indexed` gets. One collection, one access path.
const INDEXED_ONCE: &str = "`indexed` is declared more than once on this field — one word, one \
                            access path";

/// The column a WRITE computes, at the seat the fragment tier spells `record(derived(…))`.
///
/// Read as a word at BOTH saddles so the record's own field seat answers with the seat's rule rather
/// than with an unknown entry — the same shape `record(sortable)` takes one namespace in, pointed
/// the other way.
const DERIVED_COLUMN: &str = "derived";

/// What the record's own field seat answers `derived(…)` with — the seat's rule, and the
/// measurement behind it.
///
/// # It is a WAIT rather than a wall, and the difference is the number of lists
///
/// A fragment publishes THREE storage faces and every one of them is dialect-free: one
/// `ColumnKind::SEGMENTS`, one `Carrier<Db>` generic in its dialect, one `Assemble` over a row. A
/// derived column joins the first two and stays out of the third, and that is the whole of the seat
/// there.
///
/// A record's are PER DATABASE and there are nine of them — a `COLUMNS` const, a DDL plan, an
/// `INSERT` list, a bind by ordinal, a `SELECT`, a decode, an order-by vocabulary, a cursor slot
/// list and a wire face — each walking the record's own field list, where a column that is not a
/// field has no entry to be. So the word is grammar at both saddles and teeth at one, and the
/// refusal says which rather than accepting a sentence nothing would emit.
const DERIVED_COLUMN_AT_A_RECORD: &str = "`derived(…)` at a RECORD's field is grammar this round and teeth the next. A column the write \
   computes joins a layout, and a fragment has ONE layout to join — `ColumnKind::SEGMENTS`, carrying \
   no dialect — while a record has one per database, plus the ordinal bind, the raise, the order-by \
   vocabulary and the cursor slots that all walk the record's own FIELD list, where a column that is \
   no field has no entry to occupy. Write the value as a `#[ingraph::fields(record(…))]` fragment \
   and derive the column there, where the layout is one list and the position is the source field's \
   own; the record then stores the fragment and gets the derived column with it";

/// The two TRANSFORM words, at the seat the fragment tier spells `record(write = "…")` /
/// `record(read = "…")`.
///
/// Read as words at BOTH saddles for [`DERIVED_COLUMN`]'s reason: the record's own field seat
/// answers with the seat's rule rather than with an unknown entry, and an author who wrote one
/// learns where it has teeth instead of being told it does not exist.
const WRITE_TRANSFORM: &str = "write";

/// The READ-path half of the pair above.
const READ_TRANSFORM: &str = "read";

/// What the record's own field seat answers `write = "…"` / `read = "…"` with — the seat's rule, and
/// the two words already sitting where its teeth would go.
///
/// # It is a COLLISION rather than a wait, and that is the difference from `derived`
///
/// A derived column has nowhere to be at a record because the record's nine faces walk its FIELD
/// list; the word waits for a layout that can carry one. A transform has somewhere to be — a
/// record's bind and its crossing are as real as a fragment's — and what it would land ON is
/// already occupied, by two seats a record has and a fragment does not:
///
/// * `<db>(type = "…", into = "…", from = "…")` is the per-DATABASE stored form and its two
///   crossings, which is `write`/`read` scoped to one dialect and answering the further question of
///   what the column's stored TYPE is;
/// * `graphql(input(comparison(<db>(into = "…"))))` is the per-dialect OPERAND converter, which is
///   the second of the two sites this seat exists to keep in agreement with the first.
///
/// So the record already spells both halves, per dialect, and a dialect-free pair beside them would
/// be a third spelling whose interaction with the two is a ruling nobody has made. The fragment tier
/// has neither seat — it admits no per-dialect rendering word at all, which its crossing's own note
/// records — and that absence is exactly why the pair lands there first.
///
/// The migration is therefore a REAL one rather than a holding sentence: the value moves into a
/// fragment, the fragment carries the transform, and the record stores the fragment.
///
/// It names BOTH of the fragment tier's seats, because the two answer different questions and an
/// author arriving here has one or the other: `record(write = "…")` on a FIELD is a `fn(&T) -> T`
/// over that column's type, and the same word at the fragment's HEAD is a `fn(&Self) -> Self` over
/// the whole value — which is what a canonical form reading several columns needs.
const TRANSFORM_AT_A_RECORD: &str = "the transform seats are the FRAGMENT tier's, and at a record \
   the two halves are already spelled: `#[ingraph(<db>(type = \"…\", into = \"…\", from = \"…\"))]` \
   is the stored form and its crossings per database, and \
   `#[ingraph::record(graphql(input(comparison(<db>(into = \"…\")))))]` converts the query operand \
   that has to agree with the bind. A dialect-free `write`/`read` beside those would be a third \
   spelling of one question, so it is not read here. The tier that HAS no per-dialect rendering \
   word is where the pair lands: write the value as a `#[ingraph::fields(record(…))]` fragment and \
   store the fragment — `record(write = \"…\")` on a FIELD there is a `fn(&T) -> T` over that \
   column's type, and the same word at the fragment's HEAD is a `fn(&Self) -> Self` over the whole \
   value, which is what a canonical form that reads several columns at once needs";

/// The sentence the OLD spelling is TAUGHT with — `list(scalar, sortable)`, the dead seat, pointing
/// at the field's own.
///
/// A refusal rather than a silent move, and a TEACHING one rather than the label vocabulary's
/// unknown-element row, for [`WRITE_SITS_IN_THE_POLL`]'s reason: the word was legal one ruling ago,
/// so a declaration carrying it is one whose author has to be told where the word went rather than
/// one whose author mistyped a family name.
const SORTABLE_MOVED_INTO_PERSIST: &str = "`sortable` is the FIELD's own word now, not the label's \
                                           — write `#[ingraph(list(scalar), sortable)]`. A label \
                                           says what a column is READ AS and this says what the \
                                           STORAGE does with one: the companion column is a fact \
                                           about how the collection persists, so it is seated with \
                                           the other storage words and composes with a database's \
                                           own block as `#[ingraph(sortable, postgres(edge))]`.";

/// The refusal `sortable` gets on a VALUE family. A stored scalar is already orderable,
/// which is what the `orderable` marker's own refusal says one layer out.
fn sortable_takes_a_collection(label: Label) -> String {
  format!(
    "`{word}` names a VALUE family and `sortable` orders a COLLECTION — a stored scalar is \
     orderable because it is stored, so there is nothing for the word to add",
    word = label.as_str(),
  )
}

/// The refusal `sortable` gets on a `set(…)`. A set declares that its order carries no
/// meaning, and the companion column would be the order of a sequence the declaration says it does
/// not have.
const SORTABLE_IS_A_LISTS_WORD: &str = "`set` declares that ORDER carries no meaning in this \
                                        collection, and `sortable` is an order — the word belongs \
                                        to a `list(…)`, whose elements have positions. A set \
                                        ordered by its stored sequence would be ordered by \
                                        something the declaration says is not there.";

/// The refusal `sortable` gets on a KEY-SIDE column, which declares no label.
///
/// A shape the old seat could not reach: the word used to be written inside a collection's own
/// parentheses, so a collection came with it. Written on the field it can stand on one whose
/// vocabulary is the sealed `Id` trait — where no label rule says anything — so this is the one seat
/// at which the word would otherwise mirror nothing in silence.
const SORTABLE_NEEDS_A_COLLECTION_WORD: &str = "`sortable` orders a COLLECTION and a KEY-SIDE \
                                                column declares no label at all — its vocabulary is \
                                                the sealed `Id` trait, and an identity is one \
                                                value. The word belongs on a data field carrying a \
                                                collection's own word, as \
                                                `#[ingraph(list(scalar), sortable)]`";

/// The refusal `sortable` gets on a DATA column that wrote no label.
///
/// [`SORTABLE_NEEDS_A_COLLECTION_WORD`]'s twin, and it exists because the two seats stopped being
/// one: while the mandatory-label rule stood, a data field with no label was answered by it and this
/// check deferred, so the only silence left to answer was a key column's. The participation
/// inversion deleted that rule — a column's kind is read off its type now — and the deferral would
/// have left a `sortable` beside no collection word reaching no sentence at all.
///
/// Two sentences rather than one, because the two fields are told different things: a key column is
/// told the word cannot belong to it, and a data column is told the word it is MISSING. One sentence
/// covering both would have to say *a key-side column declares no label* to an author looking at a
/// `Vec<String>`, which is a true rule about a different field.
const SORTABLE_NEEDS_A_COLLECTION_WORD_HERE: &str = "`sortable` orders a COLLECTION and this column \
                                                     names no family at all — the word says the \
                                                     stored order is kept, and only a declaration \
                                                     can say a column IS a collection, a macro \
                                                     holding tokens being unable to read it out of \
                                                     a type. Write the collection's own word beside \
                                                     it, as \
                                                     `#[ingraph(list(scalar), sortable)]`";

/// The refusal `sortable` gets beside `label = "a::marker::Path"`.
///
/// The grammar used to answer this by construction — the word sat inside a collection's parentheses
/// and a path has none. At the new seat the two can be written together, and the answer is the same
/// one the marker layer gives everywhere: a macro holds tokens, so a path is a name and never a
/// classification.
const SORTABLE_READS_NO_PATH: &str = "`label = \"…\"` names a marker this grammar cannot classify — \
                                      a path is a name here, not a family — and `sortable` orders a \
                                      COLLECTION, so the two cannot be written together. A \
                                      declaring crate that wants the companion column writes the \
                                      collection's own word and names its element.";

/// The refusal a repeated `sortable` gets. One collection, one intent.
const SORTABLE_ONCE: &str = "`sortable` is declared more than once on this field — one word, one \
                             collection";

/// The refusal a collection carrying SEVERAL element labels gets. One element, because a collection
/// holds one type.
const ONE_ELEMENT: &str = "a collection's label names ONE element — `list(string)`, never a list of \
                           labels";

/// The refusal a family word carrying a `= value` gets. The word IS the value; a marker the
/// framework ships no word for is the other spelling.
const BARE_WORD: &str = "a family label is a bare WORD — write it alone, as in `string`; a marker \
                         this framework ships no word for goes in `label = \"a::marker::Path\"`";

/// The refusal a repeated label gets. One field is read under one interpretation.
const ONE_LABEL: &str = "a family label is declared more than once on this field — one label, one \
                         field";

/// The payload of [`Written::Word`]: a bare word — `scalar`, `string`, and the two collection words
/// a declaration writes bare only to be told which element is missing.
///
/// It shares the variant's name, which is legal — different namespaces — and says they are the same
/// fact. So do [`Nested`] and [`Custom`] below.
pub(crate) struct Word {
  label: Label,
  /// The word's own token — the span a refusal about this level reports at.
  at: syn::Ident,
}

/// The payload of [`Written::Nested`]: a word carrying a `(…)` — `list(string)`, and
/// `string(scalar)`, which [`shape`] refuses.
pub(crate) struct Nested {
  label: Label,
  at: syn::Ident,
  /// The label inside the parentheses. Boxed because the grammar recurses and a type cannot
  /// contain itself.
  element: Box<Written>,
}

/// The payload of [`Written::Custom`]: `label = "path::To"` — a marker the DECLARING crate owns,
/// reached by path.
pub(crate) struct Custom {
  path: syn::Path,
  /// The option's own token, for the reason the words keep theirs.
  at: syn::Path,
}

/// A label as a DECLARATION writes it: the family word at this level and, where the word carries a
/// `(…)`, the label inside it.
///
/// `pub(crate)` because the INTERFACE grammar reads the same vocabulary at a pin — see
/// [`label`], which is the whole of what that front end needs and the only door it goes through.
///
/// RECURSIVE because the grammar is — every level of a label names its family, so `list(list(scalar))`
/// is three levels and all three are read. What this grammar will not carry is refused by [`shape`]
/// rather than by the reader, and that split is deliberate: a refusal that quotes what was written
/// can only be written by something that read all of it.
///
/// The name grost-mir gives the same tree is `Label`, which here is the WORD — so the tree takes the
/// other half of the same phrase.
pub(crate) enum Written {
  /// A bare word — see [`Word`].
  Word(Word),
  /// A word carrying a `(…)` — see [`Nested`].
  Nested(Nested),
  /// `label = "path::To"` — see [`Custom`].
  Custom(Custom),
}

impl Written {
  /// Whether this level names a COLLECTION — the question the nesting rule asks of an element.
  ///
  /// A [`Custom`](Self::Custom) answers NO, and that is a limit rather than a claim about the
  /// marker: a marker's family is a fact about its trait impls, and this holds a path.
  const fn collection(&self) -> bool {
    match self {
      Self::Word(Word { label, .. }) | Self::Nested(Nested { label, .. }) => label.collection(),
      Self::Custom(_) => false,
    }
  }

  /// The FAMILY WORD this level names, or `None` where the label was reached by path.
  ///
  /// What [`collection`](Self::collection) answers YES or NO to, kept as the word itself — the
  /// storage-word refusals name the family a field declared, and *this field's label is `string`* is
  /// the half of that sentence which tells an author what to change.
  const fn word(&self) -> Option<Label> {
    match self {
      Self::Word(Word { label, .. }) | Self::Nested(Nested { label, .. }) => Some(*label),
      Self::Custom(_) => None,
    }
  }

  /// The MARKER this label resolves to — the whole tree, level by level.
  ///
  /// The element is a WORD or nothing: an element that is itself nested, and an element-level custom
  /// marker, are shapes [`shape`] has already refused, so the tree the emitter receives is exactly
  /// as deep as the grammar admits.
  pub(crate) fn marker(&self) -> Marker {
    match self {
      Self::Word(word) => Marker::Framework(FrameworkMarker {
        label: word.label,
        element: None,
      }),
      Self::Nested(nested) => Marker::Framework(FrameworkMarker {
        label: nested.label,
        element: match *nested.element {
          Self::Word(Word { label, .. }) => Some(label),
          Self::Nested(_) | Self::Custom(_) => None,
        },
      }),
      Self::Custom(custom) => Marker::Path(custom.path.clone()),
    }
  }

  /// A refusal about THIS level, spanned at the token that wrote it.
  pub(crate) fn refuse(&self, message: String) -> syn::Error {
    match self {
      Self::Word(Word { at, .. }) | Self::Nested(Nested { at, .. }) => {
        syn::Error::new_spanned(at, message)
      }
      Self::Custom(custom) => syn::Error::new_spanned(&custom.at, message),
    }
  }
}

/// Whether an entry BEGINS a label — the top level's question, asked before the reader runs so an
/// entry that is not one falls through to the field's other markers and to their refusal.
pub(crate) fn begins_a_label(path: &syn::Path) -> bool {
  path.is_ident(LABEL) || path.is_ident(MAP) || family_word(path).is_some()
}

/// ONE label, read and shape-checked — the whole label grammar behind one door.
///
/// `None` when nothing readable was written, and the refusal is already recorded. The caller decides
/// what a second label on one subject means, because the two front ends word that differently: a
/// record says *one label, one field*, and an interface says *one word, one pin*.
///
/// # It exists because the two front ends read ONE vocabulary
///
/// The record's own call site keeps the [`Written`] tree, which it needs for a question this
/// signature cannot answer — whether the label named a collection, asked long after the walk to
/// settle an `Option` around the field. An interface pin has no such second reader, so it takes the
/// [`Marker`] and nothing else.
pub(crate) fn label(meta: &syn::meta::ParseNestedMeta<'_>, errors: &mut Errors) -> Option<Written> {
  let declared = written(meta, errors)?;
  shape(&declared, 0, errors);
  Some(declared)
}

/// The same vocabulary as the NEAR-MISS reader compares against: the shipped words plus the custom
/// escape's own key, which is every word a label position takes.
///
/// One list beside [`label_vocabulary`]'s one sentence, so the two front ends that read this
/// grammar suggest from what they teach.
pub(crate) fn label_words() -> Vec<&'static str> {
  Label::ALL
    .into_iter()
    .map(Label::as_str)
    .chain(core::iter::once(LABEL))
    .collect()
}

/// The label vocabulary as a REFUSAL lists it — the shipped words, the element position, and the
/// custom escape.
///
/// One sentence, so an interface's unknown-entry refusal and a record's name the same grammar.
pub(crate) fn label_vocabulary() -> String {
  format!(
    "its interpretation WORD: {list}, a collection's element inside it (`list(string)`), or \
     `label = \"a::marker::Path\"`",
    list = shipped(Label::ALL.into_iter().map(Label::as_str)),
  )
}

/// The family word a path spells, if it spells one.
///
/// `unraw` for the reason [`marker`]'s own note gives: `r#enum` is a different token from `enum`,
/// and it is the spelling a Rust author reaches for by reflex.
fn family_word(path: &syn::Path) -> Option<Label> {
  let word = path.get_ident()?.unraw();
  Label::ALL.into_iter().find(|label| word == label.as_str())
}

/// Read ONE level of a label, and every level below it.
///
/// `None` when nothing readable was written, and the refusal is already recorded. The unknown-word
/// branch is reachable from an ELEMENT position only — the top level asks [`begins_a_label`] first,
/// so a field entry that is not a label reaches the field's own unknown-attribute refusal instead
/// of being answered about a vocabulary it was not writing.
fn written(meta: &syn::meta::ParseNestedMeta<'_>, errors: &mut Errors) -> Option<Written> {
  if meta.path.is_ident(LABEL) {
    return match value::parse_literal::<syn::Path>(meta, &label_shape()) {
      Ok(path) => Some(Written::Custom(Custom {
        path,
        at: meta.path.clone(),
      })),
      Err(e) => {
        errors.push(e);
        None
      }
    };
  }
  if meta.path.is_ident(MAP) {
    // A word this grammar RESERVES, matched exactly.
    errors.push(attribute::unknown(meta, MAP_RESERVED, &[]));
    return None;
  }
  let Some(label) = family_word(&meta.path) else {
    // Spanned at what was WRITTEN and quoting the normalised word, exactly as `marker` is.
    let spelled = meta.path.get_ident().cloned();
    let message = spelled
      .as_ref()
      .map_or_else(label_shape, |spelled| unknown_element(&spelled.unraw()));
    // THE ELEMENT POSITION's own words: the shipped families, and the collection's FIELD-INTENT
    // word, which `nested` reads before recursing here. `label` is deliberately absent — an
    // element-level custom marker is RESERVED, so offering it would send a reader to a second
    // refusal.
    errors.push(attribute::unknown(
      meta,
      &message,
      &Label::ALL
        .into_iter()
        .map(Label::as_str)
        .chain(core::iter::once(SORTABLE))
        .collect::<Vec<_>>(),
    ));
    return None;
  };
  let at = meta
    .path
    .get_ident()
    .cloned()
    .expect("a family word is one ident");
  if attribute::has_value(meta) {
    // A family word spelled right and written the wrong SHAPE.
    errors.push(attribute::unknown(meta, BARE_WORD, &[]));
    return None;
  }
  // A bare word and an empty `()` are the same declaration, and both are a level with no element —
  // `shape` is where a collection is told it needs one.
  if !attribute::has_block(meta) || attribute::empty_group(meta) {
    attribute::skip_entry(meta);
    return Some(Written::Word(Word { label, at }));
  }
  let mut element: Option<Written> = None;
  let mut extra = false;
  let walked = meta.parse_nested_meta(|inner| {
    // The STORAGE word is caught HERE and not by the recursion, exactly as it was while it was read
    // here: a walk that let it fall through would answer it as an unknown interpretation and offer
    // the list of families it is not one of, where what its author needs is the container it moved
    // to. Spanned at the WORD rather than at the collection's own token, because the word is what
    // has to move.
    if inner.path.is_ident(SORTABLE) {
      errors.push(attribute::named(
        &inner,
        SORTABLE_MOVED_INTO_PERSIST.to_owned(),
      ));
      return Ok(());
    }
    match (written(&inner, errors), &element) {
      (Some(read), None) => element = Some(read),
      (Some(_), Some(_)) => extra = true,
      (None, _) => {}
    }
    Ok(())
  });
  if let Err(e) = walked {
    errors.push(e);
  }
  if extra {
    errors.push(syn::Error::new_spanned(&at, ONE_ELEMENT));
  }
  element.map(|element| {
    Written::Nested(Nested {
      label,
      at,
      element: Box::new(element),
    })
  })
}

/// Refuse the label SHAPES this grammar reads and will not carry.
///
/// Separate from the reader because the tree is read WHOLE — see [`Written`] — and because these
/// are facts about the shape rather than about the tokens: which words take an element, which
/// element positions the framework has a carrier for, and where the custom escape lives.
///
/// `depth` is the level's distance from the field, which is the only thing the custom escape's rule
/// needs: it is the FIELD's, so it is refused everywhere else.
fn shape(written: &Written, depth: usize, errors: &mut Errors) {
  match written {
    Written::Custom(_) => {
      if depth > 0 {
        errors.push(written.refuse(ELEMENT_CUSTOM.to_owned()));
      }
    }
    Written::Word(word) => {
      if word.label.collection() {
        errors.push(written.refuse(bare_collection(word.label)));
      }
    }
    Written::Nested(nested) => {
      if !nested.label.collection() {
        errors.push(written.refuse(value_takes_no_element(nested.label)));
      } else if nested.element.collection() {
        // The one refusal for one mistake: the element's own bare-collection complaint would be a
        // second sentence about the same tokens, and it is not the one that answers.
        errors.push(written.refuse(NESTED_COLLECTION.to_owned()));
        return;
      }
      shape(&nested.element, depth + 1, errors);
    }
  }
}

/// The refusal a collection word written BARE gets — the nesting rule, named.
fn bare_collection(label: Label) -> String {
  format!(
    "`{word}` names a COLLECTION and a collection has elements — write the element's own label \
     inside it, as in `{word}(string)`. Every level of a label names its family.",
    word = label.as_str(),
  )
}

/// The refusal a VALUE family carrying an element gets. A value has no elements, so the element
/// position belongs to the two words that do.
fn value_takes_no_element(label: Label) -> String {
  format!(
    "`{word}` names a VALUE family and a value has no elements — an element label belongs to \
     `list(…)` and `set(…)`",
    word = label.as_str(),
  )
}

/// Refuse `sortable` where the field's LABEL names nothing the word can order.
///
/// Beside the mandatory-label rule rather than inside the field's own walk, and for its reason
/// twice over. The two halves are written in two entries and in either order —
/// `#[ingraph(sortable, list(scalar))]` and its reverse are one declaration — so the
/// question can only be asked once both slots are filled. And a field carrying NO label is answered
/// by whichever of the two sides it fell on, which is the record's declaration to know: a key-side
/// column is exempt from declaring a kind, so nothing else here would tell it the word had nothing
/// to order.
///
/// This cross-entry check is the new seat's whole cost. At the old one the word sat inside the
/// collection's own parentheses, so a collection was present by construction.
///
/// It ANSWERS a non-key field with no label now, where it used to defer, and it answers with a
/// SENTENCE OF ITS OWN: the mandatory-label rule it deferred to is gone with the participation
/// inversion, so a `sortable` written beside no collection word would otherwise have reached nothing
/// at all — and the key-side sentence, reused, would have told an author looking at a `Vec<String>`
/// that key columns declare no label. This is the one cell where the expansion genuinely needs the
/// word: the storage form a collection takes is decided at expansion time, and a macro holding
/// tokens cannot read *is this a list* out of a type.
///
/// Still silent where the label was REFUSED, for [`Markers::label_refused`]'s reason: one mistake,
/// one sentence.
fn refuse_a_storage_word_no_label_can_order(markers: &Markers, in_key: bool, errors: &mut Errors) {
  if let Some(at) = markers.storage.sortable.as_ref() {
    let refusal = match markers.label.as_ref() {
      None if markers.label_refused => None,
      None if in_key => Some(SORTABLE_NEEDS_A_COLLECTION_WORD.to_owned()),
      None => Some(SORTABLE_NEEDS_A_COLLECTION_WORD_HERE.to_owned()),
      Some(declared) => match declared.word() {
        None => Some(SORTABLE_READS_NO_PATH.to_owned()),
        Some(Label::Set) => Some(SORTABLE_IS_A_LISTS_WORD.to_owned()),
        Some(Label::List) => None,
        Some(word) => Some(sortable_takes_a_collection(word)),
      },
    };
    if let Some(refusal) = refusal {
      errors.push(syn::Error::new_spanned(at, refusal));
    }
  }
  refuse_an_access_word_no_label_can_seek(markers, errors);
}

/// Refuse `indexed` at the FIELD where the label names nothing with ELEMENTS to seek.
///
/// [`refuse_a_storage_word_no_label_can_order`]'s twin, in the same cell and for the same reason:
/// the word and its collection are two entries written in either order, so the question can only be
/// asked once both slots are filled.
///
/// It answers with ONE sentence where `sortable` has four, and the difference is that this word has
/// somewhere else to be. `sortable` on a scalar is a mistake with no other seat — a stored scalar is
/// already orderable — so its refusals differ by what the author seems to have meant. `indexed` on a
/// scalar is the RIGHT idea at the WRONG seat: the per-database block takes it, and one redirect
/// says so whether the field is key-side, data-side, labelled as a value or labelled by a path.
/// [`INDEXED_READS_NO_PATH`] is the one variant, and only because a custom label names nothing this
/// grammar can classify, so *write a collection word* has to say which words those are.
///
/// A `set(…)` is admitted where `sortable` refuses one: a set has no order and this word is not one.
///
/// Silent where the label was REFUSED, for [`Markers::label_refused`]'s reason: one mistake, one
/// sentence.
fn refuse_an_access_word_no_label_can_seek(markers: &Markers, errors: &mut Errors) {
  let Some(at) = markers.storage.indexed.as_ref() else {
    return;
  };
  let refusal = match markers.label.as_ref() {
    None if markers.label_refused => return,
    None => INDEXED_NEEDS_A_COLLECTION_WORD.to_owned(),
    Some(declared) => match declared.word() {
      None => INDEXED_READS_NO_PATH.to_owned(),
      Some(Label::List | Label::Set) => return,
      Some(_) => INDEXED_NEEDS_A_COLLECTION_WORD.to_owned(),
    },
  };
  errors.push(syn::Error::new_spanned(at, refusal));
}

/// The `skip` word's teeth, on both axes and at both SCOPES: IDENTITY is unskippable, an address
/// step is a column of EVERY database, and one field cannot both skip a column and store it.
///
/// Beside [`refuse_a_storage_word_no_label_can_order`] and for the same reason: which side of the
/// KEY a field is on is the RECORD's declaration to know, so the question can only be asked once the
/// lineage walk has finished.
///
/// # Why identity is unskippable rather than merely unwise
///
/// An address is `lineage ⊕ id` and every step of it is a column of the row a statement reaches by.
/// A skipped step is a step nothing writes and nothing reads — the row cannot be addressed, the key
/// cannot be rebuilt, and a fill would invent an identity rather than recover one. So both axes
/// refuse it, and the wire axis refuses it for the second half of the same reason: the address is
/// what a hit answers with, and a published address missing a step addresses nothing.
///
/// # And why a PARTIAL absence is refused there too — the all-databases-present law
///
/// The participation model lets an ordinary column live in some of a record's databases and not in
/// others; a read of a database that has none hands back the fill the declaration named. An address
/// step cannot take that road, and the reason is the one above with one word changed: a fill would
/// invent an identity in the database that narrowed the step away. It is also what a PAGE resumes
/// from — a keyset compares the address after every ordered column — so a record whose address
/// existed in one store and not the next would page in one and not the other. Both narrowing
/// spellings are refused at the word that wrote them.
fn refuse_a_skip_the_record_cannot_survive(
  markers: &Markers,
  name: &syn::Ident,
  in_key: bool,
  in_lineage: bool,
  errors: &mut Errors,
) {
  if in_key {
    let bearing = if in_lineage {
      "is a step of the record's LINEAGE"
    } else {
      "is the record's `id`"
    };
    let storage = format!(
      "`{name}` {bearing}, and `skip` says a field is not there — an address whose step is missing \
       addresses nothing: no statement reaches the row, no key is rebuilt from it, and a fill would \
       INVENT an identity rather than recover one. Identity is unskippable on both axes."
    );
    let wire = format!(
      "`{name}` {bearing}, and `skip` withholds a field from the schema — the address is what a hit \
       answers with, so a published key missing a step names no row a client can ask for again. \
       Identity is unskippable on both axes."
    );
    if let Some(skip) = &markers.skip {
      errors.push(syn::Error::new_spanned(&skip.at, storage));
    }
    if let Some(at) = markers
      .graphql
      .as_ref()
      .and_then(|wired| wired.skip.as_ref())
    {
      errors.push(syn::Error::new_spanned(at, wire.clone()));
    }
    for per in markers
      .graphql
      .iter()
      .flat_map(|wired| &wired.per_backend)
      .filter_map(|backend| backend.skip.as_ref())
    {
      errors.push(syn::Error::new_spanned(per, wire.clone()));
    }
    // THE PARTIAL ABSENCE, refused at the word that narrowed. Both spellings reach it — a bare
    // `<db>` keeps the databases it names, and `<db>(skip(default = "…"))` drops the one it names —
    // and neither is a road an address may take.
    let narrowed = markers
      .storage
      .per_db
      .iter()
      .filter(|per| per.bare || per.skip.is_some());
    for per in narrowed {
      errors.push(syn::Error::new_spanned(
        &per.at,
        format!(
          "`{name}` {bearing}, and this word makes it a column of some of the record's databases \
           and not the others — an address is `lineage ⊕ id` and every step of it is what a \
           statement reaches the row BY, so a store that narrowed a step away addresses nothing and \
           a fill there would INVENT an identity rather than recover one. It is also what a page \
           resumes from. An address step is a column of every database the record declares."
        ),
      ));
    }
  }
  // The STORAGE WORDS CONTRADICT the absence. `skip` is the whole field's answer — no column in any
  // database — and every word beside it describes the column it says is not there: a `rename` names
  // it, a `<db>(…)` says how one database renders it, and a bare `<db>` keeps a participation the
  // field just gave up in full.
  //
  // The PARTIAL absence is the near miss, and it is the one worth naming: a field that is a column
  // of some databases and not others is exactly what `<db>(skip(default = "…"))` says, and a field
  // that is a column of none is what this word says. Two answers to one question, and the sentence
  // says which is which rather than which law forbids the pair.
  if let (Some(skip), Some(at)) = (&markers.skip, markers.storage.at()) {
    let word = at
      .get_ident()
      .map_or_else(|| "a storage word".to_owned(), |word| format!("`{word}`"));
    errors.push(syn::Error::new_spanned(
      &skip.at,
      format!(
        "`{name}` carries `skip` and {word} — one says the field is a column in NO database and the \
         other describes the column it would be. Drop whichever is not meant: a field absent from \
         SOME of the record's databases writes that database's own \
         `#[ingraph(<db>(skip(default = \"…\")))]`, and one absent from all of them writes this \
         word alone."
      ),
    ));
  }
}

/// The refusal a KEY-SIDE field carrying a family label gets.
///
/// A key column's admission is the sealed `Id` trait, which is a stronger statement than any of
/// these words: it says the type is addressable, where a family word says only how a value is read.
///
/// It is the whole of the label's macro-time law now. Its complement — a data field with a face and
/// no label — was refused beside it until the participation inversion made every data field faced;
/// what answers that field today is `<T as DefaultMarker>::Marker`, at the type.
fn key_side_label(field: &syn::Ident) -> String {
  format!(
    "`{field}` is a key-side column and carries a family label — a key's vocabulary is the sealed \
     `Id` trait, which is stronger than any word, so a key column writes none"
  )
}

/// One backend's block inside a field's `graphql(…)`.
struct FieldBackend {
  kind: GraphqlKind,
  at: syn::Path,
  /// `input(…)` — the field's INPUT position.
  input: Option<FaceBlock>,
  /// `output(…)` — its OUTPUT position. Separate, because the two are different schema positions.
  output: Option<FaceBlock>,
  /// `skip` — this field is absent from THIS backend's vocabulary and present in the next one's.
  skip: Option<syn::Path>,
}

/// The backend a block names, if it names one.
///
/// `pub(crate)` since the index-graphql round: the derived-index grammar grew a `graphql(…)` block
/// of its own, and a second word→backend map beside this one is exactly how two grammars come to
/// disagree about which words name a backend.
pub(crate) fn graphql_kind(path: &syn::Path) -> Option<GraphqlKind> {
  GraphqlKind::ALL
    .into_iter()
    .find(|kind| path.is_ident(kind.as_str()))
}

/// The refusal a `plural` that is not a written word gets.
///
/// A STRING and not an ident, unlike every `rename` in this grammar: a rename names an emitted Rust
/// TYPE, where this names a word in a schema — so the value goes to the wire's own floor, GraphQL's
/// Name grammar, rather than to Rust's. `plural = corpora` without the quotes is the shape a reader
/// most plausibly writes, and this is what it gets.
pub(crate) const PLURAL_WORD: &str = "`plural` is the entity's plural as a WORD, in a string literal — write \
                           `plural = \"corpora\"`";

/// The two markers a reader expects and will not find: `persist` participation already implies both.
const QUERYABILITY: &[&str] = &["filterable", "orderable"];

/// Refuse a marker whose job is already done by storing the field.
fn queryability(option: &syn::meta::ParseNestedMeta<'_>) -> Option<syn::Error> {
  let name = QUERYABILITY
    .iter()
    .find(|name| option.path.is_ident(name))?;
  Some(named(
    option,
    format!(
      "`{name}` is not an option — a field carrying `persist` is filterable and orderable BECAUSE it \
       is stored, and a field that is not stored has nothing to query"
    ),
  ))
}

/// The `lineage(…)` block: the path it names, and what the emitted type is called.
struct LineageBlock {
  /// `fields(…)`'s entries, in the order they were written — resolved to struct fields later.
  /// Never empty; an empty `fields()` is refused rather than treated as a root.
  fields: Vec<LineageField>,
  /// `rename = "…"`, if it was named.
  rename: Option<syn::Ident>,
}

/// One entry of `lineage(fields(…))`: the record field it names, and — for a FUSING node — the
/// parent-key field that column mirrors.
struct LineageField {
  /// The record's own field, which is what `fields(…)` has always named.
  name: syn::Ident,
  /// `<field>(source = "…")` — the parent key's field this column equals, written only where the
  /// two names diverge.
  ///
  /// Absent is not a default filled in later: it means *the same name*, and the mapping the model
  /// carries is built from the record field when nothing was written. So a same-name mirror costs
  /// no words, which is the ruled grammar's whole shape.
  from: Option<syn::Ident>,
}

/// One `upstream(…)` entry on a node that MINTS an id — one upstream of a fusion, as written.
struct UpstreamBlock {
  /// `node = "…"`, when it was named.
  node: Option<syn::Path>,
  /// The bare `key` designation's own path, when this entry carried it.
  key: Option<syn::Path>,
  /// The block's own path, for a refusal about the entry rather than about something inside it.
  at: syn::Path,
}

/// The `subscribe(…)` CONTAINER as written: its entries, and the word's own span.
///
/// A container, where the top-level `upstream(…)` entries are not — and the two are different
/// declarations rather than one written twice. This one shapes the node's INTAKE: which upstreams
/// arrive independently, which are joined by key before the body sees them, and which product of a
/// multi-product upstream an edge carries. The top-level entries answer a question about IDENTITY,
/// which is [`key_parent`]'s.
struct SubscribeBlock {
  /// The entries inside it, in the order they were written.
  entries: Vec<SubscribeEntry>,
}

/// ONE `upstream(…)` entry inside `subscribe(…)`, as written.
struct SubscribeEntry {
  /// `node = "…"`, when it was named.
  node: Option<syn::Path>,
  /// The bare `key`'s own path, when this entry joined the keyed group.
  key: Option<syn::Path>,
  /// `out = "<Variant>"`, when this entry selected one product of several.
  out: Option<syn::Ident>,
  /// `channel = bounded(512)` / `channel = unbounded`, when this entry declared a default for the
  /// edge it opens.
  channel: Option<ChannelOptions>,
  /// `changes(<db>)` / `changes(<db>(external))`, when this entry takes the store's feed instead
  /// of the channel.
  changes: Option<ChangesFeed>,
  /// The bare `notify`'s own path, when this entry asked for the KEY rather than the message.
  notify: Option<syn::Path>,
  /// The entry's own path, for a refusal about the entry rather than about something inside it.
  at: syn::Path,
}

/// The `emits` word as written: the products, and the word's own span.
struct EmitsWord {
  /// The product types, in the order they were written.
  products: Vec<syn::Path>,
  /// The word's own path, for a refusal about the declaration rather than about one product in it.
  at: syn::Path,
}

/// A record's STORAGE, as written: which databases store the rows, and under what names.
///
/// It was `persist(…)`'s block and the words are the same words; what the unwrap changed is that
/// they arrive as SIBLINGS at the head rather than as children of a wrapper, so this struct is
/// assembled entry by entry rather than filled by one walk.
///
/// It carries no span of its own, which the wrapper did. A refusal about the storage AS A WHOLE has
/// nothing left to point at — the wrapper was the token that held one — so the one refusal that
/// needed it, *this record names no store*, reports at the record's own name instead. Every refusal
/// about a WORD still reports at that word.
#[derive(Default)]
struct PersistBlock {
  /// The databases named at the head, in the order they were written.
  databases: Vec<DatabaseBlock>,
  /// `table = "…"` — the common table name.
  table: Option<syn::LitStr>,
  /// `rename = "…"` — the base every emitted row's suffix attaches to. `rename` is uniform: it
  /// names the thing its scope is about, and this scope is the projection as a whole.
  rename: Option<syn::Ident>,
}

/// One database's block inside the record's `persist(…)` — that database's own vocabulary.
struct DatabaseBlock {
  kind: DatabaseKind,
  /// `unique(a, b, …)` — the COMPOSITE constraints this database holds, in written order.
  ///
  /// REPEATABLE where every other entry in this block is once-only, and the difference is what the
  /// word is about: `table` and `row(rename)` each name ONE fact about the projection, so a second
  /// spelling is a contradiction; a constraint is a fact about a TUPLE, and a table may hold several
  /// — `scenes` is addressed by `(media, track, index)` and identified again by `(run, ordinal)`.
  /// So the repeat is the grammar rather than an error, and what IS refused is two words naming the
  /// same entries in the same order. See [`composite_unique`].
  uniques: Vec<CompositeUniqueWord>,
  /// `row(rename = "…")` — what the emitted ROW type is called.
  rename: Option<syn::Ident>,
  /// `comparison(rename = "…")` — what the emitted COMPARISON type is called.
  comparison: Option<syn::Ident>,
  /// `table = "…"` / `collection = "…"`, overriding the head's own [`PersistBlock::table`].
  table: Option<syn::LitStr>,
  /// `schema = "…"`. SQL only.
  schema: Option<syn::LitStr>,
  /// A conversion for the whole row: stored → domain.
  from: ConversionSpec,
  /// A conversion for the whole row: domain → stored.
  into: ConversionSpec,
  /// `alias(…)` — this database's row-source namespace and depth, already held to what the mint can
  /// spend. Settled HERE rather than at the model, because the FENCE reads the prefix while the
  /// fields are still being walked and a value that had not been checked yet would widen it.
  aliases: AliasOptions,
}

/// ONE composite unique as written — the entries it names and the word's own span.
struct CompositeUniqueWord {
  /// The record's fields, in the order the word wrote them. Idents rather than names, because the
  /// audit is against the STRUCT's own fields and the refusal points at the token that named one.
  entries: Vec<syn::Ident>,
  /// The `unique` token itself — the span a refusal about this constraint AS A WHOLE reports at,
  /// where a refusal about one entry reports at that entry.
  at: syn::Path,
}

/// One direction's conversion AS WRITTEN — the two slots the grammar has, so that writing both is
/// detectable at all.
///
/// The model's [`Conversion`] has three states and cannot hold both, which is the point: the rule
/// is structural once the declaration is settled. This is the one place the illegal shape exists,
/// and it exists only long enough to be refused.
#[derive(Default)]
pub(crate) struct ConversionSpec {
  /// `from = "…"` / `into = "…"`.
  infallible: Option<Named>,
  /// `try_from = "…"` / `try_into = "…"`.
  fallible: Option<Named>,
  /// `try_<dir>(error = "…")` — the type this LEG's fallible impls answer with, where the block
  /// admits a cell at all. Only a RECORD-level block does; a field's leg carries the escape and
  /// leaves the type to the record.
  cell: Option<syn::Path>,
}

/// A conversion function, with the option that named it — and, where the leg was written in its
/// STRUCTURED form, the map from its error into the record's.
struct Named {
  /// The function.
  path: syn::Path,
  /// `error_with = "…"` inside the leg — `fn(FnErr) -> RecordErr`, for where `From` cannot hold.
  escape: Option<syn::Path>,
  /// The option's own token — the span a refusal about this spelling reports at.
  at: syn::Path,
}

/// The two spellings one direction has.
#[derive(Clone, Copy)]
pub(crate) struct Direction {
  /// `from` or `into`.
  plain: &'static str,
  /// `try_from` or `try_into`.
  fallible: &'static str,
  /// What the conversion does, for a message: "a read" or "a write".
  what: &'static str,
}

/// `from` BUILDS the projection the block is about — for `persist`, domain → row. A write.
pub(crate) const BUILDS: Direction = Direction {
  plain: "from",
  fallible: "try_from",
  what: "a write",
};

/// `into` LEAVES it — for `persist`, row → domain. A read.
const LEAVES: Direction = Direction {
  plain: "into",
  fallible: "try_into",
  what: "a read",
};

impl Named {
  /// This leg as the model carries it — the function and its escape.
  fn declared(&self) -> FallibleConversion {
    FallibleConversion {
      path: self.path.clone(),
      escape: self.escape.clone(),
    }
  }
}

impl ConversionSpec {
  /// Whether either spelling of this leg was written at all.
  pub(crate) const fn written(&self) -> bool {
    self.infallible.is_some() || self.fallible.is_some()
  }

  /// Record one spelling, refusing a repeat of it.
  fn set(
    &mut self,
    fallible: bool,
    named: Named,
    scope: &str,
    direction: Direction,
    errors: &mut Errors,
  ) {
    let (slot, name) = if fallible {
      (&mut self.fallible, direction.fallible)
    } else {
      (&mut self.infallible, direction.plain)
    };
    let at = named.at.clone();
    set_once(
      slot,
      named,
      &at,
      &format!("`{name}` is declared more than once in {scope} — one option, one value"),
      errors,
    );
  }

  /// The settled conversion, refusing a declaration that wrote BOTH spellings.
  ///
  /// The fallible one is kept, so the rest of the pass reads a declaration that at least admits
  /// failure — the safer of the two to carry past an error.
  pub(crate) fn resolve(
    &self,
    subject: &str,
    direction: Direction,
    errors: &mut Errors,
  ) -> Conversion {
    match (&self.infallible, &self.fallible) {
      (Some(_), Some(fallible)) => {
        errors.push(syn::Error::new_spanned(
          &fallible.at,
          format!(
            "`{plain}` and `{try}` are both declared for {subject} — {what} either can fail or it \
             cannot, and there is no third answer. Keep `{try}` if it can, `{plain}` if it cannot.",
            plain = direction.plain,
            try = direction.fallible,
            what = direction.what,
          ),
        ));
        Conversion::Fallible(fallible.declared())
      }
      (None, Some(fallible)) => Conversion::Fallible(fallible.declared()),
      (Some(infallible), None) => Conversion::Infallible(infallible.path.clone()),
      (None, None) => Conversion::Default,
    }
  }

  /// Whether this direction was declared at all — what rule "container replaces field-wise" reads.
  pub(crate) const fn declared(&self) -> bool {
    self.infallible.is_some() || self.fallible.is_some()
  }
}

/// The options that belong to ONE database and are refused in the common scope.
///
/// Named rather than swept into "unknown entry": an author who writes `#[ingraph(unique)]` has a
/// concrete idea, and the useful answer names the block it belongs in rather than the fact that
/// the entry was not recognised.
///
/// `indexed` is NOT among them, and its absence is the one thing this list has to be read with.
/// The word is spoken at BOTH seats — one column's index per database, and a COLLECTION's value-led
/// access path at the field, dialect-free — so the field seat READS it rather than letting it fall
/// through here, and answers the scalar case with a redirect of its own that says why the two
/// differ. See [`INDEXED`] and [`INDEXED_NEEDS_A_COLLECTION_WORD`]. A word added back here would
/// take that sentence away and give the shorter one.
const PER_DATABASE: &[&str] = &[
  "unique",
  "copy",
  "edge",
  "type",
  "schema",
  "collection",
  "from",
  "try_from",
  "into",
  "try_into",
];

/// The two knobs a reader expects to find and will not: nullability is not overridable.
const NULLABILITY: &[&str] = &["required", "nullable"];

/// What decides a collection's storage in a database that has no CHOICE to make — and `None` for
/// the one that has.
///
/// Postgres is the only dialect with two usable strategies, so it is the only one a declaration may
/// pick for. SQLite and MySQL have no array type and no indexable JSON form, so every collection
/// they store is an edge table already; MongoDB has no second table to keep one in. A word naming a
/// strategy in any of the three would state the only possibility there is, which is the shape
/// `nullable` is refused in — see [`NULLABILITY`].
const fn no_strategy_to_choose(kind: DatabaseKind) -> Option<&'static str> {
  match kind {
    DatabaseKind::Postgres => None,
    DatabaseKind::Sqlite | DatabaseKind::Mysql => Some(
      "with no array type and no JSON form an index can seek, every collection it stores is \
       already an edge table",
    ),
    DatabaseKind::Mongo => Some("a document holds its own array, and there is no second table"),
  }
}

/// The database a block names, if it names one.
pub(crate) fn database_kind(path: &syn::Path) -> Option<DatabaseKind> {
  DatabaseKind::ALL
    .into_iter()
    .find(|kind| path.is_ident(kind.as_str()))
}

/// The backends a family ships, as a SENTENCE names them — the last one joined by `and`, because
/// every caller reads as prose ("write `sqlite` and `postgres` inside it").
pub(crate) fn shipped(named: impl Iterator<Item = &'static str>) -> String {
  let quoted: Vec<String> = named.map(|name| format!("`{name}`")).collect();
  match quoted.split_last() {
    Some((last, [])) => last.clone(),
    Some((last, rest)) => format!("{} and {last}", rest.join(", ")),
    None => String::new(),
  }
}

/// The store declaration that LEFT the grammar, and why its facts are already written down.
///
/// It named which database holds a table the framework owns, and that is derived from the storage
/// now. A word a reader writes is refused BY THAT REASON rather than as an unknown entry: an author
/// who writes `progress(sqlite)` has a concrete idea, and the useful answer is that the idea is
/// already recorded elsewhere in the declaration.
const DERIVED: [(&str, &str); 1] = [(
  "progress",
  "A ledger's control tables live in the ROW engine's own pool, so its hosts are the databases the \
   store words name, and what it certifies is the unit's close — which every stored record has, so \
   there is nothing to opt into. A block could only restate that or contradict it.",
)];

/// Refuse an entry the DIALECT-FREE scope does not take, by name wherever the name is one a reader
/// plausibly meant somewhere else.
///
/// `vocabulary` is the CALLER's, for the reason the sentence is: two scopes share this helper and
/// take different words, so a list written here would be right for one of them at most.
fn misplaced(
  inner: &syn::meta::ParseNestedMeta<'_>,
  takes: &str,
  vocabulary: &[&str],
) -> syn::Error {
  if let Some(name) = NULLABILITY.iter().find(|name| inner.path.is_ident(name)) {
    let error = syn::Error::new_spanned(
      inner.path.to_token_stream(),
      format!(
        "`{name}` is not an option — a column's nullability follows the `optional` MARKER on the \
         field and is not overridable: `#[ingraph(optional)]` is nullable and a field without it is \
         `NOT NULL`. A domain/column disagreement fails loudly in both directions already, so an \
         override would only hide the schema bug it reconciles."
      ),
    );
    attribute::skip_entry(inner);
    return error;
  }
  if let Some(name) = PER_DATABASE.iter().find(|name| inner.path.is_ident(name)) {
    let error = syn::Error::new_spanned(
      inner.path.to_token_stream(),
      format!(
        "`{name}` is a PER-DATABASE option and this seat speaks to every database at once — \
         write it inside the database's own block, as in `#[ingraph(postgres({name}))]`. A word is \
         dialect-free only when every database has it."
      ),
    );
    attribute::skip_entry(inner);
    return error;
  }
  attribute::unknown(inner, takes, vocabulary)
}

/// One entry inside a fusing node's `upstream(…)`: the upstream, or the bare `key` designating it the
/// one this node's identity descends from.
///
/// A fusing node PROJECTS NOTHING, and the refusal for an entry that tries to is the useful half of
/// this walk: its fields are computed from the messages it joins, so *this field is read out of that
/// upstream's* is a claim it cannot make. A node whose every field really is read out of one
/// message is a derived index, and the refusal names the three macros that declare one.
/// ONE `upstream(…)` entry INSIDE the `subscribe(…)` container.
///
/// Three words and no more. `node = "…"` is the edge, and it is the only required one — an entry
/// naming no upstream names nothing. `key` says this upstream joins THE keyed group, and `out =
/// "<Variant>"` says which of a multi-product upstream's products this edge takes.
///
/// # It is not [`fusion_entry`], and the two are deliberately apart
///
/// The words look the same and the questions are not. A top-level `upstream(…)` answers where this
/// node's IDENTITY comes from, so its `key` designates the parent whose key this node's lineage
/// mirrors — exactly one entry may carry it. A container entry's `key` says its upstream is joined
/// by key before the body sees it, so ANY number of entries carry it and they are one group. One
/// function reading both would have to be told which question it was answering, which is the fact
/// that makes them two.
fn subscribe_entry(
  inner: &syn::meta::ParseNestedMeta<'_>,
  entry: &mut SubscribeEntry,
  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(
        &mut entry.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(());
  }

  if inner.path.is_ident("key") {
    if attribute::has_value(inner) || attribute::has_block(inner) {
      errors.push(named(
        inner,
        "`key` is written bare — it says this upstream is JOINED by key, and the entry it sits on \
         is the upstream being joined, so there is nothing beside it left to name"
          .to_owned(),
      ));
      return Ok(());
    }
    set_once(
      &mut entry.key,
      inner.path.clone(),
      &inner.path,
      "`key` is written twice in one `upstream(…)` — one entry joins the group once",
      errors,
    );
    return Ok(());
  }

  if inner.path.is_ident("out") {
    match value::parse_literal::<syn::Ident>(inner, OUT_IS_QUOTED) {
      Ok(variant) => set_once(
        &mut entry.out,
        variant,
        &inner.path,
        "`out` is declared more than once in `upstream(…)` — one edge carries one product",
        errors,
      ),
      Err(e) => errors.push(e),
    }
    return Ok(());
  }

  if inner.path.is_ident("channel") {
    match channel_word(inner) {
      Ok(spec) => set_once(
        &mut entry.channel,
        spec,
        &inner.path,
        "`channel` is declared more than once in one `upstream(…)` — one edge is opened one way",
        errors,
      ),
      Err(e) => errors.push(e),
    }
    return Ok(());
  }

  // THE RECEIPT this consumer takes, and it is the CONSUMER's to choose: the default is the message
  // itself, and `notify` is the entity's KEY — *landed, proceed*. Bare, like `key`, because the
  // entry it sits on is the upstream being received from and there is nothing beside it to name.
  if inner.path.is_ident("notify") {
    if attribute::has_value(inner) || attribute::has_block(inner) {
      errors.push(named(
        inner,
        "`notify` is written bare — it says this edge carries the landed entity's KEY instead of \
         the entity, and the key's TYPE is the upstream's own answer rather than a word this \
         declaration could name. What the payload is is the upstream's to say; what arrives is this \
         entry's to choose"
          .to_owned(),
      ));
      return Ok(());
    }
    set_once(
      &mut entry.notify,
      inner.path.clone(),
      &inner.path,
      "`notify` is written twice in one `upstream(…)` — one edge carries one receipt",
      errors,
    );
    return Ok(());
  }

  // THE STORE'S OWN FEED as this edge's intake, per database — the second delivery mode, and the
  // one whose knobs live inside the database's block by the axis law `sqlite(flatten)`
  // already writes.
  if inner.path.is_ident("changes") {
    match changes_word(inner) {
      Ok(feed) => set_once(
        &mut entry.changes,
        feed,
        &inner.path,
        "`changes` is declared more than once in one `upstream(…)` — one edge is fed one way, and two \
         databases' feeds are two upstreams",
        errors,
      ),
      Err(e) => errors.push(e),
    }
    return Ok(());
  }

  errors.push(attribute::unknown(
    inner,
    "unknown entry in `upstream(…)` — inside `subscribe(…)` it takes `node = \"…\"`, the bare words \
     `key` and `notify`, `out = \"<Variant>\"`, `channel = bounded(…) | unbounded` and \
     `changes(<db>)` where the edge takes the store's own feed",
    &["node", "key", "notify", "out", "channel", "changes"],
  ));
  Ok(())
}

/// The sentence a bare `changes` is refused with.
///
/// It names the wall rather than the rule, because the wall is the reason: which databases an
/// upstream stores in is the UPSTREAM's declaration, and two macro expansions cannot see each other.
/// A grammar that admitted the bare word would be promising a resolution it has no way to perform.
const CHANGES_NAMES_ITS_DATABASE: &str = "`changes(<db>)` names WHICH store's feed this edge takes \
                                          — `changes(sqlite)`, `changes(postgres)`. Bare `changes` \
                                          would have to read the upstream's own store words to \
                                          know, and two declarations cannot see each other, so the \
                                          database is named here or nowhere";

/// The sentence a database block is refused with when what is inside it is not `external`.
const CHANGES_TAKES_EXTERNAL: &str = "the only word inside a `changes(<db>(…))` block is `external`, \
                                      which says the hand that fills the watched store is OUTSIDE \
                                      this process. Everything else a feed needs is the backend's, \
                                      and everything else this edge needs is beside the block";

/// `changes(<db>)` / `changes(<db>(external))`, read into the model's own feed.
///
/// # Errors
/// One of the sentences above, spanned at what was written.
fn changes_word(inner: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<ChangesFeed> {
  // The BARE word, caught before the walk — which would otherwise report *expected parentheses* and
  // say nothing about the database it is missing.
  if !attribute::has_block(inner) {
    return Err(syn::Error::new_spanned(
      inner.path.to_token_stream(),
      CHANGES_NAMES_ITS_DATABASE,
    ));
  }
  let mut feed: Option<ChangesFeed> = None;
  let mut refusal: Option<syn::Error> = None;
  inner.parse_nested_meta(|database| {
    let Some(kind) = database_kind(&database.path) else {
      // `external` written where a DATABASE belongs is the near miss worth naming: the word exists
      // and the axis law puts it one block further in, which is what a reader has to be told.
      let sentence = if database.path.is_ident("external") {
        "`external` is a per-database word, so it lives INSIDE the database's own block — \
         `changes(sqlite(external))`. Written where the database belongs it would be a store called \
         `external`, and the feed is a backend's before it is anybody's hand"
          .to_owned()
      } else {
        CHANGES_NAMES_ITS_DATABASE.to_owned()
      };
      refusal.get_or_insert_with(|| {
        syn::Error::new_spanned(database.path.to_token_stream(), sentence)
      });
      attribute::skip_entry(&database);
      return Ok(());
    };
    if feed.is_some() {
      refusal.get_or_insert_with(|| {
        syn::Error::new_spanned(
          database.path.to_token_stream(),
          "`changes(…)` names ONE database — one edge is one store's feed, and a node watching two \
           stores draws two edges",
        )
      });
      attribute::skip_entry(&database);
      return Ok(());
    }
    let mut external = false;
    if attribute::has_block(&database) {
      database.parse_nested_meta(|word| {
        if word.path.is_ident("external") {
          external = true;
          return Ok(());
        }
        refusal.get_or_insert_with(|| {
          syn::Error::new_spanned(word.path.to_token_stream(), CHANGES_TAKES_EXTERNAL)
        });
        attribute::skip_entry(&word);
        Ok(())
      })?;
    } else if attribute::has_value(&database) {
      refusal.get_or_insert_with(|| {
        syn::Error::new_spanned(database.path.to_token_stream(), CHANGES_TAKES_EXTERNAL)
      });
      attribute::skip_entry(&database);
      return Ok(());
    }
    feed = Some(ChangesFeed {
      database: kind,
      external,
    });
    Ok(())
  })?;
  if let Some(refusal) = refusal {
    return Err(refusal);
  }
  feed.ok_or_else(|| {
    syn::Error::new_spanned(inner.path.to_token_stream(), CHANGES_NAMES_ITS_DATABASE)
  })
}

/// The sentence the `channel` word is refused with when its value is neither of the two shapes.
///
/// The value is written BARE, and the round's mint-bare/refer-quoted law is why rather than an
/// exception to it: `bounded` and `unbounded` refer to nothing — no upstream, no type, no name any
/// declaration minted — they ARE the framework's vocabulary, in the same position `depth = 16`
/// writes a count. What is quoted here is the DOCUMENT's form of the same word, which is a different
/// grammar with a different reader.
const CHANNEL_IS_ONE_OF_TWO: &str = "`channel = bounded(512)` and `channel = unbounded` are the two \
                                     shapes an edge has — a depth its sender blocks at, or no bound \
                                     at all. The words are written bare, being the framework's own \
                                     vocabulary rather than a name this declaration refers to";

/// The sentence `bounded` is refused with when it names no depth.
const BOUNDED_NAMES_ITS_DEPTH: &str = "`bounded` is a depth — write `bounded(512)`. A bound with no \
                                       number is the one thing the word cannot mean, and the kind \
                                       that needs no number is `unbounded`";

/// The sentence `unbounded` is refused with when something was written beside it.
const UNBOUNDED_TAKES_NOTHING: &str = "`unbounded` takes nothing — a queue nothing bounds has no \
                                       depth to name. A number belongs to `bounded(…)`";

/// `channel = bounded(<depth>)` / `channel = unbounded`, read into the model's own two words.
///
/// # Errors
/// One of the three sentences above, spanned at what was written.
fn channel_word(inner: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<ChannelOptions> {
  let value = inner
    .value()
    .map_err(|e| syn::Error::new(e.span(), CHANNEL_IS_ONE_OF_TWO))?;
  let written = value
    .parse::<syn::Expr>()
    .map_err(|e| syn::Error::new(e.span(), CHANNEL_IS_ONE_OF_TWO))?;
  match &written {
    // `unbounded`, and the near-miss beside it: `bounded` alone is the word without its number.
    syn::Expr::Path(spelled) if spelled.path.is_ident("unbounded") => Ok(ChannelOptions::Unbounded),
    syn::Expr::Path(spelled) if spelled.path.is_ident("bounded") => {
      Err(syn::Error::new_spanned(&written, BOUNDED_NAMES_ITS_DEPTH))
    }
    syn::Expr::Call(call) => match (&*call.func, call.args.len()) {
      (syn::Expr::Path(spelled), 1) if spelled.path.is_ident("bounded") => {
        match call.args.first().expect("a call of one argument has one") {
          syn::Expr::Lit(syn::ExprLit {
            lit: syn::Lit::Int(depth),
            ..
          }) => depth.base10_parse::<usize>().map(ChannelOptions::Bounded),
          other => Err(syn::Error::new_spanned(other, BOUNDED_NAMES_ITS_DEPTH)),
        }
      }
      (syn::Expr::Path(spelled), _) if spelled.path.is_ident("bounded") => {
        Err(syn::Error::new_spanned(&written, BOUNDED_NAMES_ITS_DEPTH))
      }
      (syn::Expr::Path(spelled), _) if spelled.path.is_ident("unbounded") => {
        Err(syn::Error::new_spanned(&written, UNBOUNDED_TAKES_NOTHING))
      }
      _ => Err(syn::Error::new_spanned(&written, CHANNEL_IS_ONE_OF_TWO)),
    },
    other => Err(syn::Error::new_spanned(other, CHANNEL_IS_ONE_OF_TWO)),
  }
}

/// The sentence `out = …` is refused with when its value is not a quoted arm.
///
/// It names the older spelling by name, because that is the migration an author is standing in:
/// `out = Boxes` was legal and is not, and a reader who is told only what the grammar takes has to
/// work out that the word they wrote is the word they keep.
///
/// The law it applies is the round's own — MINT BARE, REFER QUOTED. A product's arm is a name the
/// UPSTREAM minted, so every spelling of it downstream is a reference, and references are quoted
/// here as `node = "…"` and `subscribe = "…"` already are.
const OUT_IS_QUOTED: &str = "`out = \"<Variant>\"` names one arm of the upstream's product \
                            vocabulary, QUOTED — a bare `out = <Variant>` is the older spelling. \
                            The arm is a name the upstream minted and this declaration refers to, \
                            and a reference is written in a string literal here as `node = \"…\"` \
                            is";

/// The `subscribe(…)` container read as ONE declaration: the fan-in, and every way it can be
/// written wrongly.
///
/// # The variant's name is READ OFF the declaration, never declared
///
/// A straight source is named by its upstream path's last segment, and one that selected a product
/// is named by that PRODUCT's word — because those are the words the declaration wrote, and the
/// second is what keeps two products of ONE upstream apart. Two entries whose names agree are
/// refused HERE, naming both: left alone they would be two variants of one name inside the emitted
/// enum, which is `E0428` at a span the declaration cannot edit, and the fix is a rename this
/// grammar has no word for yet. The refusal says the word is coming rather than pretending the
/// shape is illegal.
fn fan_in(
  record: &syn::Ident,
  block: Option<SubscribeBlock>,
  errors: &mut Errors,
) -> Option<Subscription> {
  let block = block?;
  let block_has_a_group = block.entries.iter().any(|entry| entry.key.is_some());
  let mut upstreams: Vec<Upstream> = Vec::new();
  for entry in block.entries {
    let Some(node) = entry.node else {
      errors.push(syn::Error::new_spanned(
        &entry.at,
        "`upstream(…)` needs `node = \"path::To::Upstream\"` — an entry with no upstream names \
         nothing, and the words beside it would qualify nothing",
      ));
      continue;
    };
    // The PRODUCT's word where one was selected, and the upstream's own otherwise. Both are what
    // the declaration wrote; neither is invented here.
    let variant = entry.out.clone().unwrap_or_else(|| {
      node
        .segments
        .last()
        .expect("a path has at least one segment")
        .ident
        .clone()
    });
    // The keyed group's own word is spoken for wherever a group exists, and a straight source
    // taking it would be two variants of one name inside the emitted enum — `E0428` at a span the
    // declaration cannot edit. Refused here, where it can.
    if entry.key.is_none() && variant == PAIRED && block_has_a_group {
      errors.push(syn::Error::new_spanned(
        &entry.at,
        format!(
          "`{record}` draws from `{PAIRED}` beside a keyed group, and `{PAIRED}` is the variant \
           that group takes in this node's fan-in — one word cannot name both. A `name = \"…\"` \
           word will settle it; until it exists, the two cannot meet in one container"
        ),
      ));
      continue;
    }
    if let Some(first) = upstreams
      .iter()
      .find(|earlier: &&Upstream| earlier.variant == variant)
    {
      errors.push(syn::Error::new_spanned(
        &entry.at,
        format!(
          "`{record}` draws two edges that would take the same name — `{}` and `{}` both come out \
           as `{variant}`, and that word is the variant this node's fan-in reads them under. It is \
           read off the declaration rather than declared, so two edges cannot share it: a `name = \
           \"…\"` word will settle a genuine collision, and until it exists the edge that needs it \
           has no spelling",
          upstream_text(first),
          upstream_text(&Upstream {
            node: node.clone(),
            keyed: entry.key.is_some(),
            out: entry.out.clone(),
            variant: variant.clone(),
            channel: entry.channel,
            changes: entry.changes,
            notify: entry.notify.is_some(),
          }),
        ),
      ));
      continue;
    }
    // THE SHELF NAME, by the P1 law: the variant's own word in snake case, which is the field the
    // emitted `[node.channels]` block carries and the key a document writes. Two entries whose
    // variants differ but whose shelf names agree — `Ab` beside `AB` — would be one struct with two
    // fields of one name, `E0124` at a span the declaration cannot edit. Refused here, where it can,
    // and by the same sentence the variant collision above gets: the fix is the same `name = "…"`
    // word, and it is the same law that has no spelling for it yet.
    if let Some(first) = upstreams
      .iter()
      .find(|earlier: &&Upstream| shelf_name(&earlier.variant) == shelf_name(&variant))
    {
      errors.push(syn::Error::new_spanned(
        &entry.at,
        format!(
          "`{record}` draws two edges whose CHANNEL SHELF names would collide — `{}` and `{}` both \
           come out as `{}` in this node's `[node.channels]` block, which is one field written \
           twice. The names are read off the declaration rather than declared, so a `name = \"…\"` \
           word will settle a genuine collision, and until it exists the edge that needs it has no \
           spelling",
          first.variant,
          variant,
          shelf_name(&variant),
        ),
      ));
      continue;
    }
    upstreams.push(Upstream {
      node,
      keyed: entry.key.is_some(),
      out: entry.out,
      variant,
      channel: entry.channel,
      changes: entry.changes,
      notify: entry.notify.is_some(),
    });
  }
  (!upstreams.is_empty()).then_some(Subscription { upstreams })
}

/// An entry as an author would read it back — the upstream, and the product where one was named.
fn upstream_text(source: &Upstream) -> String {
  match &source.out {
    Some(out) => format!("{}'s `{out}`", path_text(&source.node)),
    None => path_text(&source.node),
  }
}

/// ONE `poll(…)` entry as written: the name it mints, the schedule word it carries, the stores it
/// is granted, and the span.
struct PollBlock {
  /// The bare ident the entry minted, where it wrote one.
  name: Option<syn::Ident>,
  /// `every = "…"` read into a POSITIVE interval, with the literal it came from.
  every: Option<(syn::LitStr, std::time::Duration)>,
  /// `cron = "…"` as written — checked once the whole entry is read, because the zone it is read
  /// in may be written after it.
  cron: Option<syn::LitStr>,
  /// `tz = "…"` as written.
  zone: Option<syn::LitStr>,
  /// `write = "…"` / `write = ["…", "…"]` — the granted node paths, in the order this entry wrote
  /// them, where it wrote the word at all.
  ///
  /// Inside the entry rather than beside it, by the ruling that moved it here: a permission is spent
  /// BY A TICK, so it is seated at the clock whose ticks spend it. Two clocks sharing a store write
  /// the word twice, which is the explicit repetition the ruling chose over implicit sharing.
  ///
  /// The paths and nothing else — no span for the word itself, because every refusal the fold makes
  /// is about ONE grant and lands on that grant's own literal.
  write: Option<Vec<syn::Path>>,
  /// `handler = "app::PromScraper"` — the mounted citizen's type path, as written.
  handler: Option<syn::Path>,
  /// The bare `light` word, at the token it was written.
  ///
  /// [`handler`](Self::handler)'s OTHER ROAD, and the pair is exclusive and mandatory: every entry
  /// names its body, and the two words are the two bodies there are. The span travels because both
  /// refusals about it are about the WORD — the entry that wrote it beside a mount, and the entry
  /// that wrote it under a mode that detaches.
  ///
  /// TWO OPTIONS HERE and one `PollBody` in the model, and the asymmetry is the difference between
  /// reading and having read: this side must be able to hold *both were written* and *neither was*,
  /// which are the two states the three refusals exist to catch, and the model holds only what
  /// survived them.
  light: Option<syn::Path>,
  /// Whether a BODY word was written at all, however badly.
  ///
  /// [`spoken`](Self::spoken)'s twin over the other mandatory question, and it exists for the same
  /// reason: one mistake should cost one error. A `handler(Scraper)` earns the sentence about the
  /// word's shape and must not ALSO earn the mandatory-word sentence, which would tell an author
  /// who did name a body that they did not.
  body_spoken: bool,
  /// The MODE word and the token it was written at — one of the five, and mandatory.
  ///
  /// The span travels because the refusals about a mode are about a WORD: a `concurrent` on an
  /// inline entry and a `light` entry under a detached mode both point at the word that decided it.
  mode: Option<(PollMode, syn::Path)>,
  /// The bare `concurrent` word, at the token it was written.
  concurrent: Option<syn::Path>,
  /// Whether a MODE-SHAPED word was written at all, however badly.
  ///
  /// Kept beside [`mode`](Self::mode) rather than read off it, so that one mistake costs one error:
  /// a bare `async` earns the sentence naming its two roads and must not ALSO earn the
  /// mandatory-word sentence, which would tell an author who did say where it runs that they did
  /// not. `attribute::unknown`'s own rule, one grammar over.
  spoken: bool,
  /// The word's own path, for a refusal about the entry rather than about a word inside it.
  at: syn::Path,
}

/// The sentence a `poll(…)` that mints nothing is refused with.
const POLL_TAKES_A_NAME: &str = "`poll(<name>, every = \"10m\")` opens with the NAME this entry is \
                                 minting — the word a tick arrives under, and the variant it takes \
                                 in this node's emitted `…Due`. A clock nobody can name is a clock \
                                 whose ticks a body cannot tell apart";

/// The sentence `every` is refused with when its value is not a duration.
const EVERY_IS_A_DURATION: &str = "`every = \"…\"` is an INTERVAL, in the framework's one duration \
                                   grammar — `\"10m\"`, `\"1h 30m\"`, `\"PT1H\"`, `\"1d\"`";

/// The sentence `cron` is refused with when its value is not a quoted expression.
const CRON_IS_AN_EXPRESSION: &str = "`cron = \"…\"` is a calendar expression in the classic five \
                                     fields — `\"0 3 * * *\"`";

/// ONE entry inside `poll(…)`: the minted name, and exactly one of the two schedule words.
///
/// # The name is MINTED, so it is bare
///
/// The round's law is mint bare, refer quoted, and this word is the minting side of it: the name
/// refers to no upstream, no type and no other declaration. It is brought into being here so that
/// the author can match on it, which is the whole reason the anonymous-index alternative was
/// rejected — a declaration whose entries were reordered would silently change what every body
/// meant.
///
/// # Every entry NAMES ITS BODY, and the two words are the two bodies
///
/// `handler = "…"` mounts a citizen and `light` runs the node's own `<Node>Sweeps` method. Exactly
/// one, on every entry: the implicit form — neither word, meaning the method — is gone, because a
/// declaration that answers *who runs this* by saying nothing answers it only for a reader who
/// already knows the grammar. The two words are shaped by what they name: the mount REFERS to a
/// type and is quoted, and `light` names a road this framework owns and is bare.
///
/// # `ack` is refused BY NAME, and that is a rule rather than an unknown word
///
/// Poll is ACKLESS BY CONSTRUCTION. There is no producer window to release and no pull cursor to
/// advance, because a tick is not data — and what an ack buys elsewhere the poll side already owns:
/// the next tick over an idempotent scan is the retry, the lifecycle taps are the observation, and
/// the clock itself is the throttle. A word parsed into a model nothing spends is a promise rather
/// than a rule, so the word is refused where an author can still read why.
fn poll_entry(
  inner: &syn::meta::ParseNestedMeta<'_>,
  block: &mut PollBlock,
  errors: &mut Errors,
) -> syn::Result<()> {
  if inner.path.is_ident("every") {
    match value::literal(inner, EVERY_IS_A_DURATION) {
      Ok(text) => match interval(&text) {
        Ok(interval) => set_once(
          &mut block.every,
          (text, interval),
          &inner.path,
          "`every` is declared more than once in one `poll(…)` — one entry runs on one clock",
          errors,
        ),
        Err(refusal) => errors.push(refusal),
      },
      Err(e) => errors.push(e),
    }
    return Ok(());
  }

  if inner.path.is_ident("cron") {
    match value::literal(inner, CRON_IS_AN_EXPRESSION) {
      Ok(text) => set_once(
        &mut block.cron,
        text,
        &inner.path,
        "`cron` is declared more than once in one `poll(…)` — one entry runs on one clock",
        errors,
      ),
      Err(e) => errors.push(e),
    }
    return Ok(());
  }

  if inner.path.is_ident("tz") {
    match value::literal(
      inner,
      "`tz = \"…\"` names the zone a calendar expression is read in, as an IANA name — \
       `\"America/New_York\"`",
    ) {
      Ok(text) => set_once(
        &mut block.zone,
        text,
        &inner.path,
        "`tz` is declared more than once in one `poll(…)` — one entry keeps one clock's time",
        errors,
      ),
      Err(e) => errors.push(e),
    }
    return Ok(());
  }

  // THE PERMISSION, seated at the clock that spends it. `write = "…"` grants ONE store and
  // `write = ["…", "…"]` grants several, and the grants are THIS ENTRY's: the emission mints one
  // context per clock, so what a tick may reach is decided by which clock rang.
  //
  // The values are QUOTED for `emits`' reason: the word REFERS, naming nodes another declaration
  // minted, and every referring word in this grammar is written in a string literal.
  if inner.path.is_ident("write") {
    let at = inner.path.clone();
    if attribute::has_block(inner) {
      errors.push(named(inner, WRITE_IS_QUOTED.to_owned()));
      return Ok(());
    }
    let literals = match value::literals(inner, WRITE_IS_QUOTED) {
      Ok(literals) => literals,
      Err(e) => {
        errors.push(e);
        return Ok(());
      }
    };
    let mut declared: Vec<syn::Path> = Vec::new();
    for literal in literals {
      // The parse RESPANS to the literal, for `emits`' reason: every error the emitted context
      // reports about a granted type lands where the author wrote it.
      match literal.parse::<syn::Path>() {
        Ok(node) => declared.push(node),
        Err(_) => errors.push(syn::Error::new_spanned(
          &literal,
          "`write` names NODES, so each value is a type path — an expression or an empty string \
           is not one",
        )),
      }
    }
    if declared.is_empty() {
      errors.push(syn::Error::new_spanned(
        &at,
        "`write` grants at least one store — a clock that writes into nobody else's store is \
         spelled by omitting the word",
      ));
      return Ok(());
    }
    set_once(
      &mut block.write,
      declared,
      &at,
      "`write` is declared more than once in one `poll(…)` — one word names every store this clock \
       may write, and a second list would be a second answer to the same question. Put the extra \
       stores in the one list",
      errors,
    );
    return Ok(());
  }

  // THE MOUNT. `handler = "app::PromScraper"` names the CITIZEN this clock's ticks run, and the
  // value is quoted for `write`'s reason: the word REFERS, to a type another crate declared, and
  // every referring word in this grammar is written in a string literal.
  if inner.path.is_ident("handler") {
    let at = inner.path.clone();
    block.body_spoken = true;
    if attribute::has_block(inner) {
      errors.push(named(inner, HANDLER_IS_QUOTED.to_owned()));
      return Ok(());
    }
    match value::parse_literal::<syn::Path>(inner, HANDLER_IS_QUOTED) {
      // The parse RESPANS to the literal, for `write`'s reason: every error the emitted route
      // reports about the mounted type lands where the author wrote it.
      Ok(mounted) => set_once(
        &mut block.handler,
        mounted,
        &at,
        "`handler` is declared more than once in one `poll(…)` — one clock runs ONE body, and a \
         second mount would be a second answer to the same question. Two bodies are two entries",
        errors,
      ),
      Err(e) => errors.push(e),
    }
    return Ok(());
  }

  // THE OTHER BODY ROAD, bare: `light` runs the node's OWN `<Node>Sweeps` method, on the operator
  // the driver lends for the call. It is written rather than implied — the word this rework
  // minted — because who runs a tick is the first thing a reader of a clock wants to know, and an
  // entry that said nothing used to answer it by omission.
  //
  // Bare for the mint-bare/refer-quoted law's reason read the other way: `light` refers to nothing.
  // It is the framework's own word for a road, in the position `handler = "…"` writes a type path.
  if inner.path.is_ident("light") {
    block.body_spoken = true;
    if attribute::has_block(inner) || attribute::has_value(inner) {
      errors.push(named(inner, LIGHT_IS_BARE.to_owned()));
      return Ok(());
    }
    set_once(
      &mut block.light,
      inner.path.clone(),
      &inner.path,
      "`light` is declared more than once in one `poll(…)` — the word is presence, so a second one \
       says what the first already said",
      errors,
    );
    return Ok(());
  }

  // THE MODE, in its two shapes: three bare sync words, and the `async(…)` container whose own word
  // says which of the two async roads. One entry runs in ONE world, so they share a slot and the
  // second one written is refused wherever it came from.
  if let Some(mode) = bare_mode(&inner.path) {
    block.spoken = true;
    if attribute::has_block(inner) || attribute::has_value(inner) {
      errors.push(named(inner, mode_carries_nothing(mode)));
      return Ok(());
    }
    set_once(
      &mut block.mode,
      (mode, inner.path.clone()),
      &inner.path,
      ONE_WORLD,
      errors,
    );
    return Ok(());
  }

  if inner.path.is_ident("async") {
    let at = inner.path.clone();
    block.spoken = true;
    if !attribute::has_block(inner) || attribute::empty_group(inner) {
      errors.push(named(inner, ASYNC_NAMES_ITS_ROAD.to_owned()));
      return Ok(());
    }
    let mut named_road: Option<PollMode> = None;
    let walked = inner.parse_nested_meta(|road| {
      let picked = if road.path.is_ident("inline") {
        PollMode::AsyncInline
      } else if road.path.is_ident("spawn") {
        PollMode::AsyncSpawn
      } else {
        errors.push(attribute::unknown(
          &road,
          ASYNC_NAMES_ITS_ROAD,
          &["inline", "spawn"],
        ));
        return Ok(());
      };
      set_once(
        &mut named_road,
        picked,
        &road.path,
        "`async(…)` names ONE road — `inline` awaits the tick in the driver's loop and `spawn` \
         detaches it as a task, and an entry cannot do both",
        errors,
      );
      Ok(())
    });
    if let Err(e) = walked {
      errors.push(e);
    }
    if let Some(road) = named_road {
      set_once(&mut block.mode, (road, at.clone()), &at, ONE_WORLD, errors);
    }
    return Ok(());
  }

  // THE CONCURRENCY KNOB, bare: presence is free concurrency. Which modes have a seat for it is
  // settled once the whole entry is read, because the mode word may be written after it.
  if inner.path.is_ident("concurrent") {
    if attribute::has_block(inner) || attribute::has_value(inner) {
      errors.push(named(inner, CONCURRENT_IS_BARE.to_owned()));
      return Ok(());
    }
    set_once(
      &mut block.concurrent,
      inner.path.clone(),
      &inner.path,
      "`concurrent` is declared more than once in one `poll(…)` — the word is presence, so a \
       second one says what the first already said",
      errors,
    );
    return Ok(());
  }

  if inner.path.is_ident("channel") {
    errors.push(named(
      inner,
      "a poll entry has NO channel: a tick is a wake and not a message, so there is no queue \
       between two parties to bound or leave unbounded. The word belongs to a `upstream(…)` entry \
       inside `subscribe(…)`, which is where messages travel — and a clock's own coalescing is the \
       runtime's, one cell per upstream, never a depth a declaration names"
        .to_owned(),
    ));
    return Ok(());
  }

  if inner.path.is_ident("notify") {
    errors.push(named(
      inner,
      "a poll entry has NO receipt to choose: a tick is a wake and not a message, so nothing arrives \
       whose payload could be an entity or that entity's key. The word belongs to a `upstream(…)` \
       entry inside `subscribe(…)`, which is where messages travel — a polled node reads through \
       its held handles instead, and what it reads is its own"
        .to_owned(),
    ));
    return Ok(());
  }

  if inner.path.is_ident("ack") {
    errors.push(named(
      inner,
      "a poll inbound carries NO ack, structurally — a tick is a wake and not data, so there is no \
       producer window to release and no cursor to advance. What an ack buys elsewhere this side \
       already has: the NEXT TICK over an idempotent scan is the retry, the lifecycle taps are the \
       observation, and the clock itself is the throttle. A unit that PUBLISHES downstream keeps \
       the whole ack protocol as a sender — acklessness is a property of this edge, not of the node"
        .to_owned(),
    ));
    return Ok(());
  }

  // Whatever is left and carries nothing is the MINT — the one bare word this entry takes.
  if !attribute::has_value(inner) && !attribute::has_block(inner) {
    let Some(name) = inner.path.get_ident().cloned() else {
      errors.push(attribute::unknown(
        inner,
        "a poll entry MINTS one name, so the word is a plain identifier — a path with several \
         segments refers to something instead, and this word refers to nothing",
        // A path names no word, and the word this position takes is one the entry MINTS.
        &[],
      ));
      return Ok(());
    };
    if block.name.is_some() {
      // A SECOND bare word is as likely to be a typo of one of this position's own bare words as a
      // second clock, and it became likelier the moment `light` was minted — so the near-miss
      // round's rule is read here too, over the words a BARE position takes. `set_once`'s sentence
      // with a clause, rather than a different refusal: what broke is still one entry, one name.
      let near = suggest::word(&inner.path)
        .map(|written| suggest::did_you_mean(&written, BARE_POLL_WORDS))
        .unwrap_or_default();
      errors.push(named(
        inner,
        format!(
          "a `poll(…)` entry mints ONE name — a second bare word would be a second clock, which is \
           a second entry{near}"
        ),
      ));
      return Ok(());
    }
    block.name = Some(name);
    return Ok(());
  }

  errors.push(attribute::unknown(
    inner,
    "unknown entry in `poll(…)` — it opens with the bare name it mints, carries exactly one of \
     `every = \"…\"` or `cron = \"…\"`, names its body with `handler = \"…\"` or `light`, and says \
     WHERE it runs with one of `block`, `spawn`, `rayon`, `async(inline)` or `async(spawn)`. \
     Beside those: `tz = \"…\"` on a calendar one, `write = \"…\"` where this clock's ticks are \
     granted a store, and `concurrent` where a sync-detached clock may overlap itself",
    // The keyed and block words, plus `light` — which is bare, and is here for the shape a near
    // miss of it takes: a bare `ligth` reaches the MINT above, but `ligth = 3` reaches this
    // sentence, and the word it was nearly is one this position takes. The minted name and the
    // bare mode words stay out, having no keyed spelling for an author to nearly write.
    &["every", "cron", "tz", "write", "handler", "light", "async"],
  ));
  Ok(())
}

/// The words this position takes BARE, beside the name an entry mints — the vocabulary a second
/// bare word is measured against.
///
/// `async` is not among them because it is not bare, and the minted name is not among them because
/// it is the thing being written rather than a word to be near.
pub(crate) const BARE_POLL_WORDS: [&str; 5] = ["light", "block", "spawn", "rayon", "concurrent"];

/// The three SYNC mode words, which are written bare.
///
/// The async pair is not here because it is not bare: `async(inline)` and `async(spawn)` share a
/// container, which is what makes the world visible at a glance and keeps `spawn` from meaning two
/// different things depending on a neighbour.
fn bare_mode(path: &syn::Path) -> Option<PollMode> {
  if path.is_ident("block") {
    Some(PollMode::Block)
  } else if path.is_ident("spawn") {
    Some(PollMode::Spawn)
  } else if path.is_ident("rayon") {
    Some(PollMode::Rayon)
  } else {
    None
  }
}

/// The sentence a mode word carrying something is refused with.
fn mode_carries_nothing(mode: PollMode) -> String {
  format!(
    "`{}` is a BARE word — it says where this clock's tick runs and carries nothing. The word with \
     options is `async(…)`, and its options are the two async roads",
    mode.as_str()
  )
}

/// The sentence a second world is refused with, whichever shape wrote it.
const ONE_WORLD: &str = "a `poll(…)` entry runs in ONE world — `block`, `spawn`, `rayon`, \
                         `async(inline)` and `async(spawn)` are five answers to the same question, \
                         and nothing decides between two of them. A clock that wants both is two \
                         clocks";

/// The sentence a bare or mis-worded `async` is refused with.
const ASYNC_NAMES_ITS_ROAD: &str = "`async(…)` names WHICH async road — `async(inline)` awaits the \
                                    tick in the driver's own loop, and `async(spawn)` detaches it \
                                    as a task on the executor the deployment installed. The word \
                                    alone says the world and not the place, and the place is the \
                                    half that changes what runs where";

/// The sentence a container- or value-shaped `handler` is refused with.
///
/// [`WRITE_IS_QUOTED`]'s twin, and it states the same law: `handler` REFERS — it names a type the
/// application declared — and every referring word in this grammar is written in a string literal.
const HANDLER_IS_QUOTED: &str = "`handler = \"app::PromScraper\"` mounts the CITIZEN this clock's \
                                 ticks run — quoted, as `write = \"…\"` and `node = \"…\"` are, \
                                 because the word names a TYPE this declaration cannot resolve and \
                                 the compiler resolves where the expansion lands";

/// The sentence a `light` carrying something is refused with.
///
/// [`HANDLER_IS_QUOTED`]'s opposite half, and the pair is the mint-bare/refer-quoted law over one
/// question: the mounting word names a TYPE and is therefore quoted, and this one names a ROAD this
/// framework already owns and is therefore bare. There is nothing for it to carry, because the body
/// it selects is the one the node itself wrote.
const LIGHT_IS_BARE: &str = "`light` is a BARE word — its presence is the whole answer. Writing it \
                             says this clock's ticks run the node's OWN sweep method, on the \
                             operator the driver lends for the call. The word that carries a value \
                             is `handler = \"…\"`, which mounts a citizen instead";

/// The sentence a `concurrent` carrying something is refused with.
const CONCURRENT_IS_BARE: &str = "`concurrent` is a BARE word — its presence is the whole answer. \
                                  Writing it says this clock's detached ticks may overlap; leaving \
                                  it out is at most one in flight, which is the default a thread \
                                  per tick has to have";

/// `every = "…"` read into the interval it names, or the refusal it earns.
///
/// The duration grammar is the framework's ONE grammar, shared with the runtime filter's operand
/// parser and pinned against it — see [`ingraph_codegen::duration`]. What this adds is the rule the
/// schedule has and the filter does not: an interval must be POSITIVE. Zero is a spin rather than a
/// schedule, and a negative interval is a deadline in the past forever; both are refused by name at
/// the string, because a clock that fires as fast as the machine allows is not what any declaration
/// meant to write.
fn interval(text: &syn::LitStr) -> Result<std::time::Duration, syn::Error> {
  let written = text.value();
  let span = ingraph_codegen::duration::parse(&written).map_err(|refusal| {
    syn::Error::new_spanned(
      text,
      format!("`every = \"{written}\"` is not a duration this grammar reads — {refusal}"),
    )
  })?;
  if !span.is_positive() {
    return Err(syn::Error::new_spanned(
      text,
      format!(
        "`every = \"{written}\"` is not a schedule — a poll that fires as fast as the machine \
         allows is a SPIN, and an interval that is not positive is one. A node that wants to look \
         as often as it can is written with the shortest interval it actually means"
      ),
    ));
  }
  let seconds = u64::try_from(span.as_secs()).map_err(|_| {
    syn::Error::new_spanned(text, format!("`every = \"{written}\"` is not a schedule"))
  })?;
  let nanoseconds = u32::try_from(span.subsec_nanos()).map_err(|_| {
    syn::Error::new_spanned(text, format!("`every = \"{written}\"` is not a schedule"))
  })?;
  Ok(std::time::Duration::new(seconds, nanoseconds))
}

/// The `poll(…)` entries read as ONE declaration: the node's clocks, and every way the set can be
/// wrong.
///
/// Settled here rather than during the walk because two of the rules need a WHOLE entry or a whole
/// declaration: the schedule words are exclusive and the zone qualifies one of them, so neither can
/// be judged before the entry closes; and two entries minting one word collide only once both have
/// been read.
fn poll_sources(record: &syn::Ident, blocks: Vec<PollBlock>, errors: &mut Errors) -> Option<Polls> {
  use heck::ToUpperCamelCase as _;

  let mut entries: Vec<PollEntry> = Vec::new();
  for block in blocks {
    let Some(name) = block.name else {
      // The one word this rework took OUT of the minting position, said out loud where it costs an
      // author a name: an entry whose only bare word is `light` read that word as the body road, so
      // the sentence about a missing name would otherwise be about a name the author did write.
      let taken = if block.light.is_some() {
        " — and `light` is this position's own word for the node's own body, so an entry cannot \
         also mint a clock called that"
      } else {
        ""
      };
      errors.push(syn::Error::new_spanned(
        &block.at,
        format!("{POLL_TAKES_A_NAME}{taken}"),
      ));
      continue;
    };
    let cadence = match (block.every, block.cron) {
      (Some(_), Some(cron)) => {
        errors.push(syn::Error::new_spanned(
          &cron,
          format!(
            "`{name}` names both `every` and `cron`, and an entry runs on ONE clock — an interval \
             and a calendar are two answers to when, and nothing decides between them. Two clocks \
             are two entries"
          ),
        ));
        continue;
      }
      (None, None) => {
        errors.push(syn::Error::new_spanned(
          &block.at,
          format!(
            "`{name}` says nothing about when it is due — a poll entry carries exactly one of \
             `every = \"10m\"` or `cron = \"0 3 * * *\"`. A clock with no cadence never fires, \
             which is spelled by writing no entry"
          ),
        ));
        continue;
      }
      (Some((text, interval)), None) => {
        // The zone qualifies a WALL CLOCK, and an interval has none: `every` counts elapsed time
        // from the last tick and never asks what o'clock it is anywhere. A word nothing spends is a
        // promise rather than a rule, so it is refused where an author can read why.
        if let Some(zone) = &block.zone {
          errors.push(syn::Error::new_spanned(
            zone,
            format!(
              "`{name}` runs on an interval, and `tz` has nothing to qualify there — an interval \
               counts elapsed time from its last tick and never asks what o'clock it is. The word \
               belongs beside `cron = \"…\"`, which is wall-clock and therefore has a zone"
            ),
          ));
        }
        let _ = text;
        PollCadence::Every(interval)
      }
      (None, Some(text)) => {
        let expression = text.value();
        let zone = block.zone.as_ref().map(syn::LitStr::value);
        if let Err(refusal) = ingraph_codegen::cron::check(&expression, zone.as_deref()) {
          errors.push(syn::Error::new_spanned(
            &text,
            format!("`cron = \"{expression}\"` is not a schedule this grammar reads — {refusal}"),
          ));
          continue;
        }
        PollCadence::Calendar { expression, zone }
      }
    };
    let variant = format_ident!("{}", name.to_string().to_upper_camel_case());
    if let Some(first) = entries.iter().find(|entry| entry.variant == variant) {
      errors.push(syn::Error::new_spanned(
        &name,
        format!(
          "`{record}` mints two poll entries that would take the same word — `{}` and `{name}` \
           both come out as `{variant}`, and that word is the variant a tick from either arrives \
           under. It is read off the name rather than declared, so two entries cannot share it",
          first.name,
        ),
      ));
      continue;
    }
    // THE MODE, mandatory. Settled here rather than during the walk for the cadence's reason: the
    // word can be written anywhere in the entry, so nothing about it can be judged before the entry
    // closes — and its refusals name the clock, which is only now settled.
    let Some((mode, at)) = block.mode else {
      // Silent where a mode word WAS written and refused on its own terms — one mistake, one error.
      if block.spoken {
        continue;
      }
      errors.push(syn::Error::new_spanned(
        &block.at,
        format!(
          "`{name}` does not say WHERE it runs — a poll entry carries exactly one of {}. There is \
           no default, because a role is DECLARED rather than inferred: what a tick costs the \
           driver is the difference between a body it awaits, a body it blocks on, and a body it \
           hands to an executor, and none of the three is the obvious one. Today's behaviour is \
           `async(inline)`",
          offered()
        ),
      ));
      continue;
    };

    // THE BODY, mandatory and singular. Settled here for the mode's reason — either word can be
    // written anywhere in the entry — and the three refusals are the whole of the rule: an entry
    // names ONE of the two roads, and the road it named has to be one its mode can reach.
    match (&block.handler, &block.light) {
      (None, None) => {
        // Silent where a body word WAS written and refused on its own terms — the mode's rule, one
        // question over: one mistake, one error.
        if !block.body_spoken {
          errors.push(syn::Error::new_spanned(
            &block.at,
            body_is_named(&name, record),
          ));
        }
        continue;
      }
      (Some(_), Some(word)) => {
        errors.push(syn::Error::new_spanned(
          word,
          format!(
            "`{name}` names both `handler = \"…\"` and `light`, and one clock runs ONE body — a \
             mounted citizen and this node's own sweep method are two answers to who runs the \
             tick, and nothing decides between them. Two bodies are two entries"
          ),
        ));
        continue;
      }
      // A DETACHED tick leaves with a value it owns, and the node's own operator is not one it can
      // be given: the driver LENDS the operator per tick and takes it back. So the detached modes
      // are exactly the modes a MOUNT makes reachable, and `light` is the word that says so.
      //
      // AT THE MODE, as it was before the word existed: the two ways out are a mount and an inline
      // mode, and the mode is the half an author who wrote `light` deliberately would be changing.
      (None, Some(_)) if mode.detached() => {
        errors.push(syn::Error::new_spanned(
          &at,
          format!(
            "`{name}` is `light` and runs `{}`, which DETACHES the tick — and a light body is not \
             a thing that can be detached. It is a `{record}Sweeps` method on the node's own \
             value, which the driver lends for the call and takes back: a borrow cannot be handed \
             to another thread, and a copy of it would mutate state nothing reads. Mount a citizen \
             with `handler = \"…\"` — the deployment builds that value, so a clone of it per tick \
             is a thing that can be reasoned about — or run this clock in place with `block` or \
             `async(inline)`",
            mode.as_str()
          ),
        ));
        continue;
      }
      (Some(_), None) | (None, Some(_)) => {}
    }
    // The two settled roads become the model's own word. The refusals above are what makes this
    // total: what reaches here named exactly one body, so `light` is a WORD here and never the
    // absence of one.
    let body = match block.handler {
      Some(mounted) => PollBody::Citizen(mounted),
      None => PollBody::Light,
    };

    // THE KNOB'S SEAT. It is the sync-detached family's, and the two refusals say different things
    // because the two mistakes are different: an inline clock has nothing to overlap, and an
    // `async(spawn)` one already overlaps.
    let concurrent = match (block.concurrent, mode) {
      (None, _) => false,
      (Some(_), mode) if mode.lapses() => true,
      (Some(word), PollMode::AsyncSpawn) => {
        errors.push(syn::Error::new_spanned(
          &word,
          format!(
            "`{name}` runs `async(spawn)`, which is ALREADY concurrent — every tick fires, the \
             tasks are cheap and the runtime multiplexes them, so there is no at-most-one default \
             here for the word to lift. `concurrent` belongs to `spawn` and `rayon`, where a tick \
             costs a thread and the pile-up is the failure mode a default has to stand against"
          ),
        ));
        continue;
      }
      (Some(word), mode) => {
        errors.push(syn::Error::new_spanned(
          &word,
          format!(
            "`{name}` runs `{}`, which is INLINE — the driver awaits or blocks on the tick before \
             it takes the next one, so two of this clock's ticks cannot be in flight at once and \
             there is nothing for the word to allow. `concurrent` belongs to `spawn` and `rayon`, \
             the modes that detach",
            mode.as_str()
          ),
        ));
        continue;
      }
    };

    // THE PERMISSION, folded last because it is read against the name: a refusal about this clock's
    // grants names the clock, and the clock has only just been settled.
    let grants = block
      .write
      .and_then(|granted| entry_grants(record, &name, granted, errors));
    entries.push(PollEntry {
      name,
      variant,
      cadence,
      grants,
      body,
      mode,
      concurrent,
    });
  }
  (!entries.is_empty()).then_some(Polls { entries })
}

/// The sentence an entry that named NO body is refused with.
///
/// The rework's own rule, and the mandatory-mode sentence one question over: WHO runs a tick is
/// declared rather than inferred. The implicit form this replaces — neither word, meaning the sweep
/// method — read as an answer only to someone who already knew the grammar, and it made the
/// commonest declaration the one that said the least about itself.
///
/// It names the node's own trait, because the road `light` takes is a method an author then has to
/// go and write, and the name of the thing to write it on is the next thing they need.
fn body_is_named(name: &syn::Ident, record: &syn::Ident) -> String {
  format!(
    "`{name}` does not say WHO runs it — a poll entry names its body with exactly one of `handler \
     = \"…\"`, which mounts a citizen the deployment built, or `light`, which runs this node's own \
     `{record}Sweeps` method on the operator the driver lends. There is no default, because the \
     two are different things and not two spellings of one: a citizen is a value with its own \
     state, reusable across declarations and testable without a resident, and a light body is a \
     method over this node's own. Today's behaviour is `light`"
  )
}

/// The five mode words as a refusal offers them, read off the vocabulary rather than copied beside
/// it — so a sixth word could not be added without this sentence learning it.
fn offered() -> String {
  PollMode::ALL
    .iter()
    .map(|mode| format!("`{}`", mode.as_str()))
    .collect::<Vec<_>>()
    .join(", ")
}

/// The sentence `emits` is refused with when its value is not one quoted type or a list of them.
///
/// It names the container spelling by name for [`OUT_IS_QUOTED`]'s reason — `emits(A, B)` was legal
/// and is not — and states the law that decides the shape, so the two respellings read as one rule
/// rather than as two edits.
const EMITS_IS_QUOTED: &str = "`emits = \"…\"` names this node's ONE product and `emits = [\"…\", \
                              \"…\"]` names several — quoted, and the container `emits(A, B)` is \
                              the older spelling. The word names MESSAGE TYPES, and a type path is \
                              written in a string literal here as `subscribe = \"…\"` and `node = \
                              \"…\"` are";

/// The `emits` word read as ONE declaration: the products, and the two ways the list can be
/// wrong.
///
/// The variant is the type path's LAST SEGMENT, as a fan-in's is: the word is what the discriminant
/// IS everywhere it is spelled, so minting it once off the declaration is what keeps them one
/// vocabulary. Two products whose last segments agree are refused for a fan-in's reason — a rename
/// word will settle it, and until it exists the second product has no spelling.
///
/// The CEILING is the `Wanted` mask's, stated rather than discovered: the connection state is one
/// bit per product in a `u64`, so a sixty-fifth product would read as unwanted forever. Refused by
/// name, at the word.
fn declared_products(
  record: &syn::Ident,
  word: Option<EmitsWord>,
  errors: &mut Errors,
) -> Option<Products> {
  let word = word?;
  let mut products: Vec<Product> = Vec::new();
  for ty in word.products {
    let variant = ty
      .segments
      .last()
      .expect("a path has at least one segment")
      .ident
      .clone();
    if let Some(first) = products
      .iter()
      .find(|earlier: &&Product| earlier.variant == variant)
    {
      errors.push(syn::Error::new_spanned(
        &ty,
        format!(
          "`{record}` declares two products whose names agree — `{}` and `{}` both end in \
           `{variant}`, and that word is the variant naming this product everywhere it is spelled. \
           It is read off the declaration rather than declared, so two products cannot share it: a \
           `name = \"…\"` word will settle a genuine collision, and until it exists the second \
           product has no spelling",
          path_text(&first.ty),
          path_text(&ty),
        ),
      ));
      continue;
    }
    products.push(Product { ty, variant });
  }
  if products.len() > CONNECTED_CEILING {
    errors.push(syn::Error::new_spanned(
      &word.at,
      format!(
        "`{record}` declares {} products, and {CONNECTED_CEILING} is the ceiling — the connection \
         state a body reads is one bit per product, so a product past the {CONNECTED_CEILING}th \
         would read as wanted by nobody forever. Refused by name rather than answered wrongly",
        products.len(),
      ),
    ));
  }
  (!products.is_empty()).then_some(Products { products })
}

/// The sentence a container-shaped `write` is refused with.
///
/// [`EMITS_IS_QUOTED`]'s twin, and it states the same law for the same reason: `write` REFERS — it
/// names nodes another declaration minted — so it wears the quoted-assignment spelling every
/// referring word in this grammar wears.
const WRITE_IS_QUOTED: &str = "`write = \"…\"` grants this clock the right to write into ONE other \
                               node's store and `write = [\"…\", \"…\"]` grants several — quoted, \
                               because the word names NODES and a type path is written in a string \
                               literal here as `subscribe = \"…\"` and `emits = \"…\"` are";

/// The sentence a UNIT-LEVEL `write` is TAUGHT with — the dead spelling, pointing into the poll.
///
/// A refusal rather than a silent move, and a TEACHING one rather than the generic unknown-word row,
/// because the word was legal one ruling ago: a declaration carrying the old spelling is a
/// declaration whose author has to be told where the word went, not one whose author mistyped.
const WRITE_SITS_IN_THE_POLL: &str = "`write` is a word INSIDE a `poll(…)` entry, not beside them — \
   `poll(nightly, cron = \"0 3 * * *\", write = \"media::Media\", light, async(inline))`. A \
   permission is spent BY A TICK, so it is seated at the clock whose ticks spend it: the emission \
   mints one grants context per clock, and a tick reaching for a store another clock was granted \
   is an unsatisfied bound at the line that reached. Two clocks that share a store write the word \
   twice — explicit repetition rather than one list nobody can read a clock's reach off";

/// ONE poll entry's `write` word read into its grants: the mount each carries, and every way the
/// list can be wrong.
///
/// # The mount is the path's LAST SEGMENT, folded
///
/// `write = "media::Media"` mounts as `media`, which is the granted node's MOUNT NAME — the name a
/// node carries when nobody renames it — and it is read off the declaration for
/// [`declared_products`]'s reason: the derive that writes the grant cannot see the derive that
/// declares the store, so the last segment is the only name both ends hold. Two grants whose folded
/// segments agree are refused for the same reason a fan-in's colliding products are: the word is
/// what the context's own field IS, so two grants cannot share it.
///
/// # The collision is per ENTRY, and that is the ruling
///
/// Two clocks granting the SAME store is legal and mints two contexts, each with its own field —
/// the explicit repetition the ruling chose over one shared list. So the walk is scoped to one
/// entry's own grants, and nothing here looks at what a sibling clock was granted.
///
/// # There is no no-clock row
///
/// It cannot be written. The word's only seat is inside a `poll(…)` entry, so a grant with no clock
/// is unwritable rather than refused, and the collect-all row that used to catch it retired with the
/// unit-level spelling.
fn entry_grants(
  record: &syn::Ident,
  name: &syn::Ident,
  granted: Vec<syn::Path>,
  errors: &mut Errors,
) -> Option<Grants> {
  let mut grants: Vec<Grant> = Vec::new();
  for node in granted {
    let segment = node
      .segments
      .last()
      .expect("a path has at least one segment")
      .ident
      .clone();
    // THE ONE MOUNT-NAME VOCABULARY, third axis: `shelf_name` is what a channel shelf's field is
    // already named by, and a grant's own field is the same law over a different word. A second
    // spelling of it here is how the two would come to disagree.
    let mount = shelf_name(&segment);
    if let Some(first) = grants
      .iter()
      .find(|earlier: &&Grant| earlier.mount.safe() == mount.safe())
    {
      errors.push(syn::Error::new_spanned(
        &node,
        format!(
          "`{record}`'s `{name}` clock grants two writes whose mounts agree — `{}` and `{}` both \
           fold to `{mount}`, and that word is the granted node's mount name everywhere it is \
           spelled, so this clock's context would hold one handle under it twice. It is read off \
           the declaration rather than declared, so two grants cannot share it: name the second \
           store by a path whose last segment differs, or drop the duplicate. Two DIFFERENT clocks \
           granting one store is a different thing and is legal — two entries, two contexts",
          path_text(&first.node),
          path_text(&node),
          mount = mount.safe(),
        ),
      ));
      continue;
    }
    grants.push(Grant { node, mount });
  }
  (!grants.is_empty()).then_some(Grants { grants })
}

/// How many products the connection state can carry — `ingraph`'s `Wanted::CEILING`, restated at
/// the front end that refuses the declaration which would exceed it.
///
/// Two copies of a number is how one drifts, and the alternative was worse: the derive cannot name
/// a runtime constant of the crate it emits FOR (it does not depend on it), so the honest shape is
/// one named constant here whose docs point at the other. `ingraph`'s own
/// `the_mask_is_one_bit_per_product_and_the_ceiling_holds` pins the runtime half.
const CONNECTED_CEILING: usize = u64::BITS as usize;

fn fusion_entry(
  inner: &syn::meta::ParseNestedMeta<'_>,
  node: &mut Option<syn::Path>,
  key: &mut Option<syn::Path>,
  kind: NodeKind,
  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(());
  }

  if inner.path.is_ident("key") {
    // A DESIGNATION rather than a setting: the entry it is written on is the answer, so there is
    // nothing left for a value or a block to say. Refused rather than read past, because a `key =
    // "…"` an author wrote to name the parent has already named it — on the entry above.
    if attribute::has_value(inner) || attribute::has_block(inner) {
      errors.push(named(
        inner,
        "`key` is a DESIGNATION and is written bare — the entry it sits on is the upstream being \
         designated, so there is nothing beside it left to name"
          .to_owned(),
      ));
      return Ok(());
    }
    set_once(
      key,
      inner.path.clone(),
      &inner.path,
      "`key` is written twice in one `upstream(…)` — one entry designates one upstream",
      errors,
    );
    return Ok(());
  }

  errors.push(named(
    inner,
    format!(
      "`upstream(…)` on {article} {noun} names ONE upstream of a fusion — `node = \"…\"`, and `key` \
       on the one this node's identity descends from. It projects nothing: a fusing node computes \
       its fields from the messages it joins, so no field of it is READ OUT OF a named upstream \
       field. A node whose every field is read out of one message is a derived index, declared \
       with the `fulltext`, `vector` or `blob` macro",
      article = kind.article(),
      noun = kind.noun(),
    ),
  ));
  Ok(())
}

/// `<field>(source = "…")` inside `lineage(fields(…))` — the parent key's field this column equals.
///
/// Written only where the two names diverge, which is what makes the block readable at the size a
/// real lineage reaches: a mirror that agrees with the parent costs nothing, and a word appears
/// exactly where a reader needs to be told something.
fn mirrored_field(
  field: &syn::meta::ParseNestedMeta<'_>,
  name: &syn::Ident,
  errors: &mut Errors,
) -> Option<syn::Ident> {
  // The flat spelling of the same idea, and it reads as a RENAME of the lineage column rather than
  // as a mapping onto the parent's — which is a word this block already has, in `rename = "…"`.
  if attribute::has_value(field) {
    errors.push(named(
      field,
      format!(
        "`{name}` names a lineage field, and the parent key's field it mirrors is written inside \
         it — `{name}(source = \"…\")`. A bare `=` here would read as renaming the column, which \
         is `lineage(rename = \"…\")`'s scope and not this one"
      ),
    ));
    return None;
  }
  let mut from = None;
  let walked = attribute::options(field, |option| {
    if option.path.is_ident("source") {
      match value::literal(
        &option,
        "`source = \"…\"` names ONE field of the designated parent's key, in a string literal",
      ) {
        // The reader RESPANS to the literal, which is why the string is kept: every error the
        // emitted equation reports about this mapping lands where the author wrote it. It is the
        // RAW-IDENT-tolerant one, the same law the artifact family's two positions take: a parent's
        // key field may be legally called `r#type`, and the word the schema and the database know
        // it by is `type` — so both spellings name it, and what is an identifier under neither is
        // still refused with the sentence below.
        Ok(literal) => match value::named_field(
          &literal,
          "`source = \"…\"` names ONE field of the parent's key, so its value is a field name — a \
           path, an expression or an empty string is not one",
        ) {
          Ok(parsed) => set_once(
            &mut from,
            parsed,
            &option.path,
            "`source` is declared more than once — one column mirrors one field of the parent's key",
            errors,
          ),
          Err(e) => errors.push(e),
        },
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    errors.push(attribute::unknown(
      &option,
      "unknown entry on a lineage field — it takes `source = \"…\"`, naming the field of the \
       designated parent's key this column equals",
      &["source"],
    ));
    Ok(())
  });
  if let Err(e) = walked {
    errors.push(e);
  }
  from
}

/// Walk the node's own attributes. A refused value leaves its default in place and records the
/// refusal, so the pass keeps going and the next rule is still checked.
///
/// The NODE KIND decides which storage block this declaration may write, and there is nothing else
/// for it to decide here: the MACRO IS the storage declaration, so the block a node takes is a
/// fact about the derive it was written under and every other one is somebody else's.
fn record_options(attrs: &[syn::Attribute], node: NodeKind, errors: &mut Errors) -> Options {
  let mut construction: Option<Construction> = None;
  let mut krate = None;
  let mut key_rename = None;
  let mut key_seen = None;
  let mut lineage = None;
  let mut lineage_seen = None;
  let mut persist_block: Option<PersistBlock> = None;
  let mut graphql_block: Option<GraphqlBlock> = None;
  let mut derived_block: Option<DerivedBlock> = None;
  let mut locate_block: Option<LocateBlock> = None;
  let mut memberships: Vec<syn::Path> = Vec::new();
  let mut implements_seen: Option<syn::Path> = None;
  let mut subscribe: Option<syn::Path> = None;
  let mut subscribe_seen: Option<syn::Path> = None;
  let mut subscriptions: Option<SubscribeBlock> = None;
  let mut emits_seen: Option<syn::Path> = None;
  let mut products: Option<EmitsWord> = None;
  let mut polls: Vec<PollBlock> = Vec::new();
  let mut teardown: Option<syn::Path> = None;
  let mut asynchronous: Option<syn::Path> = None;
  let mut streaming: Option<syn::Path> = None;
  let mut autonomous: Option<syn::Path> = None;
  let mut attributed: Option<syn::Path> = None;
  let mut options_type: Option<syn::Path> = None;
  let mut remote: Option<syn::Path> = None;
  let mut upstreams: Vec<UpstreamBlock> = Vec::new();
  let mut declared_errors: Vec<BackendError> = Vec::new();
  let mut tracing: Option<TracingLevel> = None;
  let mut tracing_seen: Option<syn::Path> = None;
  let mut receipt: Option<syn::Path> = None;

  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") {
      // Kept as a PATH, never as a string: a value that cannot be a path is refused here rather
      // than pasted into an expansion and failing somewhere downstream.
      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(());
    }

    // THE OPTIONS TYPE — what a deployment's section for this node deserializes into.
    //
    // It refers to a type the declaration did not mint, so it is written QUOTED, like every other
    // referring word in this grammar. Absent means `()` — a node with no knobs, which is most of
    // them, writes nothing.
    //
    // What it buys is the ROOT's spine: the emitted options can name the path a declaration wrote
    // instead of projecting `<Node as AsyncConstructor>::Options`, which put a compile-time demand on
    // every node in a catalog just to spell the type of a section. The author's `AsyncConstructor` still
    // owns the type — the two are pinned equal by an emitted equation, so a declaration whose word
    // and whose constructor disagree is refused where the launch is written rather than deep inside
    // a walk.
    if meta.path.is_ident("options") {
      match value::parse_literal::<syn::Path>(
        &meta,
        "`options = \"…\"` must be a path to this node's options type, in a string literal",
      ) {
        Ok(path) => set_once(
          &mut options_type,
          path,
          &meta.path,
          "`options` is declared more than once — one node is configured by one type",
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }

    // THE RECEIPT TYPE — what a consumer hands BACK for one item of THIS MESSAGE.
    //
    // A referring word, so it is written QUOTED exactly as `options` and `subscribe` are: it names a
    // type this declaration did not mint, nothing here resolves it, and the path is EMITTED — so a
    // path naming nothing is `E0412` at the string the author wrote, `LitStr::parse` having
    // respanned the tokens onto the literal.
    //
    // KIND-GATED to the rungs that MINT a message, which is the re-key's whole grammar half: a
    // receipt is a property of the thing GIVEN, so the word belongs on the declaration a producer
    // gives — see [`receipt_is_the_messages_word`], which owns the sentence.
    //
    // WHAT THE WORD BUYS is `impl Receipts for <Message> { type Receipt = <path>; }`, which is the
    // ONLY place a declaration can state this fact: the producer holding the far end of the ack
    // cannot see these tokens, and the seat is a SIBLING trait rather than a member of anything
    // because associated-type defaults are unstable (`E0658`) and a corpus of messages must not each
    // write a line to say they are answered with nothing. So the word is a DECLARATION and not a
    // restatement — there is no impl it repeats, because absent the word there is no impl at all.
    // Hand-writing the impl instead stays equally legal, and it is the road a GENERIC message takes;
    // two roads, one seat.
    if meta.path.is_ident("receipt") {
      if !node.mints_a_message() {
        errors.push(named(&meta, receipt_is_the_messages_word(node)));
        return Ok(());
      }
      match value::parse_literal::<syn::Path>(
        &meta,
        "`receipt = \"…\"` must be a path to the type a consumer answers this message with, in a \
         string literal",
      ) {
        Ok(path) => set_once(
          &mut receipt,
          path,
          &meta.path,
          "`receipt` is declared more than once — one message is answered with one type",
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }

    // THE REWRITE WORD — the foreign type this declaration mirrors, and the one word in this
    // grammar that changes what the FIELDS mean rather than adding a fact beside them.
    //
    // A path in a STRING, exactly as `crate`, `options` and `subscribe` are: it refers to a type
    // this declaration did not mint, so nothing here resolves it — the path is EMITTED, and a path
    // naming nothing is `E0412` at the string the author wrote.
    //
    // Kind-gated to the two rungs that PUBLISH: an operator is the node family's base, and a
    // wrapper with no address is a value rather than a node. See [`remote_is_a_published_rung`].
    if meta.path.is_ident("remote") {
      if !node.dressable() {
        errors.push(named(&meta, remote_is_a_published_rung(node)));
        return Ok(());
      }
      match value::parse_literal::<syn::Path>(
        &meta,
        "`remote = \"…\"` names the type this declaration wraps, as a type path in a string literal",
      ) {
        Ok(path) => set_once(
          &mut remote,
          path,
          &meta.path,
          "`remote` is declared more than once — one declaration wraps one type",
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }

    // THE CONSTRUCTION PROTOCOL — how the wrapped type is BUILT, where the default law does not
    // describe it. Read here and refused at the ASSEMBLY where nothing is wrapped: the two words
    // are entries in one walk, so neither can see whether the other was written.
    if meta.path.is_ident(crate::construct::WORD) {
      return crate::construct::container(&meta, &mut construction, errors);
    }

    // THE EDGE, in its two spellings. `subscribe = "…"` is the short form for a node driven by ONE
    // upstream; `subscribe(upstream(…), …)` is the CONTAINER, and holds the whole fan-in. A path is
    // written as a STRING and re-parsed, which is this grammar's rule for every type it names — and
    // it is not stringly typed, because nothing here resolves it: the path is EMITTED, and the
    // compiler resolves it where it lands.
    //
    // ONE word, two arities. The container is what a node with several upstreams writes, and each
    // entry inside it carries the facts a bare path has no room for: whether the upstream joins the
    // keyed group, and which of a multi-product upstream's products this edge takes.
    if meta.path.is_ident("subscribe") {
      set_once(
        &mut subscribe_seen,
        meta.path.clone(),
        &meta.path,
        "`subscribe` is declared more than once — one node has one fan-in. `subscribe = \"…\"` \
         names the one upstream a node is driven by, and `subscribe(upstream(…), …)` names them all",
        errors,
      );
      if attribute::has_value(&meta) {
        match value::parse_literal::<syn::Path>(
          &meta,
          "`subscribe = \"…\"` names the upstream node, as a type path in a string literal",
        ) {
          Ok(path) => subscribe = Some(path),
          Err(e) => errors.push(e),
        }
        return Ok(());
      }
      // An EMPTY container is answered here rather than walked: a node that subscribes to nothing
      // is spelled by writing no `subscribe` at all, and the empty parentheses would otherwise
      // parse into a fan-in with no arms.
      if !attribute::has_block(&meta) || attribute::empty_group(&meta) {
        errors.push(named(
          &meta,
          "`subscribe(…)` holds at least one `upstream(node = \"…\")` entry — a node that draws \
           from nothing is spelled by omitting the word, and one upstream is \
           `subscribe = \"path::To::Upstream\"`"
            .to_owned(),
        ));
        return Ok(());
      }
      let mut entries: Vec<SubscribeEntry> = Vec::new();
      let walked = meta.parse_nested_meta(|inner| {
        if inner.path.is_ident("upstream") {
          let at = inner.path.clone();
          let mut entry = SubscribeEntry {
            node: None,
            key: None,
            out: None,
            channel: None,
            changes: None,
            notify: None,
            at,
          };
          let walked =
            attribute::options(&inner, |word| subscribe_entry(&word, &mut entry, errors));
          entries.push(entry);
          return walked;
        }
        errors.push(attribute::unknown(
          &inner,
          "unknown entry in `subscribe(…)` — every upstream is one `upstream(node = \"…\")` entry, \
           carrying `key` where it joins the keyed group, `notify` where this consumer wants the \
           landed entity's KEY rather than the entity, `out = \"<Variant>\"` where the upstream \
           emits several products, and `channel = bounded(…) | unbounded` where its author ships a \
           default for the edge",
          // The CONTAINER takes one word; the rest of the sentence names what a `upstream(…)` entry
          // carries, which is the position one level in.
          &["upstream"],
        ));
        Ok(())
      });
      subscriptions = Some(SubscribeBlock { entries });
      return walked;
    }

    // THE PRODUCTS, self-declared. Two derives cannot see each other, so a node's downstream cannot
    // tell it what it produces and a subscription is a CONNECTION rather than the source of truth.
    // What this word buys is the sum a multi-product node's `Out` becomes, the vocabulary naming its
    // arms, and the per-product edges its wire set holds.
    //
    // The products are QUOTED — `emits = "…"` for one, `emits = ["…", "…"]` for several — because
    // this word REFERS: it names MESSAGE TYPES, and the refer-quoted half of the round's law covers
    // every type path this grammar names. The container spelling it replaces is answered BY NAME
    // below, an author who wrote one having a declaration to migrate rather than an unknown word.
    if meta.path.is_ident("emits") {
      let at = meta.path.clone();
      set_once(
        &mut emits_seen,
        at.clone(),
        &at,
        "`emits` is declared more than once — one word names every product this node has",
        errors,
      );
      if attribute::has_block(&meta) {
        errors.push(named(&meta, EMITS_IS_QUOTED.to_owned()));
        return Ok(());
      }
      let literals = match value::literals(&meta, EMITS_IS_QUOTED) {
        Ok(literals) => literals,
        Err(e) => {
          errors.push(e);
          return Ok(());
        }
      };
      let mut declared: Vec<syn::Path> = Vec::new();
      for literal in literals {
        // The parse RESPANS to the literal, which is why the string is kept: every error the
        // emitted product face reports about a type lands where the author wrote it.
        match literal.parse::<syn::Path>() {
          Ok(product) => declared.push(product),
          Err(_) => errors.push(syn::Error::new_spanned(
            &literal,
            "`emits` names MESSAGE TYPES, so each value is a type path — an expression or an empty \
             string is not one",
          )),
        }
      }
      if declared.is_empty() {
        errors.push(syn::Error::new_spanned(
          &at,
          "`emits` names at least one product — a node whose product is the declared struct itself \
           is spelled by omitting the word",
        ));
        return Ok(());
      }
      products = Some(EmitsWord {
        products: declared,
        at,
      });
      return Ok(());
    }

    // THE DEAD SPELLING, kept alive only as a TEACHING refusal. `write` was a unit-level word for
    // one ruling; the ruling that moved it INTO the poll entry left this seat empty, so a
    // declaration that still writes the word here earns a sentence pointing at where it went rather
    // than the generic unknown-word row.
    //
    // It is also what makes the old no-clock refusal unnecessary: the word's only seat is inside a
    // `poll(…)` entry, so a grant with no clock is now unwritable rather than refused.
    if meta.path.is_ident("write") {
      errors.push(named(&meta, WRITE_SITS_IN_THE_POLL.to_owned()));
      return Ok(());
    }

    // THE NODE'S OWN CLOCK, and it is OUTSIDE the fan-in container by the ruling's own physics: a
    // tick is a WAKE. It moves no message, it touches no `In` enum, and what the node does with it
    // is read through the handles it already holds — so a poll source is not an upstream and the
    // word does not live among them. One entry per clock, and DECLARATION ORDER IS THE CONTRACT:
    // the position an entry lands at is the position a tick carries.
    if meta.path.is_ident("poll") {
      let at = meta.path.clone();
      if !attribute::has_block(&meta) || attribute::empty_group(&meta) {
        errors.push(named(&meta, POLL_TAKES_A_NAME.to_owned()));
        return Ok(());
      }
      let mut block = PollBlock {
        name: None,
        every: None,
        cron: None,
        zone: None,
        write: None,
        handler: None,
        light: None,
        body_spoken: false,
        mode: None,
        concurrent: None,
        spoken: false,
        at,
      };
      let walked = attribute::options(&meta, |inner| poll_entry(&inner, &mut block, errors));
      polls.push(block);
      return walked;
    }

    // FUSION: several upstreams jointly making one output, one of them designated the key parent.
    // One entry per upstream, and the macro's own argument list is the container that holds them.
    // The entries INSIDE `subscribe(…)` are spelled the same and answer a different question — see
    // `subscribe_entry` for the split.
    if meta.path.is_ident("upstream") {
      let at = meta.path.clone();
      let (mut upstream, mut key) = (None, None);
      let walked = attribute::options(&meta, |inner| {
        fusion_entry(&inner, &mut upstream, &mut key, node, errors)
      });
      upstreams.push(UpstreamBlock {
        node: upstream,
        key,
        at,
      });
      return walked;
    }

    // THE GOODBYE, opted into. A constructed value is torn down by `Drop` unless it has something
    // to AWAIT before the process leaves it — a flush, a device released politely, a lock removed —
    // and this word is where a declaration says that it has. It carries nothing, because what to say
    // is the `AsyncTeardown` impl's and the expansion's whole content is the demand that one exists.
    if meta.path.is_ident("teardown") {
      if attribute::has_value(&meta) || attribute::has_block(&meta) {
        errors.push(named(
          &meta,
          "`teardown` is a bare word — the goodbye itself is the `AsyncTeardown` impl on this type, so \
           there is nothing here to configure"
            .to_owned(),
        ));
        return Ok(());
      }
      set_once(
        &mut teardown,
        meta.path.clone(),
        &meta.path,
        "`teardown` is declared more than once — one declaration says goodbye once",
        errors,
      );
      return Ok(());
    }

    // THE MODE WORD. A bare declaration is on the BLOCKING face — an `accept` that answers — and
    // this is what buys the awaited one. It carries nothing for the same reason `teardown` does
    // not: what the body does is the `AsyncOperator` impl's, and the expansion's whole content is
    // the demand that the impl be that one.
    //
    // The word is READ ONLY BY THIS MACRO, which is the dual-mode law's own mechanism: the root
    // that mounts this node cannot see it, and reaches the same fact through the `Declared::Mode`
    // seat the emission sets.
    if meta.path.is_ident("async") {
      if attribute::has_value(&meta) || attribute::has_block(&meta) {
        errors.push(named(
          &meta,
          "`async` is a bare word HERE — it names the face this node's own `accept` wears, and the \
           body itself is the `AsyncOperator` impl on this type, so there is nothing to configure. \
           (The `async(inline)` / `async(spawn)` pair inside `poll(…)` is a different word on a \
           different axis: it says WHERE a tick runs, not what a unit answers.)"
            .to_owned(),
        ));
        return Ok(());
      }
      set_once(
        &mut asynchronous,
        meta.path.clone(),
        &meta.path,
        "`async` is declared more than once — one declaration wears one face",
        errors,
      );
      return Ok(());
    }

    // THE FACE WORD. A declaration wears the BUFFERED compute pair unless it says otherwise, and
    // this is what buys the STREAMING one: `StreamOperator` for a body whose per-item fan-out grows
    // with its input, streamed out through a bounded `Feed` over one delivery's whole life.
    //
    // It is on a DIFFERENT AXIS from `async`, and the two multiply: this word picks the pair and
    // that one picks which half of it, so `stream, async` is `AsyncStreamOperator` and needs no
    // third word. Minting one would be a second spelling of a fact the mode vocabulary already
    // states.
    //
    // Bare, for `async`'s reason: what the body does is the impl's, and the expansion's whole
    // content is the demand that the impl be the streaming one. There is deliberately NO `dispatch`
    // word beside it either — a stream-faced delivery is self-contained by the face's own
    // definition, so what the lane does per delivery is DERIVED from the face rather than declared.
    if meta.path.is_ident("stream") {
      if attribute::has_value(&meta) || attribute::has_block(&meta) {
        errors.push(named(
          &meta,
          "`stream` is a bare word — it names the PAIR this node's body wears, and the body itself \
           is the `StreamOperator` (or `AsyncStreamOperator`) impl on this type, so there is \
           nothing here to configure. The per-node seats a lane runs under — how many deliveries it \
           holds at once, how deep each one's feed is cut — are `StreamOptions` at the launch, \
           because a feed policy is a value and an attribute cannot name one"
            .to_owned(),
        ));
        return Ok(());
      }
      set_once(
        &mut streaming,
        meta.path.clone(),
        &meta.path,
        "`stream` is declared more than once — one declaration wears one pair",
        errors,
      );
      return Ok(());
    }

    // THE KIND WORD, and it is the PAIR axis's THIRD value rather than a third axis. A declaration
    // wears the buffered pair unless it says otherwise, `stream` buys the streaming one, and this
    // buys the AUTONOMOUS one: a body that OWNS ITS OWN LOOP — select order, arm priority, intake
    // gating, batching, ack timing and internal workers, all the node's.
    //
    // It multiplies with `async` exactly as `stream` does — `autonomous, async` is
    // `AsyncAutonomousOperator` — and it is REFUSED beside `stream`, because a declaration wears
    // one kind and the two words would be a declaration answering the face-selection law twice.
    //
    // Bare, for `stream`'s reason: what the body does is the impl's, and the expansion's whole
    // content is the demand that the impl be the autonomous one.
    if meta.path.is_ident("autonomous") {
      if attribute::has_value(&meta) || attribute::has_block(&meta) {
        errors.push(named(
          &meta,
          "`autonomous` is a bare word — it names the KIND this node's body wears, and the body \
           itself is the `AutonomousOperator` (or `AsyncAutonomousOperator`) impl on this type, so \
           there is nothing here to configure. What such a node would otherwise configure — how \
           many workers it keeps, how it routes among them, how deep its own queues are — is \
           inside `run`, because those are the node's own and not the framework's"
            .to_owned(),
        ));
        return Ok(());
      }
      set_once(
        &mut autonomous,
        meta.path.clone(),
        &meta.path,
        "`autonomous` is declared more than once — one declaration wears one kind",
        errors,
      );
      return Ok(());
    }

    // THE ATTRIBUTION WORD. A node's observations are COUNTER-GRADE unless something says which
    // content root each output descends from, and this is where a declaration says that its outputs
    // carry one: the launch installs `RootProjection<Out>` on the node, and the journal's rows
    // become keyable by `(root, node)` instead of by nothing.
    //
    // It is NOT on the pair, mode or kind axis and composes with all three: those say what a body
    // IS, and this says what the framework does with what the body EMITS.
    //
    // Bare, for `teardown`'s reason: the projection itself is the `Attributes` impl the OUTPUT's own
    // declaration emitted, so there is no type to name here and nothing to configure. An output no
    // record declared has no such impl, and the mount is where that is refused — with the payload
    // named, which is the sentence an author can act on.
    if meta.path.is_ident("attributed") {
      if attribute::has_value(&meta) || attribute::has_block(&meta) {
        errors.push(named(
          &meta,
          "`attributed` is a bare word — the projection is the `Attributes` impl this node's OUTPUT \
           carries, emitted beside that output's own declaration, so there is nothing here to name. \
           An attribution that carries state — a journal writer, a queue, a handle — is a VALUE no \
           attribute can name, and it is attached at the launch through `Resident::attributing`"
            .to_owned(),
        ));
        return Ok(());
      }
      set_once(
        &mut attributed,
        meta.path.clone(),
        &meta.path,
        "`attributed` is declared more than once — one declaration attributes its outputs once",
        errors,
      );
      return Ok(());
    }

    if meta.path.is_ident("key") {
      return attribute::block(
        &meta,
        &mut key_seen,
        "`key(…)` is declared more than once — one block per emitted type",
        errors,
        |inner, errors| {
          if inner.path.is_ident("rename") {
            match rename(&inner) {
              Ok(name) => set_once(
                &mut key_rename,
                name,
                &inner.path,
                "`rename` is declared more than once in `key(…)` — one option, one value",
                errors,
              ),
              Err(e) => errors.push(e),
            }
            return Ok(());
          }
          errors.push(attribute::unknown(
            &inner,
            "unknown entry in `key(…)` — it takes `rename = \"…\"`",
            &["rename"],
          ));
          Ok(())
        },
      );
    }

    if meta.path.is_ident("lineage") {
      let mut names: Option<Vec<LineageField>> = None;
      let mut renamed = None;
      let walked = attribute::block(
        &meta,
        &mut lineage_seen,
        "`lineage(…)` is declared more than once — one block per emitted type",
        errors,
        |inner, errors| {
          if inner.path.is_ident("fields") {
            const REPEATED: &str = "`fields` is declared more than once in `lineage(…)` — one \
                                    list carries the whole path";
            // An EMPTY `fields()` is answered here rather than walked — see `attribute::empty_group`.
            if attribute::empty_group(&inner) {
              errors.push(syn::Error::new_spanned(
                &inner.path,
                "`fields(…)` must name at least one field — a record with no path is a root, \
                 and a root is spelled by omitting the `lineage(…)` block",
              ));
              attribute::skip_entry(&inner);
              set_once(&mut names, Vec::new(), &inner.path, REPEATED, errors);
              return Ok(());
            }
            let mut collected = Vec::new();
            let walked = inner.parse_nested_meta(|field| {
              let Some(name) = field.path.get_ident().cloned() else {
                // A path rather than a bare ident: record it and keep walking, so one pass
                // reports every offender.
                errors.push(attribute::unknown(
                  &field,
                  "`lineage(fields(…))` takes field idents",
                  // The list names THIS record's own fields, which is not a vocabulary.
                  &[],
                ));
                return Ok(());
              };
              collected.push(LineageField {
                from: mirrored_field(&field, &name, errors),
                name,
              });
              Ok(())
            });
            set_once(&mut names, collected, &inner.path, REPEATED, errors);
            return walked;
          }
          if inner.path.is_ident("rename") {
            match rename(&inner) {
              Ok(name) => set_once(
                &mut renamed,
                name,
                &inner.path,
                "`rename` is declared more than once in `lineage(…)` — one option, one value",
                errors,
              ),
              Err(e) => errors.push(e),
            }
            return Ok(());
          }
          errors.push(attribute::unknown(
            &inner,
            "unknown entry in `lineage(…)` — it takes `fields(…)` and `rename = \"…\"`",
            &["fields", "rename"],
          ));
          Ok(())
        },
      );
      match names {
        // An empty list already reported itself; dropping the block here keeps the record a root
        // rather than inventing a lineage type with no columns.
        Some(fields) if !fields.is_empty() => {
          lineage = Some(LineageBlock {
            fields,
            rename: renamed,
          });
        }
        Some(_) => {}
        None => errors.push(syn::Error::new_spanned(
          &meta.path,
          "`lineage(…)` needs `fields(…)` — it is the path the type carries, and without it \
           there is no type to emit; a root is spelled by omitting the block",
        )),
      }
      return walked;
    }

    // THE STORE WORDS, BARE AT THE HEAD — `#[ingraph::record(sqlite, postgres(schema = "…"))]`.
    //
    // Storage is a record's ESSENCE, and an essence sits bare where an OPTIONAL axis takes a block:
    // `graphql(…)` is a record's optional wire face and keeps its parentheses, and rows are what a
    // record IS. Each word's own entries are unchanged and still inside it — the unwrap took one
    // layer off the outside and moved nothing in.
    if let Some(kind) = database_kind(&meta.path) {
      if !node.holds_rows() {
        errors.push(named(
          &meta,
          format!(
            "{article} {noun} stores no rows — `{db}` names a DATABASE the rows land in, and the \
             MACRO is the storage declaration, so a node whose messages land in a database is a \
             `record`. {law}",
            article = node.article(),
            noun = node.noun(),
            db = kind.as_str(),
            law = owns_one_storage(node),
          ),
        ));
        attribute::skip_entry(&meta);
        return Ok(());
      }
      let block = persist_block.get_or_insert_with(PersistBlock::default);
      return record_database(&meta, kind, &mut block.databases, errors);
    }

    // `table` and `rename` are the store words' two COMMON entries, and they unwrapped with them.
    // Both are refused on a kind that holds no rows for the store words' own reason, and both are
    // refused BESIDE no store word by the assembly — a table name for rows that do not exist names
    // nothing.
    if meta.path.is_ident("table") || meta.path.is_ident("rename") {
      if !node.holds_rows() {
        errors.push(named(
          &meta,
          format!(
            "{article} {noun} stores no rows, so it has no {subject} to name — `{word}` is a store \
             word's common entry, and the store words are a `record`'s. {law}",
            article = node.article(),
            noun = node.noun(),
            subject = if meta.path.is_ident("table") {
              "table"
            } else {
              "row type"
            },
            word = if meta.path.is_ident("table") {
              "table"
            } else {
              "rename"
            },
            law = owns_one_storage(node),
          ),
        ));
        attribute::skip_entry(&meta);
        return Ok(());
      }
      let block = persist_block.get_or_insert_with(PersistBlock::default);
      if meta.path.is_ident("table") {
        match value::literal(&meta, TABLE_VALUE) {
          Ok(name) => set_once(
            &mut block.table,
            name,
            &meta.path,
            "`table` is declared more than once — one record, one common table name",
            errors,
          ),
          Err(e) => errors.push(e),
        }
      } else {
        match rename(&meta) {
          Ok(name) => set_once(
            &mut block.rename,
            name,
            &meta.path,
            "`rename` is declared more than once — one record, one row-type base",
            errors,
          ),
          Err(e) => errors.push(e),
        }
      }
      return Ok(());
    }

    // THE WRAPPER, refused by name. It is not an unknown word: an author who wrote it has an idea,
    // and which idea decides which sentence answers.
    //
    // On a kind with NO ROWS the mistake is the rows and not the layer, so it gets the store words'
    // own refusal — telling such an author to unwrap would send them to a shape that is refused for
    // a second reason one compile later. On a RECORD the rows are right and the layer is not, so the
    // sentence shows the line they meant rather than listing what a record takes.
    if meta.path.is_ident("persist") {
      let sentence = if node.holds_rows() {
        "`persist(…)` is gone — a record's stores are named BARE at the head, so write \
         `#[ingraph::record(sqlite)]` and keep every word that was inside each database's own \
         block. Storage is a record's ESSENCE and an essence does not wrap; `graphql(…)`, which is \
         OPTIONAL, still does. A node that stores nothing is an `entity`."
          .to_owned()
      } else {
        format!(
          "{article} {noun} stores no rows — `persist(…)` was the ROW storage's wrapper and the \
           rows are a `record`'s, so unwrapping it here would only reach the same refusal one \
           compile later. {law}",
          article = node.article(),
          noun = node.noun(),
          law = owns_one_storage(node),
        )
      };
      errors.push(named(&meta, sentence));
      attribute::skip_entry(&meta);
      return Ok(());
    }

    if meta.path.is_ident("vector") {
      errors.push(named(
        &meta,
        format!(
          "{article} {noun} owns no embedding index — an index is its OWN node, so the engines this \
           block names are that node's to name: declare them with the `vector` macro, on a type \
           whose `upstream(…)` names this {noun}. `element` and `filter` describe the EMBEDDINGS \
           rather than these rows, so they travel with the engines. {law}",
          article = node.article(),
          noun = node.noun(),
          law = owns_one_storage(node),
        ),
      ));
      return Ok(());
    }

    if meta.path.is_ident("fulltext") {
      errors.push(named(
        &meta,
        format!(
          "{article} {noun} owns no full-text index — an index is its OWN node, so the engines this \
           block names are that node's to name: declare them with the `fulltext` macro, on a type \
           whose `upstream(…)` names this {noun}. {law}",
          article = node.article(),
          noun = node.noun(),
          law = owns_one_storage(node),
        ),
      ));
      return Ok(());
    }

    if meta.path.is_ident("blob") {
      errors.push(named(
        &meta,
        format!(
          "{article} {noun} owns no artifact store — a blob family is its OWN node, so the stores \
           this block names are that node's to name: declare them with the `blob` macro, on a \
           type whose `upstream(…)` names this {noun}. `extension` is part of the ADDRESS that \
           node's key renders, so it travels with the stores. {law} A column of BYTES is a \
           different thing and stays: write `bytes` beside `persist`, and the bytes are a value in \
           this {noun}'s own row.",
          article = node.article(),
          noun = node.noun(),
          law = owns_one_storage(node),
        ),
      ));
      return Ok(());
    }

    for (family, why) in DERIVED {
      if meta.path.is_ident(family) {
        errors.push(named(
          &meta,
          format!(
            "`{family}(…)` is not a declaration — it is derived from the storage families, so \
             remove the block. {why}"
          ),
        ));
        return Ok(());
      }
    }

    if meta.path.is_ident("graphql") {
      // DRESSING crosses the storage axis rather than following it, which is the ladder's own
      // correction: a wire face publishes a node's ADDRESS before it publishes any column, and an
      // address is minted by every kind that bears an identity. So a record and an entity both take
      // the block, and an operator — the family's base, which publishes nothing — does not. What
      // rides the ROWS is a wire FIELD, and that is a per-field rule answered at `stored_in`.
      if !node.dressable() {
        errors.push(named(
          &meta,
          format!(
            "{article} {noun} publishes nothing — an operator is the node family's BASE, and the \
             rowless tier that publishes its address is an `entity`. Change the macro, or drop the \
             block. {law}",
            article = node.article(),
            noun = node.noun(),
            law = owns_one_storage(node),
          ),
        ));
        return Ok(());
      }
      let at = meta.path.clone();
      let mut backends: Vec<BackendBlock> = Vec::new();
      // FOUR slots: the emitted TYPES a declaring scope holds, kept in one array because they are
      // read by one loop, which is what stops a fifth entry from being wired up a fourth way.
      let mut wire = [None, None, None, None];
      let mut renamed = None;
      // The PAGE's two SDL names, and the PLURAL, at their own three slots and at the literal rather
      // than at an ident. They are one KIND — a word naming a schema entity — and the array above is
      // the other, so they are not in it: the array is the ident-kind loop's, and a slot that held a
      // `LitStr` beside four `Ident`s is exactly the mixing the 2026-08-13 ruling separated.
      let mut connection: Option<syn::LitStr> = None;
      let mut edge_name: Option<syn::LitStr> = None;
      let mut plural: Option<syn::LitStr> = None;
      // THE ADDRESS'S TWO FACES, at their own slots for the reason the three above take theirs: they
      // are schema words rather than Rust names, and the array is the ident-kind loop's.
      let mut key_object: Option<syn::LitStr> = None;
      let mut key_argument: Option<syn::LitStr> = None;
      let walked = attribute::options(&meta, |inner| {
        if let Some(kind) = graphql_kind(&inner.path) {
          return record_backend(&inner, kind, &mut backends, errors);
        }
        // The OUTPUT block is the one that carries more than a name: its `error(…)` types the
        // crossing a stored row takes onto the object, and the cell lives AT the path the crossing
        // does rather than in a mirror tree beside it. Its three neighbours name a type and nothing
        // else, so they stay the plain rename block they were.
        if inner.path.is_ident("output") {
          return attribute::options(&inner, |option| {
            if database_kind(&option.path).is_some() {
              return error_blocks(
                &option,
                Crossing::Output,
                "graphql(output(…))",
                "try_from",
                &mut declared_errors,
                errors,
              );
            }
            if option.path.is_ident("rename") {
              match value::parse_literal::<syn::Ident>(&option, attribute::TYPE_NAME) {
                Ok(spelled) => set_once(
                  &mut wire[0],
                  spelled,
                  &option.path,
                  "`rename` is declared more than once in `output(…)` — one option, one value",
                  errors,
                ),
                Err(e) => errors.push(e),
              }
              return Ok(());
            }
            errors.push(attribute::unknown(
              &option,
              "unknown entry in `output(…)` — it takes `rename = \"…\"`, which names the object, \
                 and one block per database carrying `try_from(error = \"…\")`, which types the \
                 crossing a stored row takes onto it",
              &["rename"]
                .into_iter()
                .chain(DatabaseKind::ALL.map(DatabaseKind::as_str))
                .collect::<Vec<_>>(),
            ));
            Ok(())
          });
        }
        // The INPUT block exists for its ONE crossing and holds nothing else — the argument object
        // has no rename of its own, so nothing here is a name.
        if inner.path.is_ident("input") {
          return attribute::options(&inner, |position| {
            if position.path.is_ident("comparison") {
              return attribute::options(&position, |option| {
                error_blocks(
                  &option,
                  Crossing::Comparison,
                  "graphql(input(comparison(…)))",
                  // `try_into`, and NOT the `try_from` a first reading suggests: the leg word is the
                  // FIELD's, and a field writes this crossing with `into` because a wire value
                  // LEAVES for a row. Naming it the other way here would make the two levels
                  // disagree about one crossing, which is the drift the axis law exists to stop.
                  "try_into",
                  &mut declared_errors,
                  errors,
                )
              });
            }
            errors.push(attribute::unknown(
              &position,
              "unknown entry in `input(…)` on a record — the input half has ONE crossing that \
                 carries a value, and it is `comparison(…)`. An order names a column and a \
                 direction and a page names a cursor, so neither has an operand to convert.",
              &["comparison"],
            ));
            Ok(())
          });
        }
        // THE ADDRESS BLOCK, which is the one of the four that carries more than a base — the
        // 2026-08-16 rename ruling's fourth law. An address wears TWO faces in one GraphQL
        // namespace, so `rename = "…"` re-bases both and each may then be named outright: the base
        // is a RUST name that also derives the schema's, and the two members are the schema's alone.
        if inner.path.is_ident("key") {
          return key_block(
            &inner,
            &mut wire[1],
            &mut key_object,
            &mut key_argument,
            errors,
          );
        }
        for (index, what) in ["filter", "order_by"].into_iter().enumerate() {
          if inner.path.is_ident(what) {
            return attribute::rename_block(&inner, &mut wire[index + 2], what, errors);
          }
        }
        // `connection` and `edge` write the same BLOCK their three neighbours do — the ruling's own
        // instruction, *mirroring the block's existing rename entries* — and a different KIND of
        // word inside it. Their word names a type in GraphQL's flat namespace and nothing in Rust,
        // so it is carried as the STRING it is; the neighbours above name emitted Rust types and
        // stay identifiers.
        //
        // The 2026-08-13 ruling is what separated them: *graphql 和 db 那边 type 和其他的 rust
        // 关键词都不是问题, 所以我们应该想办法支持*. A `syn::Ident` parse refuses `type`, `where` and
        // `fn` — legal GraphQL names every one, GraphQL's own keywords being CONTEXTUAL — and
        // refusing them was a Rust fact leaking onto a schema nothing in Rust names. The one fence
        // that remains is GraphQL's Name grammar, applied where the word settles.
        for (what, slot) in [("connection", &mut connection), ("edge", &mut edge_name)] {
          if inner.path.is_ident(what) {
            return attribute::sdl_name_block(&inner, slot, what, errors);
          }
        }
        // `name` MOVED into `output(…)`: it named the schema type, the wire face emits four, and
        // one `rename` now sets both faces of whichever one its block is about.
        if inner.path.is_ident("name") {
          errors.push(named(
            &inner,
            "`name` moved into `output(…)` — the wire face emits four types, so write \
               `output(rename = \"…\")`; one `rename` sets both the Rust name and the schema name"
              .to_owned(),
          ));
          return Ok(());
        }
        if inner.path.is_ident("rename") {
          match rename(&inner) {
            Ok(spelled) => set_once(
              &mut renamed,
              spelled,
              &inner.path,
              "`rename` is declared more than once in `graphql(…)` — one option, one value",
              errors,
            ),
            Err(e) => errors.push(e),
          }
          return Ok(());
        }
        // The PLURAL — a word rather than a name, which is why it is not a `rename` and not an
        // ident: what it corrects is English, and the field that spends it lowers the initial
        // itself. Held to the wire floor here, at the literal's own span, so `""` and `9lives`
        // refuse where they were written rather than at a schema nobody can edit.
        if inner.path.is_ident("plural") {
          match value::literal(&inner, PLURAL_WORD) {
            Ok(word) => {
              wire::refuse_invalid_name(&word.value(), &word, errors);
              set_once(
                &mut plural,
                word,
                &inner.path,
                "`plural` is declared more than once in `graphql(…)` — one option, one value",
                errors,
              );
            }
            Err(e) => errors.push(e),
          }
          return Ok(());
        }
        if let Some(error) = queryability(&inner) {
          errors.push(error);
          return Ok(());
        }
        errors.push(wire_option(
          &inner,
          "unknown entry in `graphql(…)` — it takes `rename = \"…\"`, `plural = \"…\"`, a block per \
             emitted type (`output`, `key`, `filter`, `order_by`), a block per SDL page name \
             (`connection`, `edge`), `input(comparison(error(…)))` and one per backend \
             (`async_graphql`)",
          &["rename", "plural", "output", "key", "filter", "order_by", "connection", "edge", "input"]
            .into_iter()
            .chain(GraphqlKind::ALL.map(GraphqlKind::as_str))
            .collect::<Vec<_>>(),
        ));
        Ok(())
      });
      set_once(
        &mut graphql_block,
        GraphqlBlock {
          backends,
          output: wire[0].clone(),
          key: wire[1].clone(),
          filter: wire[2].clone(),
          order_by: wire[3].clone(),
          key_object,
          key_argument,
          connection,
          edge: edge_name,
          rename: renamed,
          plural,
          at: at.clone(),
        },
        &at,
        "`graphql(…)` is declared more than once — one block per emitted type",
        errors,
      );
      return walked;
    }

    if meta.path.is_ident("derived") {
      let at = meta.path.clone();
      let mut entries: Vec<DerivedEntry> = Vec::new();
      // A `derived()` naming nothing is recorded and refused at the ASSEMBLY, exactly as a record
      // naming no store is: the refusal is about the record's reverse positions rather than about an
      // entry the block did not take.
      let walked = attribute::options(&meta, |inner| derived_entry(&inner, &mut entries, errors));
      set_once(
        &mut derived_block,
        DerivedBlock {
          entries,
          at: at.clone(),
        },
        &at,
        "`derived(…)` is declared more than once — one block carries every reverse position",
        errors,
      );
      return walked;
    }

    // THE OTHER REVERSE CONTAINER, and it sits here rather than anywhere else in this walk because
    // it is the same declaration pointed the other way: `derived(…)` names what points BACK at this
    // record, and `locate(…)` names what was derived FROM it. Same reader, same sentences, same
    // assembly — see [`LocateBlock`].
    if meta.path.is_ident("locate") {
      let at = meta.path.clone();
      let mut entries: Vec<LocateEntry> = Vec::new();
      // A `locate()` naming nothing is recorded and refused at the ASSEMBLY, exactly as its sibling
      // is: the refusal is about the record's artifact families rather than about an entry the
      // block did not take.
      let walked = attribute::options(&meta, |inner| locate_entry(&inner, &mut entries, errors));
      set_once(
        &mut locate_block,
        LocateBlock {
          entries,
          at: at.clone(),
        },
        &at,
        "`locate(…)` is declared more than once — one block carries every artifact family",
        errors,
      );
      return walked;
    }

    if meta.path.is_ident("implements") {
      let at = meta.path.clone();
      let walked = attribute::options(&meta, |inner| membership(&inner, &mut memberships, errors));
      set_once(
        &mut implements_seen,
        at.clone(),
        &at,
        "`implements(…)` is declared more than once — one block carries every interface",
        errors,
      );
      return walked;
    }

    // THE OBSERVATION WORD, and the one entry in this grammar whose whole subject is how loudly
    // the framework talks about the node rather than anything the node does. It parses in every
    // build — the emission is what rides `ingraph`'s own feature — so a declaration is a fixed
    // text whatever the framework was compiled with, and a level nobody ships is refused here
    // rather than at whichever build happened to turn observation on.
    if meta.path.is_ident("tracing") {
      let at = meta.path.clone();
      if !attribute::has_block(&meta) || attribute::empty_group(&meta) {
        errors.push(named(&meta, TRACING_TAKES_A_LEVEL.to_owned()));
        return Ok(());
      }
      let walked = attribute::options(&meta, |inner| tracing_entry(&inner, &mut tracing, errors));
      set_once(
        &mut tracing_seen,
        at.clone(),
        &at,
        "`tracing(…)` is declared more than once — one node observes itself at one level",
        errors,
      );
      return walked;
    }

    // THE AGGREGATE's two role words, refused by name at the head. Read here rather than left to
    // the unknown-entry list for that refusal's own reason: an author who wrote one has a fold in
    // mind, and what they need is the kind that folds rather than a near miss at a word this
    // grammar happens to spell similarly.
    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, node, crate::aggregate::Written::AtTheHead),
        ));
        return Ok(());
      }
    }

    errors.push(attribute::unknown(
      &meta,
      &format!(
        "unknown `ingraph` record attribute — a record takes its STORE WORDS bare ({stores}, with \
         `table = \"…\"` and `rename = \"…\"` beside them), and `key(…)`, `lineage(…)`, \
         `graphql(…)`, `derived(…)`, `locate(…)`, `implements(…)`, `upstream(…)`, `subscribe`, \
         `emits`, `poll(…)`, `tracing(…)`, the bare `teardown`, `async`, `stream`, \
         `autonomous` and `attributed` words, `crate = \"…\"`, `options = \"…\"`, \
         `receipt = \"…\"`, `remote = \"…\"` and `builder(…)`",
        stores = shipped(DatabaseKind::ALL.into_iter().map(DatabaseKind::as_str)),
      ),
      &[
        "table",
        "rename",
        "key",
        "lineage",
        "graphql",
        "derived",
        "locate",
        "implements",
        "upstream",
        "subscribe",
        "emits",
        "poll",
        "tracing",
        "teardown",
        "async",
        "stream",
        "autonomous",
        "attributed",
        "crate",
        // THE OPTIONS WORD, and it was missing from BOTH halves of this refusal — the sentence a
        // reader is shown and the roster a near miss is measured against. A declaration writing
        // `option = "…"` or `opts = "…"` got the whole list and no suggestion, which is the one
        // thing this vocabulary exists to give. It is not kind-gated, so every rung that reaches
        // this parser takes it.
        "options",
        "receipt",
        "remote",
        crate::construct::WORD,
      ]
      .into_iter()
      .chain(DatabaseKind::ALL.into_iter().map(DatabaseKind::as_str))
      .collect::<Vec<_>>(),
    ));
    Ok(())
  });

  Options {
    krate: krate.unwrap_or_else(|| syn::parse_quote!(::ingraph)),
    key_rename,
    lineage,
    persist: persist_block,
    graphql: graphql_block,
    derived: derived_block,
    locate: locate_block,
    implements: memberships,
    subscribe,
    subscribe_at: subscribe_seen,
    subscriptions,
    products,
    polls,
    teardown: teardown.is_some(),
    asynchronous,
    streaming,
    autonomous,
    attributed: attributed.is_some(),
    options: options_type,
    remote,
    construction,
    upstreams,
    errors: declared_errors,
    tracing,
    receipt,
  }
}

/// The refusal `remote = "…"` earns on a NODE rung that publishes no address.
///
/// The word makes a declaration a WRAPPER over somebody else's type, and what a wrapper is FOR is
/// giving that type this framework's faces. Among NODES the discriminator is the ADDRESS: an
/// `entity` and a `record` publish one, so the word buys a key, a filter and a wire root; an
/// operator is the family's base and has none of those to give.
///
/// `fields` takes the word too and is told nothing by this sentence, because it is not on this
/// ladder at all. A fragment publishes no address and needs none — its faces are a width, a filter,
/// a comparison and an object a HOLDER resolves through — so the word is admitted where that tier's
/// grammar is written, by its own reason rather than by this one. Three declarations take it, and
/// the two this sentence is written for are the node rungs below them.
fn remote_is_a_published_rung(node: NodeKind) -> String {
  format!(
    "{article} {noun} publishes no address, and `remote = \"…\"` exists to give a FOREIGN type this \
     framework's faces — a key, a filter and a wire face are what a wrapper is for. The \
     declarations that take the word are `entity`, `record` and `fields`",
    article = node.article(),
    noun = node.noun(),
  )
}

/// The refusal `receipt = "…"` earns on a declaration that MINTS NO MESSAGE.
///
/// The word used to sit on the consumer, which made a receipt a property of the NODE: two seats over
/// one message each declared the answer's type, and the two could come to disagree about a question
/// neither of them asked. A receipt is a property of what is GIVEN — one message, one answer,
/// whichever consumer happens to be on the far end of the edge — so the word moved onto the
/// declaration that mints the message, and this is the sentence the old position now earns.
///
/// The rungs that take it are the ones [`NodeKind::mints_a_message`] names, and the refusal SENDS an
/// author there rather than only saying no: what an operator answers for is a message somebody else
/// declared, so the fix is one word on that declaration and nothing at all here.
///
/// The framework-author road is named too, because it is the one this refusal must not close. A seat
/// answering with something the message did not declare — or a message whose receipt is a generic
/// parameter no quoted path could name — states it through the open doors, which take any value and
/// project no declaration.
fn receipt_is_the_messages_word(node: NodeKind) -> String {
  format!(
    "{article} {noun} mints no MESSAGE, and `receipt = \"…\"` is a property of the thing GIVEN \
     rather than of the seat that answers for it — one message, one receipt, whichever consumer is \
     on the far end. Write the word on the declaration that MINTS the message this node is \
     answering for: an `entity` (the message node), a `record`, or an `aggregate`. A seat that must \
     answer with something its message did not declare states it through `Emitter::receipt` or \
     `Ack::receipting`, which take any value and name no type",
    article = node.article(),
    noun = node.noun(),
  )
}

/// The sentence `tracing` is refused with when it carries no block.
const TRACING_TAKES_A_LEVEL: &str = "`tracing` is a block — write `tracing(level = debug)`. The \
                                     word exists to carry the level a node's spans open at, and \
                                     there is nothing else it could say";

/// ONE entry inside `tracing(…)`.
///
/// The level is a BARE WORD and never `= "debug"`, which is the grammar's own law rather than a
/// preference here: a quoted value in this vocabulary REFERS to something declared elsewhere — a
/// type, a path, a duration somebody parses — and a level refers to nothing. It is one of five
/// words the framework itself ships, so it is written the way `dedup(hash)` and `sqlite(text)` are.
fn tracing_entry(
  inner: &syn::meta::ParseNestedMeta<'_>,
  tracing: &mut Option<TracingLevel>,
  errors: &mut Errors,
) -> syn::Result<()> {
  if !inner.path.is_ident("level") {
    errors.push(attribute::unknown(
      inner,
      "unknown entry in `tracing(…)` — the block carries exactly one word, `level = …`",
      &["level"],
    ));
    return Ok(());
  }
  let value = inner
    .value()
    .map_err(|e| syn::Error::new(e.span(), LEVEL_TAKES_A_WORD))?;
  let word: syn::Ident = value
    .parse()
    .map_err(|e| syn::Error::new(e.span(), LEVEL_TAKES_A_WORD))?;
  let Some(level) = TracingLevel::named(&word.to_string()) else {
    errors.push(syn::Error::new_spanned(
      &word,
      format!(
        "`{word}` is not a level this framework names — the words are {words}. The vocabulary is \
         `tracing`'s own five, so a level it cannot filter on is not a word here{near}",
        words = shipped(TracingLevel::ALL.into_iter().map(TracingLevel::as_str)),
        near = crate::suggest::did_you_mean(
          &word.to_string(),
          TracingLevel::ALL.map(TracingLevel::as_str)
        ),
      ),
    ));
    return Ok(());
  };
  set_once(
    tracing,
    level,
    &inner.path,
    "`level` is declared more than once in `tracing(…)` — one option, one value",
    errors,
  );
  Ok(())
}

/// The sentence `level` is refused with when its value is not a bare word.
const LEVEL_TAKES_A_WORD: &str = "`level` takes a BARE WORD — write `tracing(level = debug)` and \
                                  not `tracing(level = \"debug\")`. A quoted value in this grammar \
                                  REFERS to something declared elsewhere, and a level refers to \
                                  nothing: it is one of five words the framework itself ships";

/// ONE interface this record declares itself a member of.
///
/// # The word is the EVIDENCE, and the evidence is all it emits
///
/// An interface's declaration names its members and that alone is not evidence: the two derives
/// cannot see each other, so an interface asserting a membership its member never agreed to would
/// be claiming a promise on somebody else's behalf. This word is the agreement, and what it emits
/// is `impl Implements<Interface> for Record`.
///
/// # A rename is the INTERFACE's, and this word is refused for saying so
///
/// `implements(Media(created_at = imported_at))` reads as though a member could name its own column
/// for one of the interface's fields, and the fact is real — a member may carry a contract field
/// under another name. Where it is DECLARED is the interface, because that is the only side that
/// can check it: a member set and its contract arrive in one derive input, so a variant key is
/// checked token-for-token against the enum's own variants, where a word written here would have to
/// reach the interface's expansion across a derive boundary and only a type or a const does that.
/// So the shape is recognised, and the refusal names the home rather than reporting an unknown
/// word.
fn membership(
  inner: &syn::meta::ParseNestedMeta<'_>,
  memberships: &mut Vec<syn::Path>,
  errors: &mut Errors,
) -> syn::Result<()> {
  let interface = inner.path.clone();
  if memberships
    .iter()
    .any(|already| tight(already) == tight(&interface))
  {
    errors.push(syn::Error::new_spanned(
      interface.to_token_stream(),
      format!(
        "`{name}` is named more than once in `implements(…)` — a record is a member of an \
         interface once, and a second word states the same fact",
        name = tight(&interface)
      ),
    ));
    attribute::skip_entry(inner);
    return Ok(());
  }
  if attribute::has_value(inner) {
    // The entry NAMES an interface, so the word was the author's own type and not a vocabulary's.
    errors.push(attribute::unknown(inner, MEMBERSHIP_SHAPE, &[]));
    return Ok(());
  }
  memberships.push(interface);
  attribute::options(inner, |renamed| {
    // A membership takes nothing inside it, so the empty list is the position's real answer.
    errors.push(attribute::unknown(&renamed, MEMBERSHIP_RENAME, &[]));
    Ok(())
  })
}

/// The refusal a membership gets when it is not a bare path.
const MEMBERSHIP_SHAPE: &str = "`implements(…)` names INTERFACES — write the type, as in \
                                `implements(media::Media)`. A membership is a fact rather than a \
                                value, so there is nothing for it to be equal to";

/// The refusal a member-side column rename gets, naming what has to arrive before it can be read.
const MEMBERSHIP_RENAME: &str = "a member's column answers an interface's field name where the \
                                 INTERFACE declares it — `<field>(…, members(<Variant>(field = \
                                 \"…\")))` in \
                                 its `fields(…)` list. Declared there, the variant key is checked \
                                 against the enum's own variants in one derive input; declared \
                                 here, it would have to reach that expansion across a derive \
                                 boundary, and only a type or a const crosses one";

/// A path as a MESSAGE spells it — `quote!`'s spacing removed.
fn tight(path: &syn::Path) -> String {
  path.to_token_stream().to_string().replace(' ', "")
}

/// ONE crossing's per-database ERROR cells at the record level.
///
/// # The axis law
///
/// A DATABASE NAME ALWAYS OPENS A BLOCK, and inside it a CELL ALWAYS RIDES ITS LEG. Both are the
/// FIELD grammar's own shapes read one level up: a field writes
/// `graphql(output(sqlite(try_from = "…")))`, so the record writes
/// `graphql(output(sqlite(try_from(error = "…"))))` — the same two words in the same two positions,
/// with the entry that is the record's inside the leg that is the field's.
///
/// The leg word is NESTED even where a crossing has only one, which is the same law the field-level
/// escape follows: a shape that collapses when there is one of a thing is a shape that has to be
/// re-argued the day there are two.
fn error_blocks(
  inner: &syn::meta::ParseNestedMeta<'_>,
  crossing: Crossing,
  scope: &str,
  leg_word: &'static str,
  declared: &mut Vec<BackendError>,
  errors: &mut Errors,
) -> syn::Result<()> {
  let Some(kind) = database_kind(&inner.path) else {
    errors.push(attribute::unknown(
      inner,
      &format!(
        "unknown entry in `{scope}` — a per-database entry opens that DATABASE's block, because an \
         error is what one crossing's impls at one backend answer with: {list}",
        list = shipped(DatabaseKind::ALL.into_iter().map(DatabaseKind::as_str)),
      ),
      &DatabaseKind::ALL.map(DatabaseKind::as_str),
    ));
    return Ok(());
  };
  attribute::options(inner, |option| {
    // The flat cell is GONE: it named a crossing and not a LEG, so it had nowhere to put a second
    // one the day the crossing grew a second direction.
    if option.path.is_ident("error") {
      errors.push(named(
        &option,
        format!(
          "`error` rides its LEG now — write `{leg_word}(error = \"…\")` in `{scope}`'s `{kind}` \
           block, which is the same word the FIELD's leg is written under one level down",
          kind = kind.as_str()
        ),
      ));
      return Ok(());
    }
    if option.path.is_ident(leg_word) {
      let (_, cell) = leg(&option, leg_word, true, true, scope, errors);
      let Some(path) = cell else {
        return Ok(());
      };
      if declared
        .iter()
        .any(|error| error.crossing == crossing && error.kind == kind)
      {
        errors.push(syn::Error::new_spanned(
          &option.path,
          format!(
            "`error` is declared more than once in `{scope}`'s `{kind}` block — one leg, one type",
            kind = kind.as_str()
          ),
        ));
        return Ok(());
      }
      declared.push(BackendError {
        crossing,
        kind,
        path,
      });
      return Ok(());
    }
    errors.push(attribute::unknown(
      &option,
      &format!(
        "unknown entry in `{scope}`'s `{kind}` block — this crossing has ONE leg and it is \
         `{leg_word}(…)`, which is the word the field's own leg is written under; the cell it \
         carries is `error = \"…\"`",
        kind = kind.as_str()
      ),
      &[leg_word],
    ));
    Ok(())
  })
}

/// ONE reverse position, in whichever of its two forms it was written.
///
/// The entry's NAME is the position and the VALUE is the source, which is the half a reader gets
/// backwards — so the refusal both forms share says which is which.
///
/// A repeat is refused and DROPPED rather than appended, exactly as a repeated database block is:
/// the first declaration is what the rest of the pass reads.
fn derived_entry(
  inner: &syn::meta::ParseNestedMeta<'_>,
  entries: &mut Vec<DerivedEntry>,
  errors: &mut Errors,
) -> syn::Result<()> {
  let Some(name) = inner.path.get_ident().cloned() else {
    // The entry's NAME is a word this record MINTS for the position, so there is no vocabulary.
    errors.push(attribute::unknown(inner, DERIVED_SHAPE, &[]));
    return Ok(());
  };
  if entries.iter().any(|entry| entry.name == name) {
    errors.push(syn::Error::new_spanned(
      &name,
      format!("`{name}` is declared more than once in `derived(…)` — one position, one name"),
    ));
    attribute::skip_entry(inner);
    return Ok(());
  }
  // The shorthand: the value IS the source, and there is nothing else to read.
  if attribute::has_value(inner) {
    match value::parse_literal::<syn::Path>(inner, DERIVED_SHAPE) {
      Ok(source) => entries.push(DerivedEntry {
        name,
        source,
        field: None,
      }),
      Err(e) => errors.push(e),
    }
    return Ok(());
  }
  let mut source: Option<syn::Path> = None;
  let mut field: Option<syn::LitStr> = None;
  let walked = attribute::options(inner, |option| {
    if option.path.is_ident("type") {
      match value::parse_literal::<syn::Path>(&option, DERIVED_TYPE) {
        Ok(path) => set_once(
          &mut source,
          path,
          &option.path,
          "`type` is declared more than once in a reverse position — one option, one value",
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    if option.path.is_ident("field") {
      match value::literal(&option, DERIVED_FIELD) {
        Ok(named) => set_once(
          &mut field,
          named,
          &option.path,
          "`field` is declared more than once in a reverse position — one option, one value",
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    errors.push(attribute::unknown(
      &option,
      "unknown entry in a reverse position — it takes `type = \"…\"` and `field = \"…\"`",
      &["type", "field"],
    ));
    Ok(())
  });
  match source {
    Some(source) => entries.push(DerivedEntry {
      name,
      source,
      field,
    }),
    None => errors.push(syn::Error::new_spanned(&name, DERIVED_SHAPE)),
  }
  walked
}

/// ONE artifact position, in whichever of its two forms it was written.
///
/// [`derived_entry`]'s analogue and now its exact shape: the entry's NAME is the word this record
/// mints and the VALUE is the family, so the two ways of getting that backwards — writing a path on
/// the left, or a bare word where a type belongs — each earn a sentence naming which side is which.
///
/// # The FULL FORM, and what it is for
///
/// The form was refused by name until the round that un-refused it, on the ground that both of
/// `derived`'s options are answered here before they can be asked. That reasoning survives — `type`
/// and `field` are still refused, by [`LOCATE_SIBLINGS_WORDS`] — and what the form carries instead
/// is the one thing the shorthand has nowhere to put: the `data` ASK and the `required` SIGNATURE. A
/// GraphQL field's presence is decided by the expansion writing the `#[Object]` block, so the word
/// that puts a bytes field on the wire has to be written HERE, where the family's own `data` permits
/// it — and the word that says how either field is TYPED has to be written where the type is chosen,
/// which is the same place.
///
/// A repeat is refused and DROPPED rather than appended, exactly as a reverse position is: the first
/// declaration is what the rest of the pass reads.
fn locate_entry(
  inner: &syn::meta::ParseNestedMeta<'_>,
  entries: &mut Vec<LocateEntry>,
  errors: &mut Errors,
) -> syn::Result<()> {
  let Some(name) = inner.path.get_ident().cloned() else {
    // The entry's NAME is a word this record MINTS for the family, so there is no vocabulary.
    errors.push(attribute::unknown(inner, LOCATE_MINTS_ITS_OWN_WORD, &[]));
    return Ok(());
  };
  if entries.iter().any(|entry| entry.name == name) {
    errors.push(syn::Error::new_spanned(
      &name,
      format!("`{name}` is declared more than once in `locate(…)` — one position, one name"),
    ));
    attribute::skip_entry(inner);
    return Ok(());
  }
  // The shorthand: the value IS the family, and there is nothing else to read. A bare word carries
  // no value at all, and [`value::parse_literal`] answers that with the shape sentence too.
  if !attribute::has_block(inner) {
    match value::parse_literal::<syn::Path>(inner, LOCATE_SHAPE) {
      Ok(family) => entries.push(LocateEntry {
        name,
        family,
        data: None,
        required: false,
      }),
      Err(e) => errors.push(e),
    }
    return Ok(());
  }
  let mut family: Option<syn::Path> = None;
  let mut data: Option<LocateData> = None;
  let mut required = false;
  let walked = attribute::options(inner, |option| {
    if option.path.is_ident("family") {
      match value::parse_literal::<syn::Path>(&option, LOCATE_FAMILY) {
        Ok(path) => set_once(
          &mut family,
          path,
          &option.path,
          "`family` is declared more than once in an artifact position — one option, one value",
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    if option.path.is_ident("data") {
      return locate_data(&option, &mut data, errors);
    }
    // THE ADDRESS's `required`, read with the ask's exact spelling — see [`REQUIRED`]. Bare or
    // nothing, one per position, and the same two sentences the ask next door raises, because the
    // one word means one thing at both.
    if option.path.is_ident(REQUIRED) {
      if attribute::has_value(&option) || attribute::has_block(&option) {
        errors.push(named(&option, LOCATE_REQUIRED_IS_BARE.to_owned()));
        return Ok(());
      }
      if required {
        errors.push(syn::Error::new_spanned(
          &option.path,
          "`required` is declared more than once in an artifact position — the word is PRESENCE, \
           so the second one says exactly what the first already said",
        ));
      }
      required = true;
      attribute::skip_entry(&option);
      return Ok(());
    }
    // `derived`'s own two words, answered by name — see [`LOCATE_SIBLINGS_WORDS`]. Before the
    // near-miss line, because neither is a typo of anything this position takes and the sentence
    // that names them is the whole answer.
    if option.path.is_ident("type") || option.path.is_ident("field") {
      errors.push(named(&option, LOCATE_SIBLINGS_WORDS.to_owned()));
      return Ok(());
    }
    errors.push(attribute::unknown(&option, LOCATE_OPTIONS, &LOCATE_WORDS));
    Ok(())
  });
  match family {
    Some(family) => entries.push(LocateEntry {
      name,
      family,
      data,
      required,
    }),
    None => errors.push(syn::Error::new_spanned(&name, LOCATE_FAMILY_MISSING)),
  }
  walked
}

/// The `data` ASK inside one artifact position's full form — bare, or naming the wire field.
///
/// The marker-may-carry-a-value shape `ref` and `persist` already take, at the one position where
/// what the value names is a SCHEMA field rather than a Rust one: the literal is carried unread for
/// the string-kind schema-words law's reason, and what a client sees is exactly what was written.
fn locate_data(
  option: &syn::meta::ParseNestedMeta<'_>,
  data: &mut Option<LocateData>,
  errors: &mut Errors,
) -> syn::Result<()> {
  let at = option.path.clone();
  // THE BLOCK FORM — the one shape that carries more than a name. The extension word's template:
  // bare is the fact, `= "…"` is the fact plus its one obvious knob, and the block is the fact plus
  // knobs that need naming.
  if attribute::has_block(option) {
    let mut rename = None;
    let mut required = false;
    let walked = attribute::options(option, |inner| {
      if inner.path.is_ident("rename") {
        match value::literal(&inner, LOCATE_DATA_RENAME) {
          Ok(name) => set_once(
            &mut rename,
            name,
            &inner.path,
            "`rename` is declared more than once in a `data(…)` ask — one field, one name",
            errors,
          ),
          Err(e) => errors.push(e),
        }
        return Ok(());
      }
      if inner.path.is_ident(REQUIRED) {
        if attribute::has_value(&inner) || attribute::has_block(&inner) {
          errors.push(named(&inner, LOCATE_REQUIRED_IS_BARE.to_owned()));
          return Ok(());
        }
        if required {
          errors.push(syn::Error::new_spanned(
            &inner.path,
            "`required` is declared more than once in a `data(…)` ask — the word is PRESENCE, so \
             the second one says exactly what the first already said",
          ));
        }
        required = true;
        attribute::skip_entry(&inner);
        return Ok(());
      }
      errors.push(attribute::unknown(
        &inner,
        LOCATE_DATA_OPTIONS,
        &LOCATE_DATA_WORDS,
      ));
      Ok(())
    });
    set_once(
      data,
      LocateData {
        at,
        rename,
        required,
      },
      &option.path,
      "`data` is declared more than once in an artifact position — one ask, one field",
      errors,
    );
    return walked;
  }
  let rename = if attribute::has_value(option) {
    match value::literal(option, LOCATE_DATA_SHAPE) {
      Ok(name) => Some(name),
      Err(e) => {
        errors.push(e);
        return Ok(());
      }
    }
  } else {
    attribute::skip_entry(option);
    None
  };
  set_once(
    data,
    LocateData {
      at,
      rename,
      required: false,
    },
    &option.path,
    "`data` is declared more than once in an artifact position — one ask, one field",
    errors,
  );
  Ok(())
}

/// The refusal a reverse position's `type` gets when it is not a path.
const DERIVED_TYPE: &str = "`type` names the record that points back at this one, as a type path \
                            in a string literal";

/// The refusal a reverse position's `field` gets when it is not a string.
///
/// A STRING and never an ident: what it selects is a name on the SOURCE's declaration, which this
/// declaration cannot see — so there is nothing here for an ident to be checked against, and the
/// check is the audit the emission writes.
const DERIVED_FIELD: &str = "`field` names one of the source's `ref` fields, in a string literal";

/// WHY no storage face but this node's own is this node's — the ruling every one of these refusals
/// shares, so the reason cannot drift between them.
///
/// One node holds one storage, so a macro IS the storage declaration: a record's storage is its
/// rows, an aggregate's is the folded rows it keeps, an operator's is nothing at all, and each
/// derived index's is the engine its own macro names. An index over somebody's rows, or a family of
/// artifacts beside them, is a second storage and therefore a second node.
///
/// The ADVICE splits with the family, along the axis [`NodeKind::derives_its_key`] names. Told to a
/// node that mints an id, the sentence points at the index it should be subscribed to; told to a
/// node that already carries a borrowed key, it points at the sibling that would carry the same one.
/// One reader either way, because the LAW is one law and only its consequence differs.
///
/// The MATCH is here rather than on [`NodeKind`] because what varies is a clause of an English
/// sentence, and sentences are the front end's: the vocabulary answers what a node is CALLED, and
/// this answers what this refusal says about it. Exhaustive, so a kind added later cannot take an
/// answer by silence.
///
/// Shared with [`crate::index`], the other grammar in this family that has to say it.
pub(crate) fn owns_one_storage(kind: NodeKind) -> String {
  let held = match kind {
    NodeKind::Record => "its rows",
    // Rows, exactly as a record's are — a separate clause because it can afford to name the FOLD,
    // and an author who reached for a second storage is better served by *the rows are filled for
    // you* than by a word that leaves them wondering what fills them.
    NodeKind::Aggregate => "the folded rows it keeps",
    NodeKind::Operator | NodeKind::Entity => "none at all",
    NodeKind::Fulltext | NodeKind::Vector | NodeKind::Blob => "the one its own macro names",
  };
  let article = kind.article();
  let noun = kind.noun();
  let elsewhere = if kind.derives_its_key() {
    "A second storage over the same messages is a second node, subscribing to the same upstream."
      .to_owned()
  } else {
    format!(
      "The storage node subscribes to this {noun} and shares its key, which is why it carries no \
       `id` of its own."
    )
  };
  format!(
    "One node holds ONE storage, so the MACRO is the storage declaration and {article} {noun}'s \
     is {held}. {elsewhere}"
  )
}

/// The refusal when a name that reaches a `CREATE TABLE` is not a string.
const TABLE_VALUE: &str = "`table` must be the table's name, in a string literal";

/// One database's block inside the record's `persist(…)`.
///
/// A repeat is refused and DROPPED rather than appended: the first declaration is what the rest of
/// the pass reads, exactly as [`set_once`] keeps the first value of a repeated option.
fn record_database(
  inner: &syn::meta::ParseNestedMeta<'_>,
  kind: DatabaseKind,
  databases: &mut Vec<DatabaseBlock>,
  errors: &mut Errors,
) -> syn::Result<()> {
  let repeated = databases.iter().any(|block| block.kind == kind);
  if repeated {
    errors.push(syn::Error::new_spanned(
      &inner.path,
      format!(
        "`{kind}` is declared more than once — one block per database",
        kind = kind.as_str()
      ),
    ));
  }
  let mut block = DatabaseBlock {
    kind,
    uniques: Vec::new(),
    rename: None,
    comparison: None,
    table: None,
    schema: None,
    from: ConversionSpec::default(),
    into: ConversionSpec::default(),
    aliases: AliasOptions::default(),
  };
  let mut alias_seen = None;
  let scope = format!("`{}(…)`", kind.as_str());
  let walked = attribute::options(inner, |option| {
    if option.path.is_ident("alias") {
      return alias::block(
        &option,
        &mut block.aliases,
        &mut alias_seen,
        &scope,
        alias::Depth::Sized,
        errors,
      );
    }
    if option.path.is_ident("row") {
      return attribute::rename_block(&option, &mut block.rename, "row", errors);
    }
    if option.path.is_ident("comparison") {
      return attribute::rename_block(&option, &mut block.comparison, "comparison", errors);
    }
    // A bare `rename` MOVED rather than vanished: this block is about two emitted types now, and
    // the refusal says which block the option went into rather than calling it unknown.
    if option.path.is_ident("rename") {
      errors.push(named(
        &option,
        format!(
          "`{db}` emits a ROW and a COMPARISON, so a bare `rename` cannot say which — write \
             `row(rename = \"…\")` or `comparison(rename = \"…\")`",
          db = kind.as_str()
        ),
      ));
      return Ok(());
    }
    // Each family keeps its own word for the same thing, and the other one is refused by name.
    // `table` and `collection` are the SAME option, so the two share a slot.
    for (spelled, belongs) in [("table", true), ("collection", false)] {
      if option.path.is_ident(spelled) {
        if belongs != kind.is_sql() {
          let (theirs, ours) = if belongs {
            ("table", "collection")
          } else {
            ("collection", "table")
          };
          errors.push(named(
            &option,
            format!(
              "`{theirs}` is not `{db}`'s word — `{db}` names it `{ours} = \"…\"`",
              db = kind.as_str()
            ),
          ));
          return Ok(());
        }
        match value::literal(&option, TABLE_VALUE) {
          Ok(name) => set_once(
            &mut block.table,
            name,
            &option.path,
            &format!("`{spelled}` is declared more than once in {scope} — one option, one value"),
            errors,
          ),
          Err(e) => errors.push(e),
        }
        return Ok(());
      }
    }
    if option.path.is_ident("unique") {
      return composite_unique(&option, kind, &mut block.uniques, errors);
    }
    if option.path.is_ident("schema") {
      if !kind.is_sql() {
        errors.push(named(
          &option,
          format!(
            "`schema` is a SQL notion and `{db}` has none — it names its database and its \
               collection, and the collection is `collection = \"…\"`",
            db = kind.as_str()
          ),
        ));
        return Ok(());
      }
      match value::literal(
        &option,
        "`schema` must be the schema's name, in a string literal",
      ) {
        Ok(name) => set_once(
          &mut block.schema,
          name,
          &option.path,
          &format!("`schema` is declared more than once in {scope} — one option, one value"),
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    // The flat cell is GONE: it typed both directions at once, and the two are different impls with
    // different consumers. A cell rides its LEG now, under the word that leg is already written in.
    if option.path.is_ident("error") {
      errors.push(named(
        &option,
        format!(
          "`error` rides its LEG now — write `try_into(error = \"…\")` for the read or \
           `try_from(error = \"…\")` for the write, in {scope}. A row's read and its write are two \
           impls with two callers, so one cell over both said that either shares an error with the \
           other or that the shape had not been asked."
        ),
      ));
      return Ok(());
    }
    if conversion(
      &option,
      &mut block.from,
      &mut block.into,
      &scope,
      Cells::Admitted,
      errors,
    ) {
      return Ok(());
    }
    errors.push(column_option(
      &option,
      kind,
      &format!(
        "unknown entry in {scope} — a database block takes `rename = \"…\"`, `{name} = \"…\"`, \
           {schema}`alias(…)`{unique} and the row's own conversions, each of which may carry its \
           leg's `error = \"…\"`",
        name = if kind.is_sql() { "table" } else { "collection" },
        schema = if kind.is_sql() {
          "`schema = \"…\"`, "
        } else {
          ""
        },
        unique = if kind.is_sql() { ", `unique(…)`" } else { "" }
      ),
      // The sentence's own words, per dialect — `schema`, `unique` and the SQL spelling of the row's
      // name are offered only where the sentence offers them.
      &["rename", "alias", "from", "try_from", "into", "try_into"]
        .into_iter()
        .chain(if kind.is_sql() {
          vec!["table", "schema", "unique"]
        } else {
          vec!["collection"]
        })
        .collect::<Vec<_>>(),
    ));
    Ok(())
  });
  if !repeated {
    databases.push(block);
  }
  walked
}

/// `unique(a, b, …)` inside one database's block — ONE composite constraint, over the record's own
/// fields.
///
/// # It is the per-database road, and the field marker is the other one
///
/// `#[ingraph(sqlite(unique))]` on a FIELD is the every-declared-database shorthand for one column:
/// it says *this column's values are each held by at most one row* wherever the record is stored.
/// This word says the same thing about a TUPLE, and about ONE database — which is why it is written
/// in the database's own block rather than at the head. The two are told apart by SCOPE, so a
/// one-entry `unique(x)` is legal here and is not the marker's duplicate: it is the constraint the
/// marker cannot express, wanted on this backend alone.
///
/// Where they DO meet — the same one column by both roads — the emitter refuses the pair by name,
/// because both derive one constraint name and the second statement would create nothing. That
/// refusal is at the emitter rather than here: it has to see the column's per-database NAME, which a
/// `rename` may have moved, and this reader has only the field's ident.
///
/// # MONGO IS REFUSED BY NAME, and never by silence
///
/// A document database has no `CREATE UNIQUE INDEX` in this crate's emission — the mongo round
/// renders a collection and its indexes are not built here — so the word would be read, carried, and
/// then quietly dropped. A constraint an author WROTE and no schema enforces is the failure this
/// refusal exists to prevent, and it names the round rather than pretending the word is unknown.
fn composite_unique(
  option: &syn::meta::ParseNestedMeta<'_>,
  kind: DatabaseKind,
  uniques: &mut Vec<CompositeUniqueWord>,
  errors: &mut Errors,
) -> syn::Result<()> {
  if !kind.is_sql() {
    errors.push(named(
      option,
      format!(
        "`unique(…)` is a SQL constraint and `{db}` renders none — this crate's `{db}` emission \
         builds a collection and no index, so a constraint written here would be read and then \
         enforced by nothing. Declare it on the SQL databases this record names, or keep the \
         uniqueness where `{db}` can hold it: in the document's own `_id`.",
        db = kind.as_str()
      ),
    ));
    return Ok(());
  }
  // The three spellings of "declared" that `attribute::options` collapses are all WRONG here: a
  // constraint over no column is not a constraint, so `unique`, `unique()` and `unique = "…"` each
  // name a rule rather than a shorter legal form. `lineage(fields())`'s own guard, for its reason.
  if !attribute::has_block(option) || attribute::empty_group(option) {
    errors.push(named(
      option,
      "`unique(…)` must name at least one field — a constraint over no column constrains nothing, \
       and the statement it would render is not legal SQL. Write the fields it is over, in the \
       order the index should carry them: `unique(media, track, index)`."
        .to_owned(),
    ));
    return Ok(());
  }

  let at = option.path.clone();
  let mut entries: Vec<syn::Ident> = Vec::new();
  let walked = option.parse_nested_meta(|entry| {
    let Some(name) = entry.path.get_ident().cloned() else {
      // A path rather than a bare ident: recorded and the walk continues, so one pass reports every
      // offender — `lineage(fields(…))`'s own posture.
      errors.push(attribute::unknown(
        &entry,
        "`unique(…)` takes field idents",
        // The list names THIS record's own fields, which is not a vocabulary.
        &[],
      ));
      return Ok(());
    };
    if attribute::has_value(&entry) || attribute::has_block(&entry) {
      errors.push(attribute::named(
        &entry,
        format!(
          "`{name}` is one COLUMN of this constraint and takes nothing — a composite unique is a \
           list of fields and the ORDER is the only thing said about them"
        ),
      ));
      return Ok(());
    }
    // A field named TWICE in one constraint. Refused here rather than left to the engine: a
    // duplicate column in an index is a `CREATE` the dialect itself rejects, and the caret belongs
    // on the second spelling rather than in a driver's sentence at boot.
    if let Some(first) = entries.iter().find(|written| *written == &name) {
      errors.push(syn::Error::new_spanned(
        &entry.path,
        format!(
          "`{name}` is named twice in one `unique(…)` — a column appears once in an index, and a \
           constraint that repeated it would be the same constraint one column narrower"
        ),
      ));
      let _ = first;
      return Ok(());
    }
    entries.push(name);
    Ok(())
  });

  // Carried even where an entry was refused, so the emitter's own audits still run over what WAS
  // written — the standing this pass keeps everywhere: one declaration, every rule it broke.
  uniques.push(CompositeUniqueWord { entries, at });
  walked
}

/// One GraphQL backend's block inside the record's `graphql(…)`.
fn record_backend(
  inner: &syn::meta::ParseNestedMeta<'_>,
  kind: GraphqlKind,
  backends: &mut Vec<BackendBlock>,
  errors: &mut Errors,
) -> syn::Result<()> {
  let repeated = backends.iter().any(|block| block.kind == kind);
  if repeated {
    errors.push(syn::Error::new_spanned(
      &inner.path,
      format!(
        "`{kind}` is declared more than once in `graphql(…)` — one block per backend",
        kind = kind.as_str()
      ),
    ));
  }
  let mut block = BackendBlock {
    kind,
    rename: None,
    attrs: None,
  };
  let scope = format!("`{}(…)`", kind.as_str());
  let walked = attribute::options(inner, |option| {
    if option.path.is_ident("rename") {
      match rename(&option) {
        Ok(spelled) => set_once(
          &mut block.rename,
          spelled,
          &option.path,
          &format!("`rename` is declared more than once in {scope} — one option, one value"),
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    if option.path.is_ident("attrs") {
      match attribute::verbatim(&option) {
        Ok(tokens) => set_once(
          &mut block.attrs,
          tokens,
          &option.path,
          &format!("`attrs(…)` is declared more than once in {scope} — one list, one type"),
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    if let Some(error) = queryability(&option) {
      errors.push(error);
      return Ok(());
    }
    errors.push(wire_option(
      &option,
      &format!(
        "unknown entry in {scope} on a record — a backend block takes `rename = \"…\"` and \
           `attrs(…)`; `input_type` and `output_type` describe one FIELD"
      ),
      &["rename", "attrs"],
    ));
    Ok(())
  });
  if !repeated {
    backends.push(block);
  }
  walked
}

/// One SCHEMA POSITION of a field, as written: `input(…)` or `output(…)`.
///
/// A NAME, the attributes that ride on it, and — in the OUTPUT position — the RUST ident the emitted
/// object READS the field under. The type and the conversions left — the form because it is one per field,
/// the crossings because each has a row on one side of it and a row is one database's. Both are
/// refused here by name, pointing at the home they moved to.
#[derive(Default)]
struct FaceBlock {
  rename: Option<syn::LitStr>,
  /// `field = "…"` — the OUTPUT object's ACCESSOR for this field. `None` is the field's own name.
  ///
  /// OUTPUT-ONLY, and the input position refuses the word by name: what the input face's mangled
  /// name spells is a FILTER field, and moving that ident is what `rename` already does there.
  rust: Option<syn::Ident>,
  attrs: Option<proc_macro2::TokenStream>,
}

/// One position's entries — its NAME, the RUST ident the output object gives it, and its passthrough
/// attributes.
///
/// # The two rename axes are INDEPENDENT, and this block is where both are written
///
/// `rename = "…"` is the CLIENT-VISIBLE name and touches nothing in Rust. `field = "…"` is the
/// emitted OUTPUT object's ACCESSOR and touches nothing a client sees. Either may be written without
/// the other, and a field writing both has said two facts rather than one twice.
///
/// Neither reaches the MEMBER, which is the domain name and the substrate an emitted-to-emitted read
/// spends — see `ingraph-codegen`'s `model::GraphqlField::accessor` for the three layers whole.
///
/// `direction` is kept for the REFUSALS: the two spellings that used to live here are named rather
/// than swept into "unknown entry", and which pair a position took is what makes the sentence able
/// to point at the block they moved to.
fn face_block(
  inner: &syn::meta::ParseNestedMeta<'_>,
  slot: &mut Option<FaceBlock>,
  position: &str,
  direction: Direction,
  errors: &mut Errors,
) -> syn::Result<()> {
  if slot.is_some() {
    errors.push(syn::Error::new_spanned(
      &inner.path,
      format!("`{position}(…)` is declared more than once — one block per schema position"),
    ));
  }
  let mut block = FaceBlock::default();
  let scope = format!("`{position}(…)`");
  let walked = attribute::options(inner, |option| {
    if option.path.is_ident("rename") {
      match value::literal(&option, WIRE_NAME) {
        Ok(spelled) => set_once(
          &mut block.rename,
          spelled,
          &option.path,
          &format!("`rename` is declared more than once in {scope} — one option, one value"),
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    if option.path.is_ident("field") {
      // OUTPUT-ONLY, and refused by name in the other position rather than swept into "unknown
      // entry": what the input face names is a FILTER field, whose Rust ident is the mangling of the
      // schema name `rename` already moves — so a second word for it would be two spellings of one
      // knob.
      if position != "output" {
        errors.push(named(&option, FIELD_IS_THE_OUTPUTS.to_owned()));
        return Ok(());
      }
      // The RAW-IDENT tolerance: the accessor this names is built from one of somebody's struct
      // fields, and a Rust keyword is an ordinary schema name for one — so `field = "type"` and
      // `field = "r#type"` are the same field. Both failures answer with the same sentence, exactly
      // as they did before the tolerance landed.
      match value::literal(&option, OUTPUT_FIELD)
        .and_then(|literal| value::named_field(&literal, OUTPUT_FIELD))
      {
        Ok(member) => set_once(
          &mut block.rust,
          member,
          &option.path,
          &format!("`field` is declared more than once in {scope} — one member, one name"),
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    // `type` MOVED to the field's own `graphql(…)`: a position's type used to be its own, which made
    // an input form differing from its output form spellable — a schema a client has to read twice.
    if option.path.is_ident("type") {
      errors.push(named(
        &option,
        "`type` moved to the field's own block — write `graphql(type = \"…\")`. The wire form is \
         ONE: the operand a client filters with and the value it receives back are the same thing, \
         and neither may vary with a deployment's storage backend."
          .to_owned(),
      ));
      return Ok(());
    }
    if option.path.is_ident("attrs") {
      match attribute::verbatim(&option) {
        Ok(tokens) => set_once(
          &mut block.attrs,
          tokens,
          &option.path,
          &format!("`attrs(…)` is declared more than once in {scope} — one list, one field"),
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    // Only ONE direction belongs in each position, and the other is refused by name — the verb
    // rule is what makes "which one" answerable without a table to look up.
    let wrong = if direction.plain == "into" {
      [("from", "try_from")]
    } else {
      [("into", "try_into")]
    };
    for (plain, fallible) in wrong {
      if option.path.is_ident(plain) || option.path.is_ident(fallible) {
        return {
          errors.push(named(
            &option,
            format!(
              "`{position}(…)` takes `{}`/`{}` — `from` BUILDS the projection its block is \
                 about and `into` LEAVES it, so an `input` is written with `into` and an `output` \
                 with `from`",
              direction.plain, direction.fallible
            ),
          ));
          Ok(())
        };
      }
    }
    // The CONVERSIONS moved with it, and one axis further: a wire crossing has a ROW on one side of
    // it, so it is per DATABASE. What stood here was anchored on the DOMAIN, which is the value the
    // process happens to hold rather than the one the database will answer with.
    for spelling in [direction.plain, direction.fallible] {
      if option.path.is_ident(spelling) {
        errors.push(named(
          &option,
          format!(
            "`{spelling}` moved out of `{position}(…)` and gained a DATABASE — write \
             `graphql({home}({db}({spelling} = \"…\")))`. A crossing has a row on one side, and a \
             row is one database's; what stood here crossed from the DOMAIN, which is not what a \
             deployment will answer with.",
            db = "<db>",
            home = if direction.plain == "from" {
              "output"
            } else {
              "input(comparison"
            },
          ),
        ));
        return Ok(());
      }
    }
    if let Some(error) = queryability(&option) {
      errors.push(error);
      return Ok(());
    }
    errors.push(wire_option(
      &option,
      &format!(
        "unknown entry in {scope} — a schema position takes `rename = \"…\"`, `attrs(…)` and — in \
           `output(…)` — `field = \"…\"`; the wire FORM is the field's own `type = \"…\"` and its \
           crossings are per database"
      ),
      // `field` is the OUTPUT position's alone, and the sentence says so — the input face is
      // offered two words rather than three.
      &if position == "output" {
        vec!["rename", "attrs", "field"]
      } else {
        vec!["rename", "attrs"]
      },
    ));
    Ok(())
  });
  if slot.is_none() {
    *slot = Some(block);
  }
  walked
}

/// The refusal `field = "…"` gets when its value is not an identifier.
///
/// An IDENT, where `rename`'s value is a plain string: what this names is the ACCESSOR the emitted
/// output object reads this field through — a Rust method name, built from it by suffix — and no
/// mangling can stand in for one. The member grammar an interface writes its own renames in says the
/// same thing at the same word.
const OUTPUT_FIELD: &str = "`field` must be the name the output object reads this field under, as an identifier in a string \
   literal";

/// The refusal `field = "…"` gets in the INPUT position.
const FIELD_IS_THE_OUTPUTS: &str = "`field` names the OUTPUT object's accessor for a field — write \
                                    it in `output(…)`. The input face names a FILTER field, whose \
                                    Rust spelling is the mangling of the schema name `rename` \
                                    already moves, so there is no second ident here to name.";

/// One backend's block inside a FIELD's `graphql(…)`.
fn field_backend(
  inner: &syn::meta::ParseNestedMeta<'_>,
  kind: GraphqlKind,
  per_backend: &mut Vec<FieldBackend>,
  errors: &mut Errors,
) -> syn::Result<()> {
  let repeated = per_backend.iter().any(|block| block.kind == kind);
  if repeated {
    errors.push(syn::Error::new_spanned(
      &inner.path,
      format!(
        "`{kind}` is declared more than once in `graphql(…)` on this field — one block per backend",
        kind = kind.as_str()
      ),
    ));
  }
  let mut block = FieldBackend {
    kind,
    at: inner.path.clone(),
    input: None,
    output: None,
    skip: None,
  };
  let scope = format!("`{}(…)` on this field", kind.as_str());
  let walked = attribute::options(inner, |option| {
    if option.path.is_ident("input") {
      return face_block(&option, &mut block.input, "input", LEAVES, errors);
    }
    if option.path.is_ident("output") {
      return face_block(&option, &mut block.output, "output", BUILDS, errors);
    }
    // THIS backend's own absence — the common word one scope in, and bare for its reason.
    if option.path.is_ident("skip") {
      if attribute::has_value(&option) || attribute::has_block(&option) {
        errors.push(attribute::named(&option, WIRE_SKIP_IS_BARE.to_owned()));
        return Ok(());
      }
      attribute::skip_entry(&option);
      set_once(
        &mut block.skip,
        option.path.clone(),
        &option.path,
        &format!("`skip` is declared more than once in {scope} — one word, one backend"),
        errors,
      );
      return Ok(());
    }
    if let Some(error) = queryability(&option) {
      errors.push(error);
      return Ok(());
    }
    errors.push(wire_option(
      &option,
      &format!(
        "unknown entry in {scope} — a field's backend block takes `skip`, `input(…)` and \
           `output(…)`, the last two being two SCHEMA POSITIONS that may differ in name, type and \
           attributes"
      ),
      &["skip", "input", "output"],
    ));
    Ok(())
  });
  if !repeated {
    per_backend.push(block);
  }
  walked
}

/// An entry the wire grammar does not take, named wherever the name is one a reader plausibly
/// meant somewhere else.
///
/// `vocabulary` is the CALLER's, for [`misplaced`]'s reason: five wire scopes share this helper.
fn wire_option(
  option: &syn::meta::ParseNestedMeta<'_>,
  takes: &str,
  vocabulary: &[&str],
) -> syn::Error {
  if let Some(error) = queryability(option) {
    return error;
  }
  if option.path.is_ident("desc") || option.path.is_ident("description") {
    return named(
      option,
      "a description is passed through verbatim — write `attrs(desc = \"…\")` in the backend's \
       block. A source `///` comment is deliberately NOT published: what reaches a schema is what a \
       declaration says reaches it."
        .to_owned(),
    );
  }
  attribute::unknown(option, takes, vocabulary)
}

/// The four conversion spellings, wherever a block takes them. `true` when the entry was one.
///
/// # A leg has TWO shapes, and the escape lives INSIDE the one that can fail
///
/// `try_into = "positive"` is the short form and `try_into(fn = "positive", error_with = "wrap")`
/// the structured one. The escape nests inside its leg rather than sitting beside it, and the reason
/// is an axis a sibling entry loses: one block may carry `try_from` AND `try_into`, so an
/// `error_with` written next to them could not say which it maps. Nested, a cross-leg reference is
/// UNSPELLABLE — there is no place to write one.
///
/// A PLAIN leg takes the short form only. An infallible function has no error, so a structured form
/// over one either carries an escape with nothing to map or restates the short form in more words,
/// and both are refused by name.
pub(crate) fn conversion(
  option: &syn::meta::ParseNestedMeta<'_>,
  from: &mut ConversionSpec,
  into: &mut ConversionSpec,
  scope: &str,
  cells: Cells,
  errors: &mut Errors,
) -> bool {
  for (spelled, fallible, reads, direction) in [
    ("from", false, true, BUILDS),
    ("try_from", true, true, BUILDS),
    ("into", false, false, LEAVES),
    ("try_into", true, false, LEAVES),
  ] {
    if option.path.is_ident(spelled) {
      let slot = if reads { &mut *from } else { &mut *into };
      let admits = fallible && matches!(cells, Cells::Admitted);
      let (named, cell) = leg(option, spelled, fallible, admits, scope, errors);
      if let Some(path) = cell {
        set_once(
          &mut slot.cell,
          path,
          &option.path,
          &format!("`error` is declared more than once in `{spelled}(…)` — one leg, one type"),
          errors,
        );
      }
      if let Some(named) = named {
        slot.set(fallible, named, scope, direction, errors);
      }
      return true;
    }
  }
  false
}

/// Whether the block being walked admits an ERROR CELL inside its fallible legs.
///
/// A RECORD-level block does — the cell types the impls that crossing's legs produce there. A
/// FIELD's block does not: a field declares the CONVERSION and, where `From` cannot hold, its
/// escape; what the resulting refusal is CALLED is one answer for the whole record, so it is said
/// once at the record and never per field.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Cells {
  /// The record level: `try_into(error = "…")` is read.
  Admitted,
  /// A field: `error` inside a leg is an unknown entry, and the message says where it lives.
  Elsewhere,
}

/// ONE leg, in whichever of its two shapes was written — the conversion it names, and the error
/// cell where the block admits one.
///
/// # The leg block is the WHOLE of what one direction says
///
/// `fn` is the conversion, `error_with` maps its error where `From` cannot, and `error` names the
/// type the impls of this leg answer with. Which of the three a given block admits is the block's
/// level rather than a per-entry rule: a field writes the first two, a record the third, and both
/// write them INSIDE the leg word — so the record-level shape is the field's read one level up, and
/// a cross-leg reference stays unspellable at either.
///
/// At the record level `fn` becomes OPTIONAL, because a cell with no container conversion beside it
/// is an ordinary thing to declare: the columns carry the conversions and the record carries the
/// name of what they refuse with.
fn leg(
  option: &syn::meta::ParseNestedMeta<'_>,
  spelled: &str,
  fallible: bool,
  cell_admitted: bool,
  scope: &str,
  errors: &mut Errors,
) -> (Option<Named>, Option<syn::Path>) {
  let at = option.path.clone();
  if !attribute::has_block(option) {
    return match value::parse_literal::<syn::Path>(
      option,
      &format!(
        "`{spelled}` must be a path to a function, in a string literal — or the structured form \
         `{spelled}(…)`, which carries the conversion beside whatever else this block says about \
         the leg"
      ),
    ) {
      Ok(path) => (
        Some(Named {
          path,
          escape: None,
          at,
        }),
        None,
      ),
      Err(e) => {
        errors.push(e);
        (None, None)
      }
    };
  }
  if !fallible {
    errors.push(attribute::unknown(
      option,
      &format!(
        "`{spelled}` takes a function and nothing else — an INFALLIBLE leg cannot fail, so it has \
         no error to map and none to name, and the structured form would only restate \
         `{spelled} = \"…\"` in more words"
      ),
      // The LEG word was spelled right and written the wrong shape.
      &[],
    ));
    return (None, None);
  }
  let (mut function, mut escape, mut cell) = (None, None, None);
  let walked = attribute::options(option, |inner| {
    for (entry, slot) in [("fn", &mut function), ("error_with", &mut escape)] {
      if inner.path.is_ident(entry) {
        match value::parse_literal::<syn::Path>(
          &inner,
          &format!("`{entry}` must be a path to a function, in a string literal"),
        ) {
          Ok(path) => set_once(
            slot,
            path,
            &inner.path,
            &format!(
              "`{entry}` is declared more than once in `{spelled}(…)` — one option, one value"
            ),
            errors,
          ),
          Err(e) => errors.push(e),
        }
        return Ok(());
      }
    }
    if inner.path.is_ident("error") {
      if !cell_admitted {
        errors.push(named(
          &inner,
          format!(
            "a leg's `error` is the RECORD's — write it at `{spelled}(error = \"…\")` in the \
             record's own block for this crossing. What a refusal is CALLED is one answer for the \
             whole record; a field says how one column crosses, and where its function's error \
             cannot be absorbed, `error_with` maps it."
          ),
        ));
        return Ok(());
      }
      match value::parse_literal::<syn::Path>(
        &inner,
        "`error` must be a path to the type this leg's fallible impls answer with, in a string \
         literal",
      ) {
        Ok(path) => set_once(
          &mut cell,
          path,
          &inner.path,
          &format!("`error` is declared more than once in `{spelled}(…)` — one leg, one type"),
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    errors.push(attribute::unknown(
      &inner,
      &format!(
        "unknown entry in `{spelled}(…)` in {scope} — a leg takes `fn = \"…\"`, which is the \
         conversion, `error_with = \"…\"`, which maps that function's error{cell}",
        cell = if cell_admitted {
          ", and `error = \"…\"`, which names the type this leg's impls answer with"
        } else {
          ""
        }
      ),
      &if cell_admitted {
        vec!["fn", "error_with", "error"]
      } else {
        vec!["fn", "error_with"]
      },
    ));
    Ok(())
  });
  if let Err(e) = walked {
    errors.push(e);
  }
  if escape.is_some() && function.is_none() {
    errors.push(syn::Error::new_spanned(
      &at,
      format!(
        "`{spelled}(…)` maps an error and names no function — `error_with` is what a CONVERSION's \
         error is carried through, so there is nothing here for it to map"
      ),
    ));
    return (None, cell);
  }
  let Some(path) = function else {
    if !cell_admitted {
      errors.push(syn::Error::new_spanned(
        &at,
        format!(
          "`{spelled}(…)` names no function — the structured form exists to carry `error_with` \
           BESIDE the conversion, so `fn = \"…\"` is what it is about and is not optional"
        ),
      ));
    }
    return (None, cell);
  };
  (Some(Named { path, escape, at }), cell)
}

/// An entry a RECORD's database block does not take because it describes a COLUMN.
fn column_option(
  option: &syn::meta::ParseNestedMeta<'_>,
  kind: DatabaseKind,
  takes: &str,
  vocabulary: &[&str],
) -> syn::Error {
  for name in ["indexed", "unique", "copy", "edge", "type"] {
    if option.path.is_ident(name) {
      return named(
        option,
        format!(
          "`{name}` describes one COLUMN, and this block describes the whole row — write it on the \
           field, as `#[ingraph({db}({name}))]`",
          db = kind.as_str()
        ),
      );
    }
  }
  if let Some(name) = NULLABILITY.iter().find(|name| option.path.is_ident(name)) {
    return named(
      option,
      format!(
        "`{name}` is not an option — a column's nullability follows the `optional` MARKER on the \
         field and is not overridable"
      ),
    );
  }
  attribute::unknown(option, takes, vocabulary)
}

/// **THE ADDRESS BLOCK** — `key(rename = "Address", input(rename = "AddressIn"),
/// output(rename = "AddressM"))`.
///
/// # Why this block outgrew the plain rename its two neighbours still take
///
/// GraphQL keeps input and output types in ONE namespace, so an address has to publish two names:
/// the object a client READS and the object it SENDS when the whole address is more than an id.
/// Until the 2026-08-16 rename ruling there was one seat for both, and the sending half was composed
/// off the reading half with an `Input` suffix — a derivation that is predictable and was blessed as
/// the ONE composition in this grammar, but that leaves a declaration unable to name the argument at
/// all. The ruling separated them: the base still re-bases whatever no member overrides, and each
/// face now has a seat of its own.
///
/// `filter` and `order_by` are untouched because each publishes exactly one type, so a second word
/// there would name nothing.
///
/// # Three seats, two kinds
///
/// `rename` is an IDENT: it names the Rust type this record lands in the declaring scope, and the
/// schema's default follows it. `input` and `output` are STRINGS naming types in GraphQL's flat
/// namespace, where a Rust keyword is an ordinary word — the 2026-08-13 ruling, and the same fence
/// `connection(…)` and `edge(…)` take. Neither member moves a Rust name, which is the axis law: the
/// argument object's Rust name has never had a knob and is not being given one here.
fn key_block(
  inner: &syn::meta::ParseNestedMeta<'_>,
  base: &mut Option<syn::Ident>,
  object: &mut Option<syn::LitStr>,
  argument: &mut Option<syn::LitStr>,
  errors: &mut Errors,
) -> syn::Result<()> {
  if !attribute::has_block(inner) || attribute::empty_group(inner) {
    errors.push(attribute::unknown(
      inner,
      "`key(…)` names the ADDRESS — `rename = \"…\"` re-bases both of its faces, and \
       `output(rename = \"…\")` and `input(rename = \"…\")` name the schema's reading half and its \
       sending half outright. A block with none of them says nothing",
      // The block's own name was written correctly; what is missing is its contents, so there is no
      // word here for a near miss to be near.
      &[],
    ));
    return Ok(());
  }
  attribute::options(inner, |option| {
    if option.path.is_ident("rename") {
      // The SHARED reader and the SHARED sentence, both spelled as `attribute::rename_block` spells
      // them: this seat left that block because it grew two members, and nothing about the base's
      // own refusals changed with it.
      match value::parse_literal::<syn::Ident>(&option, attribute::TYPE_NAME) {
        Ok(spelled) => set_once(
          base,
          spelled,
          &option.path,
          "`rename` is declared more than once in `key(…)` — one option, one value",
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    for (what, slot) in [("output", &mut *object), ("input", &mut *argument)] {
      if option.path.is_ident(what) {
        let walked = attribute::sdl_name_block(&option, slot, what, errors);
        if let Some(name) = slot.as_ref() {
          wire::refuse_invalid_name(&name.value(), name, errors);
        }
        return walked;
      }
    }
    errors.push(attribute::unknown(
      &option,
      "unknown entry in `key(…)` — it takes `rename = \"…\"`, the BASE both of the address's faces \
       are built on, and one block per face: `output(rename = \"…\")` is the object a client reads \
       an address back in, `input(rename = \"…\")` the object it sends one in. A face named outright \
       is carried verbatim; a face left unnamed takes the base, and the sending half takes it with \
       `Input` on the end",
      &["rename", "output", "input"],
    ));
    Ok(())
  })
}

/// `rename = "Name"` — the record grammar's one ident-valued option.
fn rename(meta: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<syn::Ident> {
  value::parse_literal(
    meta,
    "`rename` must be a valid identifier, in a string literal",
  )
}

/// A field's own `#[ingraph(…)]` markers. Both are flags, and one attribute may carry both.
///
/// Each is kept as the marker's own PATH rather than a `bool`, for two reasons: it is the span a
/// refusal about that marker reports at, and an already-filled slot is what makes a repeat
/// detectable. A marker says one thing about one field, so declaring it twice is ambiguous exactly
/// as a repeated record-level option is, and refused the same way.
#[derive(Default)]
struct Markers {
  /// `id` — this field is the record's identity.
  id: Option<syn::Path>,
  /// `copy` — this column's type is cheap enough to hand back by value.
  copy: Option<syn::Path>,
  /// `repeated` — hand this column out as a slice, through `Repeated`.
  repeated: Option<syn::Path>,
  /// `optional` — hand this column out as `Option<&T>`, through `Optional`.
  optional: Option<syn::Path>,
  /// `key(rename = "…")` — what this field's column is called in the KEY type.
  key: Option<Rename>,
  /// `lineage(rename = "…")` — what it is called in the LINEAGE type.
  ///
  /// Separate from [`Markers::key`] on purpose. The same field reaches two emitted types as two
  /// columns, and those become two different tables' columns, which may legitimately differ.
  lineage: Option<Rename>,
  /// The field's STORAGE words — how this field's column is rendered, and in which databases.
  ///
  /// They used to live inside a `persist(…)` wrapper, and the wrapper retired the day the field seat
  /// inverted: the container declares the databases, a bare field is a column in every one of them,
  /// and what is left for a field to say is a REFINEMENT. So the words sit where the container's own
  /// storage words sit — at the top level of the attribute, bare — and the wrapper that used to hold
  /// them says nothing a reader can act on. One idiom, one level count.
  ///
  /// An empty [`FieldStorage`] means *this column is rendered as its type is* rather than *this field
  /// is not a column*. [`Markers::skip`] is what says the second, and it is the only word that does.
  storage: FieldStorage,
  /// `builder(…)` — which seat of the construction protocol this column fills.
  ///
  /// A block rather than bare words beside `copy` and `optional`, and [`crate::construct`] carries
  /// why: three of its words already mean something else in a neighbouring scope of this grammar.
  build: Option<Build>,
  /// `skip` / `skip(default = "…")` — this field is DELIBERATELY not a column, in any database.
  ///
  /// ONE seat and no per-database twin: a record is one storage shape across every database it
  /// declares. Where two stores want different columns, the difference is the GRAPH's — a second
  /// record subscribing to the same upstream.
  skip: Option<SkipField>,
  /// `graphql` / `graphql(…)` — this field is EXPOSED on the wire.
  ///
  /// It cannot stand alone: a wire field with no stored source cannot be populated by a read, so
  /// the marker requires a stored COLUMN on the same field. It used to require the `persist` marker
  /// beside it and now requires only that the field not be absent — the two were one condition
  /// while participation was a marker, and the rule reads [`stored_in`] either way, which is why it
  /// did not have to move when the marker did.
  graphql: Option<WireField>,
  /// Whether an entry naming this field's LABEL was written and refused.
  ///
  /// The guard of the two label rules that survive, so one mistake gets one sentence: a field
  /// writing `map(…)`, the spelling the word replaces, or a value no label reader can take, has
  /// said what its kind is and been answered — telling it a second time that it declared none names
  /// nothing new.
  label_refused: bool,
  /// The field's LABEL — the family its type is read under, fully nested.
  ///
  /// At the TOP level rather than inside a face block, because it is a fact about the field's KIND
  /// and not about one face of it: `bytes` and `list` on a `Vec<u8>` are a blob column and an edge
  /// table, so the word feeds storage as surely as it feeds the filter.
  label: Option<Written>,
  /// `ref = "…"` / `ref(type = "…")` — the record this field REFERS to.
  ///
  /// A second WORD beside the family label rather than a family of its own, because the two say
  /// different things about one column: the label is the interpretation the value is read under,
  /// and this is the record the value addresses. A key-side field carries this and no label at all.
  ///
  /// The TARGET rather than the entry, unlike every marker above: those keep their own path because
  /// it is the span a refusal about them reports at, and this one has no refusal of its own to
  /// report — what a relation gets wrong is checked by the compiler, at the equation the emission
  /// writes.
  reference: Option<syn::Path>,
}

/// A field's STORAGE words: the column it becomes, and each database's refinements of it.
///
/// Every word here is written BARE on the field, at the same level the container writes its own
/// storage words at. The dialect-free ones (`rename`, `sortable`, `flatten`) speak to every database
/// the field participates in; a `<db>(…)` block speaks to one.
#[derive(Default)]
struct FieldStorage {
  /// `rename = "…"` — the column's name in every database that does not override it.
  rename: Option<syn::LitStr>,
  /// The `rename` word's own path, kept beside the literal it carried.
  ///
  /// The literal's span reports what the NAME is wrong about; this reports what the WORD is wrong
  /// beside — the contradiction with `skip`, which is about the word and not the name it chose.
  rename_at: Option<syn::Path>,
  /// `sortable` — this COLLECTION's order is kept in an order-preserving companion column.
  ///
  /// A DIALECT-FREE word beside the per-database blocks — see [`SORTABLE`] — kept as the word's own
  /// path for the reason every other marker keeps one: it is the span a refusal about the word
  /// reports at, and an already-filled slot is what makes a repeat detectable.
  sortable: Option<syn::Path>,
  /// `indexed` — this COLLECTION's elements take the VALUE-LED access path.
  ///
  /// A DIALECT-FREE word beside the per-database blocks — see [`INDEXED`] — and kept as the word's
  /// own path for [`FieldStorage::sortable`]'s reason. It is a DIFFERENT slot from the `indexed` a
  /// [`FieldDatabase`] carries, which is one column's index in one database: two seats, two
  /// questions, and the refusals on both sides name each other.
  indexed: Option<syn::Path>,
  /// `flatten` — this field's own name is dropped in every participating database that HAS a prefix
  /// to drop, so its type's columns join the holder's namespace.
  ///
  /// The dialect-free spelling of a word each database's own block also takes. What a given dialect
  /// does with it is DERIVED rather than declared, exactly as [`FieldStorage::sortable`]'s is: a SQL
  /// dialect drops the segment, and a document database has no prefix there to drop, so it mints
  /// nothing. Written at ONE database that has no columns the word is a concrete mistake and
  /// [`field_database`] still refuses it by name.
  flatten: Option<syn::Path>,
  /// The per-database blocks, in the order they were written.
  per_db: Vec<FieldDatabase>,
}

impl FieldStorage {
  /// The span a refusal about this field's storage reports at — the first word it wrote, and
  /// `None` where it wrote none.
  ///
  /// The question a rowless tier asks — *did this field describe a column* — and the one the
  /// contradiction with `skip` asks. Both want the WORDS and not the participation, which every data
  /// field has by default and no word grants.
  fn at(&self) -> Option<&syn::Path> {
    self
      .rename_at
      .as_ref()
      .or(self.sortable.as_ref())
      .or(self.indexed.as_ref())
      .or(self.flatten.as_ref())
      .or_else(|| self.per_db.first().map(|per| &per.at))
  }

  /// The PRESENCE LIST — the databases named BARE on this field.
  ///
  /// A bare `<db>` restricts: it says *only these*. A `<db>(…)` carrying words configures that
  /// database and restricts nothing, which is the reading the wrapper era already had — a block
  /// refines a column rather than selecting one — kept whole now that the block is the field's own.
  fn presence(&self) -> impl Iterator<Item = &FieldDatabase> {
    self.per_db.iter().filter(|per| per.bare)
  }

  /// Whether this field is a COLUMN of `kind`, given the databases the container declared.
  ///
  /// # The MASK, computed rather than declared
  ///
  /// Under the inversion a field is a column of every database the container named, and only a word
  /// takes one away. Two spellings do, and they are one claim read from its two ends: a bare `<db>`
  /// list keeps the databases it NAMES, and a `<db>(skip[(…)])` block drops the one it names. A
  /// field that wrote neither participates everywhere, which is the inversion's own answer and the
  /// one this returns for the whole existing corpus.
  ///
  /// `declared` is the container's list, so a bare `<db>` naming a database the container never
  /// declared narrows nothing — that word has its own refusal, and one mistake earns one sentence.
  fn participates(&self, kind: DatabaseKind, declared: &[DatabaseKind]) -> bool {
    let narrowed = self.presence().any(|per| declared.contains(&per.kind));
    if narrowed && !self.presence().any(|per| per.kind == kind) {
      return false;
    }
    !self
      .per_db
      .iter()
      .any(|per| per.kind == kind && per.skip.is_some())
  }

  /// What a read of `kind`'s row SUPPLIES for this field, where the field is not a column of it.
  ///
  /// [`None`] where the absence named no fill — which is a REFUSAL rather than a default, see
  /// [`refuse_an_unfilled_absence`]. The full absence keeps its own floor: `skip` at the field says
  /// the value is nowhere and `Default::default()` answers for it, because one absence stated once
  /// reads the same way out of every store. A PARTIAL one cannot borrow that floor — the value would
  /// round-trip out of one database and be invented out of the next, with nothing written down
  /// saying so.
  fn fill_at(&self, kind: DatabaseKind) -> Option<&SkipField> {
    self
      .per_db
      .iter()
      .find(|per| per.kind == kind)
      .and_then(|per| per.skip.as_ref())
      .filter(|skip| skip.default.is_some())
  }
}

/// The `skip` word, in either of its two spellings — the bare marker and `skip(default = "…")`.
///
/// # The word is the DECLARED absence, and the fill is what makes it one
///
/// A field that simply carries no `persist` marker reaches no row either, and what it leaves behind
/// is a PARTIAL row: nothing can rebuild the record from it, so the whole SQL query face goes with
/// it. The word says the absence was meant and names what a read supplies instead, which is the one
/// fact silence cannot carry.
pub(crate) struct SkipField {
  /// The word's own path — the span the hydration obligation lands at, and the span every refusal
  /// about the word reports at.
  pub(crate) at: syn::Path,
  /// `default = "path::to::fn"` — the named filler, or [`None`] for `Default::default()`.
  ///
  /// A `syn::Path` rather than the literal that carried it: what the emission spells is a CALL, and
  /// the literal's own span is spent at the parse where a string that is not a path is refused.
  pub(crate) default: Option<syn::Path>,
}

impl SkipField {
  /// The word as the model carries it — the WORD'S OWN SPAN and whatever fill it named.
  ///
  /// The span travels because the obligation does: a skipped column with no `Default` is `E0277`,
  /// and the token the author can act on is the word that skipped it.
  pub(crate) fn fill(&self) -> Fill {
    use syn::spanned::Spanned as _;

    Fill {
      at: self.at.span(),
      named: self.default.clone(),
    }
  }
}

/// One database's block on a field — how THAT database stores this column.
pub(crate) struct FieldDatabase {
  pub(crate) kind: DatabaseKind,
  /// The database's own token — the span a refusal about this column-in-this-database reports at.
  pub(crate) at: syn::Path,
  /// Whether the word was written BARE — `#[ingraph(sqlite)]` rather than `#[ingraph(sqlite(…))]`.
  ///
  /// The bare form is the PRESENCE claim: under the inversion a field is a column of every database
  /// the container declared, and naming some of them narrows that to the ones named. A block with
  /// words in it configures the database it names and narrows nothing — see [`FieldStorage::presence`].
  pub(crate) bare: bool,
  /// `rename = "…"` — the column's name in this database alone.
  pub(crate) rename: Option<syn::LitStr>,
  /// `indexed`.
  pub(crate) indexed: Option<syn::Path>,
  /// `unique` — a SECOND-INDEX identity, distinct from the record's own `id`: the column's values
  /// are each held by at most one row, and the constraint is this database's own to enforce.
  ///
  /// The spelling stays legal beside `indexed` on the SAME field — an author who writes both has
  /// stated two intents, `indexed` for the seek and `unique` for the constraint — and `ingraph`'s
  /// schema lane satisfies both with the ONE statement a unique index already is: a plain index
  /// over a column already carrying a unique one would be a redundant write amplifier, so it is the
  /// plain half that never renders.
  pub(crate) unique: Option<syn::Path>,
  /// `copy` — the STORED type is `Copy`, which the domain field's own marker cannot imply.
  pub(crate) copy: Option<syn::Path>,
  /// `edge` — this COLLECTION is kept in a second table here rather than in a column of the row.
  ///
  /// Postgres's word and no other database's: it is the one dialect with two usable strategies, and
  /// [`field_database`] refuses the word everywhere else.
  pub(crate) edge: Option<syn::Path>,
  /// `flatten` — this field's own name is DROPPED, so its type's columns join the holder's namespace.
  ///
  /// A SQL word and no document database's: mongo's default IS the nested structure, so there is no
  /// prefix there to drop, and [`field_database`] refuses `mongo(flatten)` by name.
  pub(crate) flatten: Option<syn::Path>,
  /// `skip(default = "…")` — this field is NO COLUMN of this database, and what a read supplies.
  ///
  /// # The partial absence, and why the fill is not optional here
  ///
  /// The field seat's own `skip` says the value is a column of NO database, and its bare spelling
  /// falls back to `Default::default()`: one absence, stated once, read the same way out of every
  /// store. This one says the value is a column of SOME of them — so the same declaration
  /// round-trips out of one database and is invented out of the next, and which value the second
  /// hands back is a fact only the declaration can carry. A bare `<db>(skip)` is therefore a named
  /// refusal asking for the fill rather than an absence with an implied one.
  ///
  /// [`None`] is the ordinary case: this database stores the column, whatever else the block says
  /// about how.
  pub(crate) skip: Option<SkipField>,
  /// `type = "…"` — what this database stores, when it is not the domain type.
  pub(crate) stored: Option<syn::Type>,
  /// Stored → domain.
  pub(crate) from: ConversionSpec,
  /// Domain → stored.
  pub(crate) into: ConversionSpec,
}

impl FieldDatabase {
  /// Whether the block carried a word that RENDERS the column — as against a bare presence claim,
  /// an absence, or a block whose every entry earned a refusal of its own.
  ///
  /// The fragment tier asks it: a per-dialect rendering is what its one dialect-free segment list
  /// has nowhere to put, and a block that configured NOTHING has already been answered by whatever
  /// refused the word inside it. Two sentences about one mistake is what this question prevents.
  ///
  /// [`skip`](Self::skip) is deliberately not counted. It describes no column — it says there is
  /// none here — so it is a participation claim rather than a rendering, and the seat that answers a
  /// rendering is not the seat that answers an absence.
  pub(crate) fn configured(&self) -> bool {
    self.rename.is_some()
      || self.indexed.is_some()
      || self.unique.is_some()
      || self.copy.is_some()
      || self.edge.is_some()
      || self.stored.is_some()
      || self.from.written()
      || self.into.written()
  }
}

/// A scoped rename, with the block it was written in.
struct Rename {
  /// The name the column takes in that scope.
  name: syn::Ident,
  /// The scope's own path — the span a refusal about this rename reports at.
  at: syn::Path,
}

impl Markers {
  /// The one projection these markers ask for.
  ///
  /// The three are mutually exclusive: `repeated` and `optional` are two different projections of
  /// one column, and `copy` hands the column back BY VALUE, which is the opposite of what either
  /// exists for. A combination is refused rather than ordered by precedence, so no reader has to
  /// remember which would have won.
  fn projection(&self, field: &syn::Ident, errors: &mut Errors) -> Projection {
    let declared: Vec<(&str, &syn::Path)> = [
      ("copy", self.copy.as_ref()),
      ("repeated", self.repeated.as_ref()),
      ("optional", self.optional.as_ref()),
    ]
    .into_iter()
    .filter_map(|(name, path)| path.map(|path| (name, path)))
    .collect();

    column::projection(&declared, field, errors)
  }

  /// The relation this field declares, with the projection its referring value is reached by.
  ///
  /// The DECLARATION decides the projection, never the field's spelled type — the rule the whole
  /// marker layer already runs on, for the reason it states: a macro holds tokens, and
  /// `type MaybeCover = Option<Uuid7>` is the case that proves a spelling cannot be trusted.
  ///
  /// THREE words put the referring value inside the field's type, and they are one rule three
  /// times: a collection LABEL says the value is an element, `repeated` says the column is
  /// many-valued, and `optional` says it may be absent. A field declaring none of them carries the
  /// value itself.
  ///
  /// One projection at most, whichever of the three was written — the words say where the value is,
  /// and they cannot disagree about it. `repeated` and `optional` are already refused together, and
  /// a collection label beside either is the same statement twice: a collection has no null state,
  /// so an `Option` around one declares the collection, which is the ruling `Label::collection`
  /// already carries applied one layer over.
  fn reference(&self) -> Option<Reference> {
    let held = self.label.as_ref().is_some_and(Written::collection)
      || self.repeated.is_some()
      || self.optional.is_some();
    self.reference.as_ref().map(|target| Reference {
      target: target.clone(),
      through: if held { Through::Held } else { Through::Value },
    })
  }
}

/// The refusal a `skip(default = …)` naming something other than a path gets.
const SKIP_DEFAULT: &str = "`default` names the FUNCTION that fills a skipped column — a \
                            `fn() -> T`, as a path in a string literal, which is serde's own \
                            `default = \"…\"` spelling";

/// The `skip` word, read in either spelling: the bare marker, and `skip(default = "path::to::fn")`.
///
/// ONE reader for both seats, so the word means the same thing at the top level and inside a
/// database's block — a difference between them would be a difference nobody declared.
///
/// # Errors
/// Whatever the nested walk hit. An entry the word does not take is RECORDED and the walk
/// continues, so one declaration reports every offender.
pub(crate) fn skip_word(
  meta: &syn::meta::ParseNestedMeta<'_>,
  scope: &str,
  errors: &mut Errors,
) -> syn::Result<SkipField> {
  let mut declared = SkipField {
    at: meta.path.clone(),
    default: None,
  };
  attribute::options(meta, |option| {
    if option.path.is_ident("default") {
      match value::parse_literal::<syn::Path>(&option, SKIP_DEFAULT) {
        Ok(path) => set_once(
          &mut declared.default,
          path,
          &option.path,
          &format!(
            "`default` is declared more than once in `skip(…)` {scope} — one option, one value"
          ),
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    errors.push(attribute::unknown(
      &option,
      &format!(
        "unknown entry in `skip(…)` {scope} — the word takes `default = \"path::to::fn\"` and \
         nothing else: a skipped column has no stored value, so what a read needs told is the \
         function that supplies one. Written bare, the fill is `Default::default()`."
      ),
      &["default"],
    ));
    Ok(())
  })?;
  Ok(declared)
}

fn field_markers(attrs: &[syn::Attribute], node: NodeKind, errors: &mut Errors) -> Markers {
  let mut markers = Markers::default();
  attribute::walk(attrs, errors, |meta, errors| {
    // Repeats are caught WITHIN one attribute and ACROSS several, because the slots outlive the
    // walk.
    if meta.path.is_ident("id") {
      set_once(
        &mut markers.id,
        meta.path.clone(),
        &meta.path,
        "`id` is declared more than once on this field — one marker, one field",
        errors,
      );
      return Ok(());
    }
    for marker in ["copy", "repeated", "optional"] {
      if meta.path.is_ident(marker) {
        let slot = match marker {
          "copy" => &mut markers.copy,
          "repeated" => &mut markers.repeated,
          _ => &mut markers.optional,
        };
        set_once(
          slot,
          meta.path.clone(),
          &meta.path,
          &format!("`{marker}` is declared more than once on this field — one marker, one field"),
          errors,
        );
        return Ok(());
      }
    }
    // The field level mirrors the record level: one block per emitted type, options inside. Here
    // the block names the field's COLUMN in that type, where the record level named the type.
    for scope in ["key", "lineage"] {
      if meta.path.is_ident(scope) {
        let block = meta.path.clone();
        let slot = if scope == "key" {
          &mut markers.key
        } else {
          &mut markers.lineage
        };
        return meta.parse_nested_meta(|inner| {
          if inner.path.is_ident("rename") {
            match rename(&inner) {
              Ok(name) => set_once(
                slot,
                Rename {
                  name,
                  at: block.clone(),
                },
                &inner.path,
                &format!(
                  "`rename` is declared more than once in `{scope}(…)` on this field — one \
                   option, one value"
                ),
                errors,
              ),
              Err(e) => errors.push(e),
            }
            return Ok(());
          }
          errors.push(attribute::unknown(
            &inner,
            &format!("unknown entry in `{scope}(…)` — it takes `rename = \"…\"`"),
            &["rename"],
          ));
          Ok(())
        });
      }
    }
    // THE CONSTRUCTION SEAT — which call of the wrapped type's protocol this column reaches.
    // BEFORE the bare `skip` on purpose: `builder(skip)` and `skip` are two different absences —
    // one is *no column in any database* and the other is *a column that is not handed back* — and
    // reading the block first is what keeps the pair legible where a field writes both.
    if meta.path.is_ident(crate::construct::WORD) {
      return crate::construct::field(&meta, &mut markers.build, errors);
    }
    // The SKIP word, in the seat that names every database at once. A marker that may also be a
    // block: the bare word is the whole statement, and the block says how the absence is filled.
    if meta.path.is_ident("skip") {
      let at = meta.path.clone();
      let declared = skip_word(&meta, "on this field", errors)?;
      set_once(
        &mut markers.skip,
        declared,
        &at,
        "`skip` is declared more than once on this field — one word, one field",
        errors,
      );
      return Ok(());
    }
    // `persist` IS RETIRED at this seat, and the refusal is where the migration is taught. The word
    // held two halves — the field's participation, and the refinement of the column it became — and
    // the inversion took the first: a record IS rows, and its data fields ARE the row. What was left
    // was a wrapper around the second half alone, holding a vocabulary that reads exactly like the
    // container's own storage words one level in. So the wrapper goes and the words come up to meet
    // them. One idiom, one level count.
    if meta.path.is_ident("persist") {
      attribute::skip_entry(&meta);
      errors.push(named(
        &meta,
        format!(
          "`persist` is retired at a field — a bare field is already a column in every database the \
           declaration names, so there is nothing left for a wrapper to grant. What it held goes on \
           the field itself, where the head writes its own store words: NARROW with a database's \
           bare word (`#[ingraph({db})]`), CONFIGURE with its block (`#[ingraph({db}(rename = \
           \"…\", type = \"…\", indexed))]`), and write what every database shares bare beside \
           them (`rename = \"…\"`, `sortable`, `indexed`, `flatten`). The absence is still `skip`.",
          db = DatabaseKind::Sqlite.as_str(),
        ),
      ));
      return Ok(());
    }
    // ONE DATABASE'S BLOCK, at the field's own level — bare to narrow the field to that database,
    // with words in it to say how that database renders the column.
    if let Some(kind) = database_kind(&meta.path) {
      return field_database(&meta, kind, &mut markers.storage.per_db, errors);
    }
    // ONE INTENT FOR EVERY DATABASE, so it is written where nothing scopes it. What each database
    // does with it is derived rather than declared: `mirrors` joins the word to that database's
    // storage form, so a native-array dialect mints nothing and an edge-storing one mints the
    // companion, off the same written word.
    if meta.path.is_ident(SORTABLE) {
      if attribute::has_value(&meta) || attribute::has_block(&meta) {
        errors.push(attribute::named(&meta, BARE_WORD.to_owned()));
        return Ok(());
      }
      attribute::skip_entry(&meta);
      set_once(
        &mut markers.storage.sortable,
        meta.path.clone(),
        &meta.path,
        SORTABLE_ONCE,
        errors,
      );
      return Ok(());
    }
    // THE OTHER ONE-INTENT-PER-COLLECTION WORD, read exactly beside it. `seeks_by_value` joins this
    // to a database's storage form the way `mirrors` joins `sortable`'s: a dialect keeping the
    // collection in a second table gets a second index over it, and one keeping it in an array
    // column gets the access method its own catalogue names.
    //
    // It is read HERE and never falls through to the unknown-entry list, which is what stops the
    // per-database sentence — `indexed` is one of `PER_DATABASE` — from answering a word this seat
    // now takes. The scalar case still reaches a redirect, and a sharper one: see
    // `refuse_a_storage_word_no_label_can_order`.
    if meta.path.is_ident(INDEXED) {
      if attribute::has_value(&meta) || attribute::has_block(&meta) {
        errors.push(attribute::named(&meta, BARE_WORD.to_owned()));
        return Ok(());
      }
      attribute::skip_entry(&meta);
      set_once(
        &mut markers.storage.indexed,
        meta.path.clone(),
        &meta.path,
        INDEXED_ONCE,
        errors,
      );
      return Ok(());
    }
    // THE COLUMN THE WRITE COMPUTES, at the seat whose column lists are PER DATABASE. Read as a
    // WORD rather than left to the unknown-entry list, and answered with the measurement that says
    // where its teeth are — see [`DERIVED_COLUMN_AT_A_RECORD`].
    if meta.path.is_ident(DERIVED_COLUMN) {
      attribute::skip_entry(&meta);
      errors.push(attribute::named(
        &meta,
        DERIVED_COLUMN_AT_A_RECORD.to_owned(),
      ));
      return Ok(());
    }
    // THE TWO TRANSFORM WORDS, read at this saddle so the answer is the seat's rule rather than an
    // unknown entry — see [`TRANSFORM_AT_A_RECORD`], which names the two seats a record already
    // spells them with.
    if meta.path.is_ident(WRITE_TRANSFORM) || meta.path.is_ident(READ_TRANSFORM) {
      attribute::skip_entry(&meta);
      errors.push(attribute::named(&meta, TRANSFORM_AT_A_RECORD.to_owned()));
      return Ok(());
    }
    // THE DIALECT-FREE `flatten`, beside `sortable` and read the same way: it speaks to every
    // database the field participates in, and each one answers with what it has. A SQL dialect drops
    // the segment; a document database has no prefix there to drop and mints nothing. Written at ONE
    // database that has no columns it is a concrete mistake, and `field_database` refuses it there
    // by name.
    if meta.path.is_ident("flatten") {
      if attribute::has_value(&meta) || attribute::has_block(&meta) {
        errors.push(attribute::named(&meta, FLATTEN_IS_BARE.to_owned()));
        return Ok(());
      }
      attribute::skip_entry(&meta);
      set_once(
        &mut markers.storage.flatten,
        meta.path.clone(),
        &meta.path,
        "`flatten` is declared more than once on this field — one word, one layout",
        errors,
      );
      return Ok(());
    }
    // An embedding is content for an index that is a node of its own now, so the marker travels with
    // the node rather than being refused as a word nobody recognises.
    if meta.path.is_ident("vector") {
      errors.push(named(
        &meta,
        format!(
          "`vector` marks a field as an embedding, and an embedding index is its OWN node, so the \
           marker is that node's declaration: write the field under the `vector` macro, on a type \
           whose `upstream(…)` names this {noun}. {law} The field's own column stays here, where \
           `persist` puts it.",
          noun = node.noun(),
          law = owns_one_storage(node),
        ),
      ));
      return Ok(());
    }
    // A payload is content for an artifact family that is a node of its own now, and the marker
    // travels with it. `bytes` is the neighbouring word and a different thing entirely — a COLUMN of
    // this record's row — so the refusal names it, because that is the mistake worth catching here.
    if meta.path.is_ident("blob") {
      errors.push(named(
        &meta,
        format!(
          "`blob` marks a field as an artifact's payload, and an artifact family is its OWN node, so \
           the marker is that node's declaration: write the field under the `blob` macro, on a type \
           whose `upstream(…)` names this {noun}. {law} A `Vec<u8>` COLUMN is a different thing and \
           stays: write `bytes` beside `persist`, and the bytes are a value in this {noun}'s own \
           row.",
          noun = node.noun(),
          law = owns_one_storage(node),
        ),
      ));
      return Ok(());
    }
    // Every spelling reaches ONE arm — the bare word, the block and the `= "…"` value — because what
    // the block and the value carried was the CONVERSION, and a conversion describes how a field
    // enters an index that is a node of its own. So the marker travels with the node rather than
    // being refused three ways for three shapes.
    if meta.path.is_ident("fulltext") {
      errors.push(named(
        &meta,
        format!(
          "`fulltext` marks a field for an index that is its OWN node, so the marker — and the \
           per-engine conversion its block carried — belong to that node's declaration: write the \
           field under the `fulltext` macro, on a type whose `upstream(…)` names this {noun}. {law} \
           The field's own column stays here, where `persist` puts it.",
          noun = node.noun(),
          law = owns_one_storage(node),
        ),
      ));
      return Ok(());
    }
    if meta.path.is_ident("graphql") {
      // A BARE `graphql` SAYS NOTHING NOW. The word was the wire face's participation marker, and
      // the container declares participation: a record naming a backend publishes every column it
      // has. What is left for a field is the REFINING half — the name, the form, the crossings and
      // the absence — and every one of those is written inside the block.
      if !attribute::has_block(&meta) || attribute::empty_group(&meta) {
        attribute::skip_entry(&meta);
        errors.push(named(
          &meta,
          "`graphql` alone says nothing now — a declaration naming a wire backend publishes every \
           column it has, so the word that put a field on the face is the DEFAULT. Delete it. \
           `graphql(…)` stays for what it always also did: name the field on the wire \
           (`rename = \"…\"`), pin its form (`type = \"…\"`), carry its crossings \
           (`output(…)`, `input(comparison(…))`) and WITHHOLD it (`skip`, or one backend's own \
           `async_graphql(skip)`)."
            .to_owned(),
        ));
        return Ok(());
      }
      let at = meta.path.clone();
      let mut refused = false;
      let mut declared = WireField {
        at: at.clone(),
        rename: None,
        ty: None,
        output: Vec::new(),
        comparison: Vec::new(),
        skip: None,
        per_backend: Vec::new(),
      };
      let walked = attribute::options(&meta, |inner| {
        if let Some(kind) = graphql_kind(&inner.path) {
          return field_backend(&inner, kind, &mut declared.per_backend, errors);
        }
        // The WIRE SKIP, in the seat that names every backend at once. BARE: what the storage word's
        // block carries is a FILL, and a field the wire never publishes has nothing to fill.
        if inner.path.is_ident("skip") {
          if attribute::has_value(&inner) || attribute::has_block(&inner) {
            errors.push(attribute::named(&inner, WIRE_SKIP_IS_BARE.to_owned()));
            return Ok(());
          }
          attribute::skip_entry(&inner);
          set_once(
            &mut declared.skip,
            inner.path.clone(),
            &inner.path,
            "`skip` is declared more than once in `graphql(…)` on this field — one word, one field",
            errors,
          );
          return Ok(());
        }
        // The ONE wire form, here rather than in a position block: a schema whose input and output
        // spelled one field two ways is a schema a client reads twice, and a schema that varied
        // with a deployment's storage backend is one no client could hold against two deployments.
        if inner.path.is_ident("type") {
          match value::parse_literal::<syn::Type>(
            &inner,
            "`type` must be the form this field takes ON THE WIRE, in a string literal",
          ) {
            Ok(ty) => set_once(
              &mut declared.ty,
              ty,
              &inner.path,
              "`type` is declared more than once in `graphql(…)` on this field — one field, one \
                 wire form",
              errors,
            ),
            Err(e) => errors.push(e),
          }
          return Ok(());
        }
        if inner.path.is_ident("output") {
          return wire_legs(
            &inner,
            &mut declared.output,
            "graphql(output(…))",
            BUILDS,
            errors,
          );
        }
        if inner.path.is_ident("input") {
          return attribute::options(&inner, |position| {
            if position.path.is_ident("comparison") {
              return wire_legs(
                &position,
                &mut declared.comparison,
                "graphql(input(comparison(…)))",
                LEAVES,
                errors,
              );
            }
            // The two the input half does NOT admit, each refused with the reason rather than as an
            // unknown name: what a conversion needs is an OPERAND, and neither of these carries one.
            if position.path.is_ident("orderby") || position.path.is_ident("order_by") {
              errors.push(named(
                &position,
                "an order carries a COLUMN and a DIRECTION and never a value — its lowering is a \
                 variant partition emitted from the tier declarations, so a per-field conversion \
                 here would have no reader"
                  .to_owned(),
              ));
              return Ok(());
            }
            if position.path.is_ident("pagination") || position.path.is_ident("page") {
              errors.push(named(
                &position,
                "a cursor is an opaque round trip of the ENGINE's own: its values speak `persist`'s \
                 vocabulary and never take the wire form, so there is nothing here for a conversion \
                 to cross"
                  .to_owned(),
              ));
              return Ok(());
            }
            errors.push(attribute::unknown(
              &position,
              "unknown entry in `input(…)` on a field — the input half has ONE crossing that \
                 carries a value, and it is `comparison(…)`",
              &["comparison"],
            ));
            Ok(())
          });
        }
        if inner.path.is_ident("marker") {
          let message = marker_is_the_older_spelling(&inner);
          // The OLDER SPELLING, matched exactly and answered with the migration.
          errors.push(attribute::unknown(&inner, &message, &[]));
          refused = true;
          return Ok(());
        }
        if inner.path.is_ident("rename") {
          match value::literal(&inner, WIRE_NAME) {
            Ok(spelled) => set_once(
              &mut declared.rename,
              spelled,
              &inner.path,
              "`rename` is declared more than once in `graphql(…)` on this field — one option, \
                 one value",
              errors,
            ),
            Err(e) => errors.push(e),
          }
          return Ok(());
        }
        errors.push(wire_option(
          &inner,
          "unknown entry in `graphql(…)` on a field — it takes `skip`, `rename = \"…\"`, \
             `type = \"…\"`, `output(<db>(…))`, `input(comparison(<db>(…)))` and one block per \
             backend (`async_graphql`)",
          &["skip", "rename", "type", "output", "input"]
            .into_iter()
            .chain(GraphqlKind::ALL.map(GraphqlKind::as_str))
            .collect::<Vec<_>>(),
        ));
        Ok(())
      });
      markers.label_refused |= refused;
      set_once(
        &mut markers.graphql,
        declared,
        &at,
        "`graphql` is declared more than once on this field — one marker, one field",
        errors,
      );
      return walked;
    }
    // `ref` is a MARKER that may also be a block, exactly as `persist` is — `ref = "…"` names the
    // target and `ref(…)` names it beside whatever a relation later needs. One entry, so a repeat
    // of either spelling is one refusal.
    if meta.path.is_ident(REFERS) {
      let at = meta.path.clone();
      let target = if attribute::has_value(&meta) {
        value::parse_literal::<syn::Path>(&meta, REF_SHAPE)
      } else {
        reference_block(&meta, errors)
      };
      match target {
        Ok(target) => set_once(
          &mut markers.reference,
          target,
          &at,
          "`ref` is declared more than once on this field — one column addresses one record",
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    // A BARE `rename` MEANS "EVERYWHERE", and everywhere is the ROW: the field seat's bare axis is
    // storage, exactly as the container's is. Every other thing a field can rename already wears the
    // scope that fixes it — `key(rename)`, `lineage(rename)`, `graphql(rename)`, `<db>(rename)` —
    // so the unscoped word has one referent left and names it.
    if meta.path.is_ident("rename") {
      match value::literal(&meta, COLUMN_VALUE) {
        Ok(name) => {
          set_once(
            &mut markers.storage.rename,
            name,
            &meta.path,
            "`rename` is declared more than once on this field — one option, one value",
            errors,
          );
          markers
            .storage
            .rename_at
            .get_or_insert_with(|| meta.path.clone());
        }
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    // LAST among the recognised entries, so a word this grammar reserves or ships is read as the
    // label it is and everything else still reaches the sentence below. None of the field's markers
    // shares a name with a label word, so the order costs nothing but says which reading wins.
    if begins_a_label(&meta.path) {
      let at = meta.path.clone();
      match label(&meta, errors) {
        Some(declared) => set_once(&mut markers.label, declared, &at, ONE_LABEL, errors),
        None => markers.label_refused = true,
      }
      return Ok(());
    }
    // THE AGGREGATE's two role words at a FIELD, refused by name for the head's reason one grain in.
    // Read LAST among the named entries and before the label reader has already run, so a word this
    // grammar owns still wins — neither of these is a label word, so the position costs nothing.
    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, node, crate::aggregate::Written::OnAField),
        ));
        return Ok(());
      }
    }

    errors.push(misplaced(
      &meta,
      &format!(
        "unknown `ingraph` field attribute — a field takes `id`, `copy`, `repeated`, `optional`, \
         `skip`, `graphql`, `ref`, `key(…)`, `lineage(…)` and `builder(…)`; its STORAGE words \
         (`rename = \"…\"`, `sortable`, `indexed`, `flatten`, and one block per database — \
         {stores}); and its \
         LABEL: {list}, a collection's element inside it (`list(string)`), or \
         `label = \"a::marker::Path\"`",
        stores = shipped(DatabaseKind::ALL.into_iter().map(DatabaseKind::as_str)),
        list = shipped(Label::ALL.into_iter().map(Label::as_str)),
      ),
      &[
        "id",
        "copy",
        "repeated",
        "optional",
        "rename",
        SORTABLE,
        INDEXED,
        "flatten",
        "skip",
        DERIVED_COLUMN,
        WRITE_TRANSFORM,
        READ_TRANSFORM,
        "graphql",
        REFERS,
        "key",
        "lineage",
        crate::construct::WORD,
      ]
      .into_iter()
      .chain(DatabaseKind::ALL.map(DatabaseKind::as_str))
      .chain(label_words())
      .collect::<Vec<_>>(),
    ));
    Ok(())
  });
  // The one construction rule that reads TWO of this field's words, and therefore cannot be checked
  // inside the walk: `option` is a sentence about a column with an empty state, and `optional` is
  // what declares one — whichever order they were written in.
  crate::construct::refuse_a_whole_non_option(
    markers.optional.is_some(),
    markers.build.as_ref(),
    errors,
  );
  markers
}

/// A field's `ref(…)` in its FULL form — the block carrying the target, and whatever a relation
/// needs beside one later.
///
/// The bare `ref`, and a `ref()` naming nothing, reach the SAME refusal as an unreadable path: all
/// three are a relation with no record to relate to, and the sentence that answers shows both forms.
///
/// # Errors
/// [`REF_SHAPE`] when the block names no target. An entry the block does not take is recorded and
/// the walk continues, so one declaration reports every offender.
fn reference_block(
  meta: &syn::meta::ParseNestedMeta<'_>,
  errors: &mut Errors,
) -> syn::Result<syn::Path> {
  let mut target: Option<syn::Path> = None;
  attribute::options(meta, |option| {
    if option.path.is_ident("type") {
      match value::parse_literal::<syn::Path>(&option, REF_TYPE) {
        Ok(path) => set_once(
          &mut target,
          path,
          &option.path,
          "`type` is declared more than once in `ref(…)` — one option, one value",
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    errors.push(attribute::unknown(
      &option,
      "unknown entry in `ref(…)` — it takes `type = \"…\"`",
      &["type"],
    ));
    Ok(())
  })?;
  target.ok_or_else(|| syn::Error::new_spanned(&meta.path, REF_SHAPE))
}

/// The refusal when a wire field's name is not a string.
const WIRE_NAME: &str = "a wire field's `rename` must be its name in the schema, in a string \
                         literal";

/// The refusal a `graphql(skip)` written with a value or a block gets.
///
/// The two `skip` words differ in exactly this, and the difference is not arbitrary: the STORAGE
/// word's block names what fills the column a read cannot find, and a field the wire never publishes
/// has no read to fill.
const WIRE_SKIP_IS_BARE: &str = "`skip` on the wire is a BARE word — it takes no `default`, because \
                                 a fill is what a READ needs when a column is not there and a field \
                                 the wire never publishes is never read. The fill belongs to the \
                                 storage word: `#[ingraph(skip(default = \"…\"))]`.";

/// The refusal when a column's name is not a string. A STRING and not a Rust identifier, because
/// `type` and `bitRate` are ordinary column names — the field carrying one is mangled rather than
/// refused.
const COLUMN_VALUE: &str = "a column's `rename` must be its name, in a string literal";

/// The refusal a `flatten` written with a value or a block gets. It is a layout, not a name.
const FLATTEN_IS_BARE: &str = "`flatten` is a BARE word — it drops this field's own name from the \
                               columns its type renders, and there is nothing for a value to say \
                               about that. One database's own is `#[ingraph(sqlite(flatten))]`.";

/// One database's block on a field — bare to narrow, with words in it to configure.
pub(crate) fn field_database(
  inner: &syn::meta::ParseNestedMeta<'_>,
  kind: DatabaseKind,
  per_db: &mut Vec<FieldDatabase>,
  errors: &mut Errors,
) -> syn::Result<()> {
  let repeated = per_db.iter().any(|block| block.kind == kind);
  if repeated {
    errors.push(syn::Error::new_spanned(
      &inner.path,
      format!(
        "`{kind}` is declared more than once on this field — one block per database",
        kind = kind.as_str()
      ),
    ));
  }
  // A word carrying a value is neither spelling: `sqlite = "…"` is not the narrowing and not the
  // block, so it is answered before either is assumed.
  if attribute::has_value(inner) {
    errors.push(attribute::named(
      inner,
      format!(
        "`{kind}` names a DATABASE and takes no value — write it bare to narrow this field to that \
         database, or as a block to say how it stores the column: `#[ingraph({kind}(rename = \
         \"…\"))]`",
        kind = kind.as_str()
      ),
    ));
    return Ok(());
  }
  let bare = !attribute::has_block(inner) || attribute::empty_group(inner);
  let mut block = FieldDatabase {
    kind,
    at: inner.path.clone(),
    bare,
    rename: None,
    indexed: None,
    unique: None,
    copy: None,
    edge: None,
    flatten: None,
    skip: None,
    stored: None,
    from: ConversionSpec::default(),
    into: ConversionSpec::default(),
  };
  let scope = format!("`{}(…)` on this field", kind.as_str());
  let walked = attribute::options(inner, |option| {
    if option.path.is_ident("flatten") {
      // Mongo's exclusion is STRUCTURAL — its default IS the nested subdocument, so there is no
      // prefix to drop — and the refusal is by name rather than as an unknown entry, because the
      // word is a real one written at the one database it means nothing at.
      if !kind.is_sql() {
        errors.push(named(
          &option,
          format!(
            "`flatten` drops a field's name so its type's COLUMNS join the holder's, and `{db}` has \
             no columns — its default is the nested subdocument already. Lifting an embedded \
             document's keys into its holder is a different thing and is not spelled here.",
            db = kind.as_str()
          ),
        ));
        return Ok(());
      }
      set_once(
        &mut block.flatten,
        option.path.clone(),
        &option.path,
        &format!("`flatten` is declared more than once in {scope} — one marker, one layout"),
        errors,
      );
      return Ok(());
    }
    if option.path.is_ident("edge") {
      if let Some(instead) = no_strategy_to_choose(kind) {
        errors.push(named(
          &option,
          format!(
            "`edge` names a storage STRATEGY and `{db}` has none to choose — {instead}. The word \
             is Postgres's alone, that being the one dialect with two usable strategies",
            db = kind.as_str()
          ),
        ));
        return Ok(());
      }
      set_once(
        &mut block.edge,
        option.path.clone(),
        &option.path,
        &format!("`edge` is declared more than once in {scope} — one word, one column"),
        errors,
      );
      return Ok(());
    }
    for spelled in ["indexed", "unique", "copy"] {
      if option.path.is_ident(spelled) {
        let slot = match spelled {
          "indexed" => &mut block.indexed,
          "unique" => &mut block.unique,
          _ => &mut block.copy,
        };
        set_once(
          slot,
          option.path.clone(),
          &option.path,
          &format!("`{spelled}` is declared more than once in {scope} — one marker, one column"),
          errors,
        );
        return Ok(());
      }
    }
    if option.path.is_ident("rename") {
      match value::literal(&option, COLUMN_VALUE) {
        Ok(name) => set_once(
          &mut block.rename,
          name,
          &option.path,
          &format!("`rename` is declared more than once in {scope} — one option, one value"),
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    if option.path.is_ident("type") {
      match value::parse_literal::<syn::Type>(
        &option,
        "`type` must be the type this database stores, in a string literal",
      ) {
        Ok(stored) => set_once(
          &mut block.stored,
          stored,
          &option.path,
          &format!("`type` is declared more than once in {scope} — one option, one value"),
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    // THE PARTIAL ABSENCE — this field is a column of the other databases and not of this one, and
    // the fill is what a read of this one hands back instead. Read by the FIELD's own `skip` reader,
    // so the word means the same thing at both scopes and its `default` is spelled once.
    //
    // The fill is REQUIRED here where the field seat's bare `skip` implies `Default::default()`, and
    // the asymmetry is the whole of what a partial absence is: one declaration that round-trips out
    // of one store and is invented out of the next has to say what the next hands back, because
    // nothing else in the declaration can say it. See [`FieldDatabase::skip`].
    if option.path.is_ident("skip") {
      let at = option.path.clone();
      let declared = skip_word(&option, &scope, errors)?;
      if declared.default.is_none() {
        errors.push(named(
          &option,
          format!(
            "`{db}(skip)` says this field is a column of the OTHER databases and not of `{db}`, and \
             a read of a `{db}` row has to hand something back — write \
             `#[ingraph({db}(skip(default = \"…\")))]`, naming the `fn() -> T` that supplies it. \
             The bare word's `Default::default()` floor is the FIELD's own `#[ingraph(skip)]`, \
             which is the absence stated once and read the same way out of every store; a partial \
             one is read two ways, and which value the second store hands back is a fact only this \
             declaration carries.",
            db = kind.as_str()
          ),
        ));
        return Ok(());
      }
      set_once(
        &mut block.skip,
        declared,
        &at,
        &format!("`skip` is declared more than once in {scope} — one word, one database"),
        errors,
      );
      return Ok(());
    }
    if conversion(
      &option,
      &mut block.from,
      &mut block.into,
      &scope,
      Cells::Elsewhere,
      errors,
    ) {
      return Ok(());
    }
    // A nested block here is a SEGMENT of a held value being spoken about — nothing else in this
    // block takes one — so it is refused as the wait it is rather than as a word nobody knows. The
    // container it belongs in is named, because that is where such an override is spelled the day
    // one can be.
    if attribute::has_block(&option) && !attribute::empty_group(&option) {
      let segment = option
        .path
        .get_ident()
        .map_or_else(|| "that".to_owned(), ToString::to_string);
      errors.push(named(
        &option,
        format!(
          "`{segment}(…)` names a SEGMENT of a held value, and a per-segment override has not \
           arrived — see `flatten`, whose container is where one is written. What decides a held \
           value's columns here today is one word: laid out under this field's name by default, or \
           under the held type's own names with `flatten`"
        ),
      ));
      return Ok(());
    }
    errors.push(row_option(
      &option,
      kind,
      &format!(
        "unknown entry in {scope} — a column's database block takes `rename = \"…\"`, \
           `indexed`, `unique`, `copy`, `flatten`, `type = \"…\"` and its conversions, plus \
           `skip(default = \"…\")` for a column this database alone does not carry; Postgres also \
           takes `edge`"
      ),
      &[
        "rename", "indexed", "unique", "copy", "flatten", "skip", "type", "edge", "from",
        "try_from", "into", "try_into",
      ],
    ));
    Ok(())
  });
  if !repeated {
    per_db.push(block);
  }
  walked
}

/// An entry a COLUMN's database block does not take because it describes the whole row.
fn row_option(
  option: &syn::meta::ParseNestedMeta<'_>,
  kind: DatabaseKind,
  takes: &str,
  vocabulary: &[&str],
) -> syn::Error {
  for name in ["table", "collection", "schema"] {
    if option.path.is_ident(name) {
      return named(
        option,
        format!(
          "`{name}` names where the whole ROW lives, and this block describes one column — write \
           it on the record, as `#[ingraph::record({db}({name} = \"…\"))]`",
          db = kind.as_str()
        ),
      );
    }
  }
  if let Some(name) = NULLABILITY.iter().find(|name| option.path.is_ident(name)) {
    return named(
      option,
      format!(
        "`{name}` is not an option — a column's nullability follows the `optional` MARKER on the \
         field and is not overridable: `#[ingraph(optional)]` is nullable and a field without it is \
         `NOT NULL`"
      ),
    );
  }
  // The one COMMON word a column's block could plausibly be written in, refused by name so the
  // ruling is stated where it would be broken: `sortable` is ONE written intent and each database
  // derives its own mechanism from it. Per database it would double-book with `edge`, the word that
  // already says which storage form a database takes — and a client's written order has to
  // fingerprint alike whichever form answered it.
  if option.path.is_ident(SORTABLE) {
    return named(
      option,
      format!(
        "`sortable` is ONE intent for every database and this block is `{db}`'s — write it in the \
         common scope, as `#[ingraph(sortable, {db}(…))]`. What each database DOES with it \
         is derived rather than declared: a dialect storing the collection as a native array orders \
         it already and mints nothing, and one storing edge rows mints the companion column.",
        db = kind.as_str()
      ),
    );
  }
  attribute::unknown(option, takes, vocabulary)
}

/// **A collection column that names its ELEMENT's stored type owes the crossing in BOTH
/// directions**, and this is where saying half of it is answered.
///
/// # What the rule is about
///
/// A collection kept in an edge table holds its ELEMENTS as rows, so the row's field is the list of
/// them and `type = "…"` names one. The crossing between the two is therefore over shapes that
/// differ by a `Vec`, and nothing infers it: `from` takes the domain collection and answers
/// `Vec<element>`, `into` is its mirror.
///
/// Declaring `type` and neither verb — or `type` and one — used to compile as far as the EMISSION
/// and land there as `E0308: expected Vec<T>, found T`, pointing at the `#[ingraph::record(…)]` and
/// naming no column. That is a message about the expansion where the mistake is in the declaration,
/// which is exactly the class this front end exists to answer.
///
/// # It is the SYNTACTIC proxy, and the shape of the check is the reason
///
/// What is actually required is a crossing that typechecks, which a macro holding tokens cannot
/// verify — so the check is *both verbs written*, which is what a declaration that meant to cross
/// looks like. It is a proxy in one direction only: it can be satisfied by a function that then
/// fails to compile, and it cannot be satisfied by silence. A crossing between the SAME two types
/// still writes the pair, as `Splice` and `Roll` do, and the identity functions are the honest
/// spelling of *these are the same shape* rather than a workaround.
///
/// # Where the fence is drawn, and what stays outside it
///
/// `type` is the trigger, because a column that names no stored type keeps whatever its domain
/// already is and has nothing to cross. That is what keeps this refusal off the three `label_*`
/// fixtures, whose columns are refused one layer up by the WORD they wrote — measured, not assumed.
///
/// A per-database block is refused on its own terms: one database may cross where another does not,
/// so the check is per block and the message names the database it is about.
fn refuse_a_half_declared_collection_crossing(
  field: &syn::Field,
  per_db: &[FieldDatabase],
  errors: &mut Errors,
) {
  let source = field
    .ident
    .as_ref()
    .expect("a named field")
    .clone()
    .to_string();
  for per in per_db {
    if per.stored.is_none() {
      continue;
    }
    let missing: Vec<&Direction> = [(&per.from, &BUILDS), (&per.into, &LEAVES)]
      .into_iter()
      .filter(|(spec, _)| spec.infallible.is_none() && spec.fallible.is_none())
      .map(|(_, direction)| direction)
      .collect();
    if missing.is_empty() {
      continue;
    }
    let verbs = missing
      .iter()
      .map(|direction| format!("`{}`/`{}`", direction.plain, direction.fallible))
      .collect::<Vec<_>>()
      .join(" and ");
    errors.push(syn::Error::new_spanned(
      &per.at,
      format!(
        "`{source}` is a COLLECTION and `{db}` stores its ELEMENTS, so `type = \"…\"` names one \
         element and the row holds the list of them — the crossing between the two is this \
         declaration's, and {verbs} {is} missing. Write the pair: \
         `#[ingraph({db}(type = \"E\", from = \"to_elements\", into = \"from_elements\"))]`, where \
         `to_elements` takes the field's own type and answers `Vec<E>` and `from_elements` answers \
         the field's own type from one. Where the two shapes already agree the functions are \
         identities, and writing them is what says so.",
        db = per.kind.as_str(),
        is = if missing.len() == 1 { "is" } else { "are" },
      ),
    ));
  }
}

/// **`edge` names how a COLLECTION is stored, so a column no word called a collection has no
/// strategy for it to pick**, and that is refused where the word is written.
///
/// The strategy is a fork in what a value LIST is kept in — a native array column, or a second table
/// of one row per element — and a scalar takes neither: it is one value in one column, which is what
/// every dialect does with it. So the word here selects nothing, and a declaration that wrote it
/// believed something about the column that is not so.
///
/// It is a parse refusal rather than a tolerated no-op because the derive CAN tell: the collection
/// word is on the same field, two tokens away. That is the difference from `flatten`, which is
/// refused a whole layer later — there the derive holds `title: String` and `rate: Timebase` and
/// cannot tell them apart, so a BOUND does the refusing at the first use that names a dialect. Where
/// the tokens answer, the front end answers. The precedent matched is `label_on_a_key_side_field`'s
/// — a word refused for being written on a field whose vocabulary does not admit it.
fn refuse_a_strategy_on_a_column_that_is_not_a_collection(
  field: &syn::Field,
  per_db: &[FieldDatabase],
  errors: &mut Errors,
) {
  let source = field.ident.as_ref().expect("a named field");
  for per in per_db {
    let Some(at) = per.edge.as_ref() else {
      continue;
    };
    errors.push(syn::Error::new_spanned(
      at,
      format!(
        "`{source}` is not a COLLECTION and `edge` names how one is STORED — a value list goes in \
         an array column or in a second table of one row per element, and a single value takes \
         neither. Write `list(…)` or `set(…)` on the field if it holds many, and drop the word if \
         it holds one"
      ),
    ));
  }
}

/// **`unique` names a constraint over ONE column's values, held by at most one row apiece — and a
/// COLLECTION field has no such column**, refused where the word is written.
///
/// The claim `unique` makes is a ROW-TO-ROW comparison of a single value; a collecting field holds
/// MANY values in the one row, so there is no single value there for that comparison to be about.
/// Two readings could be meant instead and neither is this word:
///
/// * an element repeated WITHIN one row is already refused where it would collide — a `set(…)`'s
///   edge table is keyed on `(key…, value)`, so a duplicate element has nowhere to be written at
///   all, and a `sequence`'s is keyed on its position, where a repeat is ordinary;
/// * the whole collection, as ONE value, differing from every other row's is a claim this grammar
///   has no word for yet — Postgres alone could carry it, as a constraint over the array column an
///   unmarked collection already rides, and a word legal on that one dialect's column and refused
///   on the other two's edge table would be a declaration whose meaning depends on which database
///   is reading it, which is the trap `edge` itself exists to keep a reader out of one word over.
///
/// So the honest answer is the refusal rather than a guess at which reading was meant: the field's
/// per-database columns are all EDGE-SHAPED or ABSENT from the row for THIS word's purposes, and
/// the precedent is [`refuse_a_strategy_on_a_column_that_is_not_a_collection`]'s own — a word
/// refused for being written on a field whose vocabulary does not admit it, spanned at the word and
/// naming the field.
fn refuse_unique_on_a_collection(
  field: &syn::Field,
  per_db: &[FieldDatabase],
  errors: &mut Errors,
) {
  let source = field.ident.as_ref().expect("a named field");
  for per in per_db {
    let Some(at) = per.unique.as_ref() else {
      continue;
    };
    errors.push(syn::Error::new_spanned(
      at,
      format!(
        "`{source}` is a COLLECTION and `unique` names a constraint over ONE column's values, held \
         by at most one row apiece — a row here holds MANY values and there is no single one for \
         that comparison to be about. An element repeated WITHIN one row is `set(…)`'s own \
         refusal already, its edge table being keyed on the value; a claim over the whole \
         collection as one value has no column here to carry it. Drop the word."
      ),
    ));
  }
}

/// `<db>(unique(a, b, …))` RESOLVED — every entry held against the record's fields and this
/// database's own columns, and every constraint held against its siblings.
///
/// # THE FIELD AUDIT IS THE MACRO'S, and it is not deferred
///
/// The macro is holding the struct's fields while it reads this word, so a name that is not one of
/// them is answered HERE — at the token that wrote it, in a sentence that says what the list names.
/// Left to the framework, the same mistake would be `Table::with_composite_uniques`' `E0080` inside
/// generated code, spanned at an expansion the author cannot edit and phrased about a descriptor
/// they never wrote. `lineage(fields(…))`'s own posture, for its reason.
///
/// Three shapes are told apart rather than swept into one sentence, because the fix differs:
///
///   * a name that is NO FIELD of this struct — a typo, or a field that was renamed;
///   * a field this database does not carry — `skip`, or a narrowing that took it away. It is a
///     field of the record and no column of THIS row, so the constraint would name a column this
///     database's `CREATE TABLE` never declared;
///   * a COLLECTION — [`refuse_unique_on_a_collection`]'s subject one word over. A collection is
///     rows of a second table (or an array this dialect has no blueprint for), so the parent's row
///     carries nothing for a constraint to be about.
///
/// # THE DUPLICATE IS REFUSED BY NAME, and never deduplicated
///
/// Two spellings of one constraint derive one name, and the second `CREATE UNIQUE INDEX IF NOT
/// EXISTS` over it is a statement the engine discards — a silent no-op where the author believes
/// they declared something. So the collision is the tell, in the two directions it arrives: two
/// composites naming the same COLUMNS in the same order, and a one-entry composite meeting the
/// field-level `unique` marker on that same column. Both report at the LATER spelling and name the
/// earlier one, so the pair is readable from one caret.
///
/// The comparison is on the EFFECTIVE names, per database — the check every name rule in this pass
/// is on, and for the same reason: a `rename` walks straight past a check on the Rust name, and it
/// is the emitted name that reaches the statement.
fn composite_uniques(
  written: &[CompositeUniqueWord],
  kind: DatabaseKind,
  columns: &[PersistColumn],
  collections: &[(&syn::Ident, bool)],
  record: &syn::Ident,
  errors: &mut Errors,
) -> Vec<CompositeUnique> {
  let db = kind.as_str();
  let mut resolved: Vec<CompositeUnique> = Vec::new();
  for word in written {
    let mut entries: Vec<RustSafeName> = Vec::new();
    let mut whole = true;
    for entry in &word.entries {
      let Some(column) = columns.iter().find(|column| &column.source == entry) else {
        whole = false;
        let known = collections.iter().any(|(name, _)| *name == entry);
        errors.push(syn::Error::new_spanned(
          entry,
          if known {
            format!(
              "`{entry}` is a field of `{record}` and no column of `{db}`'s row — a word narrowed \
               it away from this database, so a constraint naming it here is over a column this \
               `CREATE TABLE` never declares. Name it in the blocks whose rows carry it."
            )
          } else {
            format!("`{db}(unique(…))` names fields of `{record}` — `{entry}` is not one")
          },
        ));
        continue;
      };
      if collections
        .iter()
        .any(|(name, collects)| *name == entry && *collects)
      {
        whole = false;
        errors.push(syn::Error::new_spanned(
          entry,
          format!(
            "`{entry}` is a COLLECTION, and a composite unique is over columns of THIS row — a \
             collection's elements are rows of a second table, so the parent row holds no single \
             value for the constraint to compare. An element repeated within one row is `set(…)`'s \
             own refusal; a claim over the whole collection as one value has no column here to \
             carry it."
          ),
        ));
        continue;
      }
      entries.push(column.name.clone());
    }
    // A constraint with a bad entry is DROPPED rather than carried narrower: emitting it would
    // create an index over some of what the author wrote, and the refusal above has already said
    // the declaration is wrong. The rest of the pass runs on, so one expansion reports every rule.
    if !whole {
      continue;
    }

    if let [only] = entries.as_slice()
      && let Some(marked) = columns
        .iter()
        .find(|column| column.unique && column.name.external() == only.external())
    {
      errors.push(syn::Error::new_spanned(
        &word.at,
        format!(
          "`{source}` is already `unique` in `{db}`, and a one-entry `unique({source})` over it \
           derives the SAME constraint name — `__ig_<table>_{column}` by either road — so the \
           second statement would create nothing. The two roads differ in SCOPE and not in width: keep \
           the field marker where the constraint belongs to every database this record declares, \
           and this word where it belongs to `{db}` alone.",
          source = marked.source,
          column = only.external(),
        ),
      ));
      continue;
    }

    if resolved.iter().any(|other| {
      other.entries.len() == entries.len()
        && other
          .entries
          .iter()
          .zip(&entries)
          .all(|(left, right)| left.external() == right.external())
    }) {
      let columns = entries
        .iter()
        .map(|entry| entry.external().to_owned())
        .collect::<Vec<_>>()
        .join(", ");
      errors.push(syn::Error::new_spanned(
        &word.at,
        format!(
          "`{db}` declares `unique({columns})` twice — both spellings derive one constraint name, \
           so the second creates nothing. A different ORDER would be a different constraint: a \
           composite index answers a seek by a leading prefix of its columns, so `(a, b)` and \
           `(b, a)` serve different reads."
        ),
      ));
      continue;
    }

    resolved.push(CompositeUnique { entries });
  }
  resolved
}

/// **`indexed` IN A DATABASE'S BLOCK names a structure over ONE COLUMN OF THAT ROW, and a
/// COLLECTION is not one column of a row anywhere** — refused where the word is written, and
/// redirected to the seat that does take it.
///
/// [`refuse_unique_on_a_collection`]'s argument at the sibling word, with one difference that
/// changes the ending: `unique` over a collection is a claim no seat can carry, so its refusal ends
/// in *drop the word*, where a collection's index is a real thing with a real seat one namespace
/// out. So this ends in a redirect.
///
/// # It lands per FIELD now, where it used to land per DATABASE
///
/// The old rule refused exactly the EDGE-STORED half — always on SQLite and MySQL, which have no
/// array type, and on Postgres wherever `edge` was written — because there the parent's row carries
/// no column to index at all. The array-stored half was left spellable and INERT, waiting for a word
/// that could render it.
///
/// That word arrived and it is not this seat's. [`INDEXED`] at the FIELD is one intent for every
/// database, and each derives its own mechanism from it: a second index on the elements' table where
/// the collection is one, the access method its catalogue names where the collection rides an array
/// column. A per-database seat beside that would be the double-booking with `edge` the field seat's
/// own note weighs — and worse, since the SQLite path folds case and a fold is visible in a set's
/// identity. So BOTH halves redirect, and the storage form stops being a fact this refusal has to
/// read.
fn refuse_indexed_on_a_collection(
  field: &syn::Field,
  per_db: &[FieldDatabase],
  errors: &mut Errors,
) {
  let source = field.ident.as_ref().expect("a named field");
  for per in per_db {
    let Some(at) = per.indexed.as_ref() else {
      continue;
    };
    let db = per.kind.as_str();
    errors.push(syn::Error::new_spanned(
      at,
      format!(
        "`{source}` is a COLLECTION and `{db}(indexed)` names a structure over ONE COLUMN of this \
         row — a collection is not one column of a row in any database here: it is a second table \
         keyed on the row, or an array column whose elements an index reaches through that \
         database's own access method. The word a collection takes is the FIELD's, written where \
         nothing scopes it: `#[ingraph(list(scalar), indexed)]`. It is ONE intent and each database \
         derives its mechanism from it — which is also why it cannot be written per database: on \
         `{sqlite}` the path folds case, and a fold is visible in a `set(…)`'s own identity, so a \
         word written for one store and withheld from the next would be a declaration that means \
         two different things.",
        sqlite = DatabaseKind::Sqlite.as_str(),
      ),
    ));
  }
}

/// **A PARTIAL ABSENCE NAMES WHAT A READ HANDS BACK**, refused per database that has neither a
/// column nor a fill.
///
/// # The coherence is a REFUSAL rather than a forbidding
///
/// The bare `<db>` list is the whole narrowing in one word — *only these databases* — and it says
/// nothing about the ones it left out. Those still have to answer a read: a row of that database
/// carries no such column, the raise still builds the whole record, and the value has to come from
/// somewhere. `Default::default()` is not offered as a floor here for the reason
/// [`FieldDatabase::skip`] states — a value that round-trips out of one store and is invented out of
/// the next is a difference nothing in the declaration records — so the answer is a sentence naming
/// the databases and the spelling that fills them.
///
/// A database whose block already wrote `skip` is NOT reported here whatever it named: with a fill
/// it is answered, and without one it has already earned [`field_database`]'s own sentence. One
/// mistake, one sentence.
fn refuse_an_unfilled_absence(
  field: &syn::Field,
  declaring: &FieldStorage,
  record: &syn::Ident,
  declared: &[DatabaseKind],
  errors: &mut Errors,
) {
  let unfilled: Vec<DatabaseKind> = declared
    .iter()
    .copied()
    .filter(|kind| !declaring.participates(*kind, declared))
    .filter(|kind| {
      !declaring
        .per_db
        .iter()
        .any(|per| per.kind == *kind && per.skip.is_some())
    })
    .collect();
  let (Some(first), Some(at)) = (unfilled.first(), declaring.presence().next()) else {
    return;
  };
  let source = field.ident.as_ref().expect("a named field");
  let kept: Vec<DatabaseKind> = declared
    .iter()
    .copied()
    .filter(|kind| declaring.participates(*kind, declared))
    .collect();
  // ONE error for the whole list, at the first word of it: the narrowing is a single claim about
  // one field however many words spell it, and reporting it per word would bury the rule under the
  // count.
  errors.push(syn::Error::new_spanned(
    &at.at,
    format!(
      "`{source}` is a column of {kept} and `{record}` stores its rows in {all}, so a read of {gone} \
       has no `{source}` to fetch and nothing to hand back instead — write \
       `#[ingraph({db}(skip(default = \"…\")))]` for each of them, naming the `fn() -> T` that \
       supplies the value there. The word may stay beside the fills or go: the two spellings state \
       the same absence from its two ends, and the fill is the half only the declaration can carry.",
      kept = list(&kept),
      all = list(declared),
      gone = list(&unfilled),
      db = first.as_str(),
    ),
  ));
}

/// The declared storage, checked against the words its fields wrote, into the model.
///
/// Everything here is a rule the emitter must never have to re-decide: the names are resolved, the
/// conversions are collapsed into their three states, and each database carries its own columns in
/// declaration order.
fn persist_model(
  record: &syn::Ident,
  node: NodeKind,
  block: Option<PersistBlock>,
  fence: &alias::Fence,
  marked: &[(&syn::Field, Markers)],
  address: &[syn::Ident],
  errors: &mut Errors,
) -> Option<Persist> {
  let markers = || {
    marked.iter().filter_map(|(field, markers)| {
      let at = markers.storage.at()?;
      Some((field.ident.as_ref().expect("a named field"), at))
    })
  };
  // A node that holds no rows is told SO, rather than being told its stores are missing. The
  // sentence a rowless RECORD gets ends in *name a store*, and there is no store to name here: the
  // rows belong to another derive, and pointing at one that cannot exist is the second problem
  // derived from the first that `stored_in` refuses to report for the same reason.
  if !node.holds_rows() {
    for (field, at) in markers() {
      errors.push(syn::Error::new_spanned(
        at,
        format!(
          "`{field}` refines a stored column and {article} {noun} has no rows — a field's storage \
           words say how a column is rendered, and columns are a `record`'s. {law}",
          article = node.article(),
          noun = node.noun(),
          law = owns_one_storage(node),
        ),
      ));
    }
    // The SKIP word's own version of the same sentence. It is refused here rather than read as a
    // harmless no-op because the word says something FALSE about this node: it declares that a row
    // does not hold the field, and there is no row here for that to be a fact about.
    for (field, markers) in marked {
      let name = field.ident.as_ref().expect("a named field");
      if let Some(skip) = &markers.skip {
        errors.push(syn::Error::new_spanned(
          &skip.at,
          format!(
            "`{name}` declares that no row holds it and {article} {noun} has no rows — `skip` is \
             the answer to a question a `record` asks, and this declaration never asks it. {law}",
            article = node.article(),
            noun = node.noun(),
            law = owns_one_storage(node),
          ),
        ));
      }
    }
    return None;
  }
  // A RECORD WITH NO STORE IS REFUSED, and the sentence names both exits.
  //
  // It is the ladder's own law read back: a record IS rows, so a declaration that holds none is not
  // a record at all — it is the rung below, which now has a word. Before the ladder this shape
  // compiled and emitted a key family, a wire face and nothing else, which is exactly what `entity`
  // emits; 22 declarations were on that path with no word for it, and every one of them said
  // `record` while meaning `entity`.
  //
  // Refused at the record's own NAME rather than at a token, because the mistake is what the
  // declaration IS and there is nothing written to point at. `L-G dissolves here`: a `skip` on a
  // rowless tier is refused above, and a record always has rows, so *a skip with no row to be
  // absent from* is not a state the grammar can reach.
  let Some(block) = block.filter(|block| !block.databases.is_empty()) else {
    errors.push(syn::Error::new_spanned(
      record,
      format!(
        "`{record}` holds rows and names no store — write one of {stores} at the head, as \
         `#[ingraph::record(sqlite)]`, or declare it an `entity`, which is this same declaration \
         without the rows: the key family, the accessors and the wire face, all of it, and no \
         table anywhere. A record IS rows.",
        stores = shipped(DatabaseKind::ALL.into_iter().map(DatabaseKind::as_str)),
      ),
    ));
    return None;
  };

  let base = block.rename.clone().unwrap_or_else(|| record.clone());
  // Each of the two names a database emits, renamed or defaulted independently: a block overrides
  // only its own.
  let names: Vec<(syn::Ident, syn::Ident)> = block
    .databases
    .iter()
    .map(|db| {
      let row = db
        .rename
        .clone()
        .unwrap_or_else(|| default_row_name(&base, db.kind));
      let comparison = db
        .comparison
        .clone()
        .unwrap_or_else(|| default_comparison_name(&row));
      (row, comparison)
    })
    .collect();

  let declared: Vec<DatabaseKind> = block.databases.iter().map(|db| db.kind).collect();
  // THE ROW IS THE RECORD'S FIELDS, and a field leaves it only by saying so.
  //
  // Participation used to be a per-field MARKER — a field wearing `persist` was a column and a field
  // without one was not — and it is the DEFAULT now. The tree's own sentence is what settled it:
  // *participation is the FIELD's marker, and a per-database block refines a column rather than
  // selecting one*. The two halves were always separable, and only the first is gone; the refining
  // vocabulary survives whole (`rename`, `sortable`, `flatten`, and each database's `type`, `from`,
  // `into`, `indexed`, `copy`, `edge`, `flatten`) — it just lost the wrapper that used to hold it,
  // because a wrapper granting nothing is a word a reader has to look up for no answer. A record IS
  // rows, and its data fields ARE the row unless declared absent.
  //
  // `skip` is the declared absence and the only exit, which is what makes the rule readable in one
  // direction: every field of a record is a column, and the ones that are not wear a word saying so.
  // Identity is unskippable, so a key column can never fall out of this list — which is what retires
  // the *a user-declared layout whose id no block names* branch the query face used to guard.
  //
  // Nullability follows `optional`, never the field's spelled type: a macro sees tokens, and a type
  // alias for `Option<_>` is exactly the case that proves it. The COLLECTION word travels with it
  // because a collection column's crossing is a different one — see
  // [`refuse_a_half_declared_collection_crossing`].
  let participating: Vec<(&syn::Field, &FieldStorage, bool, bool)> = marked
    .iter()
    .filter(|(_, markers)| markers.skip.is_none())
    .map(|(field, markers)| {
      (
        *field,
        &markers.storage,
        markers.optional.is_some(),
        markers.label.as_ref().is_some_and(Written::collection),
      )
    })
    .collect();

  // FIELD -> is it a collection, for the composite-unique audit below. Built from the same list
  // `refuse_unique_on_a_collection` reads, so the two words answer the question one way.
  let collections: Vec<(&syn::Ident, bool)> = participating
    .iter()
    .map(|(field, _, _, collects)| (field.ident.as_ref().expect("a named field"), *collects))
    .collect();
  for (field, declaring, _, collects) in &participating {
    if *collects {
      refuse_a_half_declared_collection_crossing(field, &declaring.per_db, errors);
      refuse_unique_on_a_collection(field, &declaring.per_db, errors);
      refuse_indexed_on_a_collection(field, &declaring.per_db, errors);
    } else {
      refuse_a_strategy_on_a_column_that_is_not_a_collection(field, &declaring.per_db, errors);
    }
  }

  // A field's block may only speak about a database the record stores the row in.
  for (_, declaring, _, _) in &participating {
    for per in &declaring.per_db {
      if !declared.contains(&per.kind) {
        errors.push(syn::Error::new_spanned(
          &per.at,
          format!(
            "`{db}` is not one of the databases `{record}` declares — it stores its rows in {list}. \
             A field names a database to narrow itself to it or to say how it renders the column \
             there, and both need the record to store the row in it first.",
            db = per.kind.as_str(),
            list = list(&declared),
          ),
        ));
      }
    }
  }

  // THE PARTICIPATION MASK, and the one thing a partial absence has to say.
  //
  // A bare `<db>` on a field says *only these databases*, which is the inversion read backwards: the
  // container granted every one it declared and the word takes some of them away. That is a shape
  // this record now HAS — each database's column list is its own — so the word is spent rather than
  // refused, and what is held to a rule is the READ: a database whose row has no such column has to
  // hand a value back anyway, and only the declaration can say which.
  //
  // Naming the whole declared set takes nothing away and is the restatement it is.
  for (field, declaring, _, _) in &participating {
    // An ADDRESS step whose narrowing was already refused by name is not told a second time that
    // its read has no answer: the first sentence says the word may not be there at all, which is
    // strictly more than this one would add.
    if address.contains(field.ident.as_ref().expect("a named field")) {
      continue;
    }
    refuse_an_unfilled_absence(field, declaring, record, &declared, errors);
  }

  let databases = block
    .databases
    .iter()
    .zip(names)
    .map(|(db, (name, comparison))| {
      let scope = format!("`{}`", db.kind.as_str());
      // THE MASK, applied. Every field the container granted this database, less the ones a word
      // took away — which is the whole of the per-dialect participation model at the record saddle:
      // the list this database's row, its `INSERT`, its `SELECT` and its comparison are all built
      // from is this database's own, and a field it does not carry is filled at the raise instead.
      let fills: Vec<Filled> = participating
        .iter()
        .filter(|(_, declaring, _, _)| !declaring.participates(db.kind, &declared))
        .filter_map(|(field, declaring, _, _)| {
          Some(Filled {
            source: field.ident.clone().expect("a named field"),
            fill: declaring.fill_at(db.kind)?.fill(),
          })
        })
        .collect();
      let columns: Vec<PersistColumn> = participating
        .iter()
        .filter(|(_, declaring, _, _)| declaring.participates(db.kind, &declared))
        .map(|(field, declaring, nullable, _)| {
          let source = field.ident.clone().expect("a named field");
          let per = declaring.per_db.iter().find(|per| per.kind == db.kind);
          let column = per
            .and_then(|per| per.rename.as_ref())
            .or(declaring.rename.as_ref())
            .map_or_else(
              || RustSafeName::from_ident(&source),
              |lit| RustSafeName::new(lit.value(), lit.span()),
            );
          let subject = format!("`{source}` in {scope}");
          let (from, into) = per.map_or_else(
            || (Conversion::Default, Conversion::Default),
            |per| {
              (
                per.from.resolve(&subject, BUILDS, errors),
                per.into.resolve(&subject, LEAVES, errors),
              )
            },
          );
          // A conversion for the whole row REPLACES the field-wise body, so a column that also
          // declares one has written a rule with nothing to apply it to. The span is whichever of
          // the two the author wrote — a field with no storage words at all declares no conversion,
          // so `column.declared()` is false and this loop reports nothing for it.
          for (container, column, direction) in
            [(&db.from, &from, BUILDS), (&db.into, &into, LEAVES)]
          {
            if let (true, true, Some(at)) = (
              container.declared(),
              column.declared(),
              per.map(|per| &per.at).or_else(|| declaring.at()),
            ) {
              errors.push(syn::Error::new_spanned(
                at,
                format!(
                  "`{db}` declares `{plain}`/`{try}` for the WHOLE row and `{source}` declares one \
                   of its own — the row's conversion replaces the field-wise body, so both is \
                   ambiguous. Keep the container's, or drop it and convert field by field.",
                  db = db.kind.as_str(),
                  plain = direction.plain,
                  try = direction.fallible,
                ),
              ));
            }
          }
          PersistColumn {
            name: column,
            domain: field.ty.clone(),
            stored: per.and_then(|per| per.stored.clone()),
            copy: per.is_some_and(|per| per.copy.is_some()),
            edge: per.is_some_and(|per| per.edge.is_some()),
            nullable: *nullable,
            indexed: per.is_some_and(|per| per.indexed.is_some()),
            unique: per.is_some_and(|per| per.unique.is_some()),
            // The DIALECT-FREE word answered by THIS dialect: a SQL database has a prefix to drop
            // and a document database has not, so one written word mints the layout where there is
            // one and nothing where there is none. A block of this database's own says the same
            // thing about it alone, and either spelling is enough.
            flatten: per.is_some_and(|per| per.flatten.is_some())
              || (declaring.flatten.is_some() && db.kind.is_sql()),
            from,
            into,
            source,
          }
        })
        .collect();
      // THE COMPOSITE CONSTRAINTS, resolved against the list built just above — this database's
      // own columns, with every `rename` already applied, which is what the audit and the
      // duplicate check both have to be on.
      let uniques = composite_uniques(&db.uniques, db.kind, &columns, &collections, record, errors);
      // The BACKEND is the type now, so a database's own vocabulary is structural: mongo takes a
      // collection and has no schema to be given.
      let storage = Storage {
        name,
        comparison,
        from: db
          .from
          .resolve(&format!("the `{}` row", db.kind.as_str()), BUILDS, errors),
        into: db
          .into
          .resolve(&format!("the `{}` row", db.kind.as_str()), LEAVES, errors),
        columns,
        fills,
        aliases: db.aliases.clone(),
      };
      let table = db.table.as_ref().map(literal_name);
      if let Some(declared) = db.table.as_ref() {
        column::refuse_reserved_table(fence, &declared.value(), declared, errors);
      }
      let schema = db.schema.as_ref().map(syn::LitStr::value);
      match db.kind {
        DatabaseKind::Sqlite => DatabaseBackend::Sqlite(SqliteDatabase {
          table,
          schema,
          uniques,
          storage,
        }),
        DatabaseKind::Postgres => DatabaseBackend::Postgres(PostgresDatabase {
          table,
          schema,
          uniques,
          storage,
        }),
        DatabaseKind::Mysql => DatabaseBackend::MySql(MySqlDatabase {
          table,
          schema,
          uniques,
          storage,
        }),
        DatabaseKind::Mongo => DatabaseBackend::Mongo(MongoDatabase {
          collection: table,
          storage,
        }),
      }
    })
    .collect::<Vec<DatabaseBackend>>();

  // Every check here is on the EFFECTIVE name, per database: a rename walks past a check on the
  // field's Rust name, and it is the emitted name that reaches a `CREATE TABLE`.
  for database in &databases {
    let mut taken: Vec<&PersistColumn> = Vec::new();
    for column in database.columns() {
      column::refuse_framework_name(fence, column.name.external(), column.name.safe(), errors);
      // On the RUST face alone, for the reason the wire check above gives: mangling is a
      // function, so an equal external name is already an equal safe one.
      if let Some(first) = taken
        .iter()
        .find(|first| first.name.safe() == column.name.safe())
      {
        let called = if first.name.external() == column.name.external() {
          format!("one column called `{}`", column.name)
        } else {
          format!(
            "one column called `{}` — `{}` and `{}` are two column names with one Rust spelling",
            column.name.safe(),
            first.name,
            column.name,
          )
        };
        errors.push(syn::Error::new_spanned(
          column.name.safe(),
          format!(
            "the `{db}` row would carry `{first}` and `{second}` as {called} — within one database \
             every column needs its own name",
            db = database.kind().as_str(),
            first = first.source,
            second = column.source,
          ),
        ));
      }
      taken.push(column);
    }
  }

  if let Some(declared) = block.table.as_ref() {
    column::refuse_reserved_table(fence, &declared.value(), declared, errors);
  }
  Some(Persist {
    backends: databases,
    // The common `table = "…"`, which the model keeps as the record's own name and hands to any
    // database that named none of its own — the resolution `Persist::table_of` makes.
    table: block.table.as_ref().map(literal_name),
  })
}

/// A family's field markers on a record that declared no block for it.
///
/// One sentence for a family, because it is one rule: a field's marker puts the field IN something,
/// and the record's block is what says that something exists. The three clauses a caller supplies
/// are what the family's own is — `consequence` completes "so it …", `puts` completes "a field's
/// `<family>` marker …", and `names` completes "the record's `<family>(…)` is what names …".
///
/// It has ONE caller now, the wire face's, and it read *one sentence for five families* while
/// storage was a family like the others. The unwrap took storage out of the block vocabulary and
/// the participation inversion took its field marker away, so the sentence has nothing to say about
/// rows: a record HAS a store by construction, and a field is a column by construction. What is
/// left is the shape rather than the count — the helper stays general because the rule is, and the
/// next family to arrive is spelled here rather than beside it.
fn no_family_block<'a>(
  record: &syn::Ident,
  family: &str,
  consequence: &str,
  puts: &str,
  names: &str,
  markers: impl Iterator<Item = &'a syn::Path>,
  errors: &mut Errors,
) {
  for at in markers {
    errors.push(syn::Error::new_spanned(
      at,
      format!(
        "`{record}` declares no `{family}(…)` block, so {consequence} — a field's `{family}` marker \
         {puts}, and the record's `{family}(…)` is what names {names}"
      ),
    ));
  }
}

/// Whether the settled [`Persist`] persists the record field `name` in any database.
///
/// [`graphql_model`]'s rule: a wire field with no stored source cannot be POPULATED, because a read
/// fills it from a column and a field with no column has nothing to read from.
///
/// It reads the SETTLED persist rather than the declaration, so a record whose `persist(…)` was itself
/// refused reports that problem rather than a second one derived from it.
fn stored_in(persist: Option<&Persist>, name: &syn::Ident) -> bool {
  persist.is_some_and(|persist| {
    persist.backends.iter().any(|database| {
      database
        .columns()
        .iter()
        .any(|column| &column.source == name)
    })
  })
}

/// The record's progress ledger, DERIVED from the storage rather than declared.
///
/// A ledger's control tables live in the `persist` engine's own pool, so its hosts are the databases
/// `persist(…)` names, and nothing else has to be declared for one to exist: what it certifies is the
/// unit's close, which every stored record has. Being stored is the whole condition, so this reports
/// nothing — there is no declaration left to disagree with the storage.
///
/// The hosts are a SUBSET rather than the whole selection, and that follows from nobody having asked:
/// a ledger is bookkeeping the framework adds wherever a pool can hold it, so a database with no
/// ledger backend has none, and a record stored only in such databases has no ledger at all. A
/// framework gap (`store/progress/` ships sqlite and postgres), named here rather than refused —
/// refusing it would refuse `persist(mongo)` outright, over a table nobody declared.
fn progress_model(persist: Option<&Persist>) -> Option<Progress> {
  let hosts: Vec<ProgressHost> = persist?
    .backends
    .iter()
    .filter_map(|backend| ProgressHost::of(backend.kind()))
    .collect();
  (!hosts.is_empty()).then_some(Progress { hosts })
}

/// The declared `derived(…)`, checked against the fields the declaration already has, into the
/// model.
///
/// TWO rules, and both are about the block as a whole rather than about an entry's own grammar:
///
/// - A block naming NO position is refused, exactly as a `persist(…)` naming no database is —
///   a record nothing points back at is spelled by omitting the block.
/// - A position may not take a FIELD's name. There is no Rust field for a reverse position, so
///   nothing collides in the struct; what collides is the FACE — one namespace per face, and a
///   reader asking for `tracks` must not have to know which half of the declaration answers.
///
/// What is NOT checked here is anything about the SOURCE: whether it refers back, and through which
/// field, are facts about a declaration this one cannot see. The emission carries them to the
/// compiler instead.
fn derived_model(
  block: Option<DerivedBlock>,
  marked: &[(&syn::Field, Markers)],
  errors: &mut Errors,
) -> Vec<Derived> {
  let Some(block) = block else {
    return Vec::new();
  };
  if block.entries.is_empty() {
    errors.push(syn::Error::new_spanned(
      &block.at,
      "`derived(…)` names the records that point back at this one, and it names none — write \
       `<name> = \"path::to::Source\"` inside it; a record nothing refers to is spelled by omitting \
       the block",
    ));
    return Vec::new();
  }
  block
    .entries
    .into_iter()
    .filter(|entry| {
      let clash = marked
        .iter()
        .any(|(field, _)| field.ident.as_ref() == Some(&entry.name));
      if clash {
        errors.push(syn::Error::new_spanned(
          &entry.name,
          format!(
            "`{name}` is already a field of this record — a reverse position has NO Rust field, so \
             the two would be one name on one face. One namespace per face: rename the position, or \
             the field.",
            name = entry.name,
          ),
        ));
      }
      !clash
    })
    .map(|entry| Derived {
      name: entry.name,
      source: entry.source,
      field: entry.field,
    })
    .collect()
}

/// The declared `locate(…)`, checked against the names this record has already spent, into the
/// model.
///
/// [`derived_model`]'s two rules, and it is the SAME two rather than two of its own — an empty block
/// is a declaration that says nothing, and a position may not take a name the face already answers.
/// What widens is only the second one's REACH: a reverse position collides with the record's fields,
/// and an artifact position collides with those and with the reverse positions too, because by now
/// there are two kinds of fieldless word on one face and the third has to clear both.
///
/// It therefore reads the SETTLED reverse positions rather than the declared block, for the reason
/// [`stored_in`] gives: a record whose `derived(…)` was itself refused reports that problem rather
/// than a second one derived from it — a position that was dropped for taking a field's name is not
/// a name this record ever mints, so nothing may be refused for repeating it.
///
/// What is NOT checked here is anything about the FAMILY: that the path names a blob node at all,
/// and that the node was derived from THIS record, are facts about a declaration this one cannot
/// see. The emission carries them to the compiler instead.
///
/// # The `data` ask's WRITTEN name is held to the same law, and its default is not
///
/// A `data = "…"` names a second field on the same face, so two positions writing one name is the
/// namespace rule one word over and it is refused here. What is NOT checked is a written name that
/// collides with another position's DEFAULT, and the reason is a boundary rather than an oversight:
/// the default is `<domain-word>Data` in the framework's own camelCase, and that rule has ONE home —
/// the wire face, where it is resolved. Reading it here would be a second authority on what a client
/// sees, which is the mistake the fallback was centralised to prevent.
fn locate_model(
  block: Option<LocateBlock>,
  marked: &[(&syn::Field, Markers)],
  reverse: &[Derived],
  errors: &mut Errors,
) -> Vec<Artifact> {
  let Some(block) = block else {
    return Vec::new();
  };
  if block.entries.is_empty() {
    errors.push(syn::Error::new_spanned(
      &block.at,
      "`locate(…)` names the artifact families this record answers an address for, and it names \
       none — write `<name> = \"path::to::Family\"` inside it; a record nothing was derived from is \
       spelled by omitting the block",
    ));
    return Vec::new();
  }
  let mut settled: Vec<Artifact> = Vec::new();
  for entry in block.entries {
    // WHICH half of the face the word was already spent on, and what to call it back — one word
    // per clause, because the sentence names the thing the author has to rename.
    let taken = if marked
      .iter()
      .any(|(field, _)| field.ident.as_ref() == Some(&entry.name))
    {
      Some(("a field of this record", "the field"))
    } else if reverse.iter().any(|position| position.name == entry.name) {
      Some((
        "a reverse position this record declares",
        "the reverse position",
      ))
    } else {
      None
    };
    if let Some((already, other)) = taken {
      errors.push(syn::Error::new_spanned(
        &entry.name,
        format!(
          "`{name}` is already {already} — an artifact position has NO Rust field either, so the \
           two would be one name on one face. One namespace per face: rename the artifact, or \
           {other}.",
          name = entry.name,
        ),
      ));
      continue;
    }
    let data = entry.data.and_then(|ask| {
      let require = |bytes: ArtifactBytes| {
        if ask.required { bytes.require() } else { bytes }
      };
      let Some(written) = ask.rename else {
        return Some(require(ArtifactBytes::asked()));
      };
      let name = written.value();
      if let Some(other) = settled
        .iter()
        .find(|position| position.data.as_ref().and_then(ArtifactBytes::name) == Some(&name))
      {
        errors.push(syn::Error::new_spanned(
          &ask.at,
          format!(
            "`{name}` is the wire field `{other}` already asks for — two positions naming one \
             field is one name on one face. One namespace per face: rename this ask, or the other.",
            other = other.name,
          ),
        ));
        return None;
      }
      Some(require(ArtifactBytes::named(name)))
    });
    settled.push(Artifact {
      name: entry.name,
      family: entry.family,
      data,
      required: entry.required,
    });
  }
  settled
}

/// The declared `graphql(…)`, checked against the fields that carry the marker, into the model.
///
/// It reads the settled [`Persist`] rather than the declaration, because the rule it enforces is about
/// what is STORED: a wire field with no stored source cannot be populated by a read.
/// A DECLARED CONVERTER on a QUANTIFIED column, refused BY NAME.
///
/// `graphql(input(comparison(<db>(into = "…"))))` names a function from the DOMAIN operand to the
/// STORED one, and the crossing spends it at the collection entry point —
/// `try_from_filter_with(filter, f)`, whose `filter` parameter is a `ListFilter` at every dialect
/// and every storage strategy. A quantified column's filter is a [`QuantifiedFilter`], so the
/// declared word reaches that entry and is `E0308` INSIDE THE EXPANSION: a message about the
/// emitter's own types, at the record attribute, naming neither the field nor the word that caused
/// it. This is that mistake, refused where the author wrote it.
///
/// The wall is the NARROW KIND's own reason and not a gap in the emitter. `QuantifiedFilter` exists
/// for an element with no honest literal form — a detection pair whose float makes `hasElement` a
/// lie — so it holds the element in NONE of its two slots: `any` holds a whole element FILTER and
/// `count` holds a cardinality. There is no operand for a converter to carry, which is also why the
/// kind has no `TryMapFilter` row for the entry to be generic over.
///
/// Both spellings refuse, and the sentence names whichever was written: `into` and `try_into` reach
/// one entry point, the total one being wrapped at `Infallible` rather than given a second door.
///
/// A field whose element DOES have a literal form wants `list(…)` or `set(…)`, whose seven element
/// slots are exactly what a converter is for. That is what the refusal says.
fn refuse_a_converter_a_quantified_column_cannot_carry(
  markers: &Markers,
  declaring: &WireField,
  name: &syn::Ident,
  errors: &mut Errors,
) {
  if markers.label.as_ref().and_then(Written::word) != Some(Label::Quantified) {
    return;
  }
  for leg in &declaring.comparison {
    // The leg carries no span of its own, and it does not need one: `value::parse_literal` respans
    // the parsed path onto the `"…"` LITERAL, so the caret sits on the function the author named.
    let (word, at) = match &leg.conversion {
      Conversion::Default => continue,
      Conversion::Infallible(path) => ("into", path),
      Conversion::Fallible(convert) => ("try_into", &convert.path),
    };
    errors.push(syn::Error::new_spanned(
      at,
      format!(
        "`{name}` is a `quantified(…)` collection and `{word} = \"…\"` converts its ELEMENT \
         OPERANDS — the narrow kind has none. It carries two slots and neither holds an element: \
         `any` holds a whole element FILTER and `count` holds a cardinality, which is the whole \
         reason the kind exists (an element with no honest literal form has no operand worth \
         publishing). Write `list(…)` or `set(…)` if this element does have one — their seven \
         element slots are what a converter is for — or drop the word and let the element's own \
         filter carry its crossing.",
      ),
    ));
  }
}

fn graphql_model(
  record: &syn::Ident,
  node: NodeKind,
  block: Option<GraphqlBlock>,
  persist: Option<&Persist>,
  marked: &[(&syn::Field, Markers)],
  errors: &mut Errors,
) -> Option<Graphql> {
  let Some(block) = block else {
    no_family_block(
      record,
      "graphql",
      "it has no wire face",
      "puts a field on a type",
      "the backends that render it",
      marked
        .iter()
        .filter_map(|(_, markers)| markers.graphql.as_ref().map(|declared| &declared.at)),
      errors,
    );
    return None;
  };
  if block.backends.is_empty() {
    errors.push(syn::Error::new_spanned(
      &block.at,
      "`graphql(…)` names the backends that render the record, and it names none — write \
       `async_graphql` inside it; a record with no wire face is spelled by omitting the block",
    ));
    return None;
  }

  // THE FACE IS THE DECLARATION'S FIELDS, and a field leaves it only by saying so — the storage
  // side's own law, read at the other face. A declaration that names a backend has said what it
  // publishes: everything it holds. So participation is not a marker here either, and what a field
  // writes is a REFINEMENT of a place it already has.
  let declared: Vec<GraphqlKind> = block.backends.iter().map(|backend| backend.kind).collect();
  // One unrefined shape per field, minted up front so the walk can hold a REFERENCE to it: a field
  // that wrote no wire word is read through the same shape as one that did.
  let unrefined: Vec<WireField> = marked
    .iter()
    .map(|(field, _)| WireField::unrefined(field.ident.as_ref().expect("a named field")))
    .collect();
  let mut exposed: Vec<(&syn::Field, &WireField)> = Vec::new();
  // The fields the WORD withheld — from every backend, and from one apiece. A withheld field never
  // becomes a `GraphqlField`, so the OUTPUT object is swept by absence; these lists are what the
  // filter and the order-by read, both being one per record and built from the STORED columns.
  let mut skipped: Vec<syn::Ident> = Vec::new();
  let mut per_backend_skipped: Vec<(GraphqlKind, syn::Ident)> = Vec::new();
  for ((field, markers), silent) in marked.iter().zip(&unrefined) {
    let name = field.ident.as_ref().expect("a named field");
    // A field that wrote no wire word is published as it stands, so the walk below reads the same
    // shape for every field: the words it wrote, or the silence that declines to change anything.
    let declaring = markers.graphql.as_ref().unwrap_or(silent);
    // The WIRE SKIP is read FIRST and it is total: a field absent from every backend's vocabulary
    // has no name, no form and no crossing to declare, so an entry beside the word is a rule with
    // nothing to apply it to. Refused by name, and the walk moves on — the field is withheld
    // whatever else was written, so nothing downstream asks about it twice.
    if let Some(at) = &declaring.skip {
      let others = [
        declaring.rename.is_some().then_some("rename"),
        declaring.ty.is_some().then_some("type"),
        (!declaring.output.is_empty()).then_some("output"),
        (!declaring.comparison.is_empty()).then_some("input"),
      ]
      .into_iter()
      .flatten()
      .collect::<Vec<_>>();
      if !others.is_empty() {
        errors.push(syn::Error::new_spanned(
          at,
          format!(
            "`skip` withholds `{name}` from every wire vocabulary, and {list} declares what it \
             looks like on one — a field the schema never names has no name, no form and no \
             crossing to declare. Drop the word, or drop what it makes unreachable.",
            list = shipped(others.iter().copied()),
          ),
        ));
      }
      for per in &declaring.per_backend {
        if let Some(at) = &per.skip {
          errors.push(syn::Error::new_spanned(
            at,
            format!(
              "`skip` already withholds `{name}` from EVERY backend — `{backend}(skip)` beside it \
               says the same thing about one of them. One absence, said once.",
              backend = per.kind.as_str(),
            ),
          ));
        }
      }
      skipped.push(name.clone());
      continue;
    }
    for per in &declaring.per_backend {
      if let Some(at) = &per.skip {
        if declared.contains(&per.kind) {
          per_backend_skipped.push((per.kind, name.clone()));
        } else {
          // The block's own not-declared refusal fires below; nothing is recorded for a backend the
          // record does not render, so no face reads a withholding nobody could have written.
          let _ = at;
        }
      }
    }
    // STORED NOWHERE AND YET PUBLISHED, refused BY NAME. A wire field with no stored source has
    // nothing to answer a read with, so the pair is refused rather than silently answering `null`.
    //
    // Asked of a declaration THAT HOLDS ROWS and of no other. The rule reads a column, and a rowless
    // tier has none to read — its face answers out of the value itself — so asking it here would
    // refuse every field of every entity over a table that tier does not have.
    //
    // ONE sentence now, where there were two. The other named the word a field had to add beside
    // `graphql`, and the inversion deleted both: there is no participation marker to forget, so the
    // only way to reach this is to have DECLARED the absence and left the field on the face.
    if node.holds_rows() && !stored_in(persist, name) {
      let at = markers.skip.as_ref().map_or(&declaring.at, |skip| &skip.at);
      errors.push(syn::Error::new_spanned(
        at,
        format!(
          "`{name}` wears `skip`, so it is a column in no database, and the wire face publishes \
           every column — a wire field with no stored source has nothing to answer a read with, so \
           the pair is REFUSED BY NAME rather than silently answering `null`. Withhold it from the \
           wire too (`graphql(skip)`), or drop `skip` and store it. This is the one shape a \
           resolver-computed field would revive: the day a declaration can name a function that \
           COMPUTES a published field, stored-nowhere-yet-published becomes a real declaration and \
           this refusal is what to lift."
        ),
      ));
      continue;
    }
    for per in &declaring.per_backend {
      if !declared.contains(&per.kind) {
        errors.push(syn::Error::new_spanned(
          &per.at,
          format!(
            "`{backend}` is not one of the backends `{record}` declares — its `graphql(…)` names \
             {list}",
            backend = per.kind.as_str(),
            list = block
              .backends
              .iter()
              .map(|backend| format!("`{}`", backend.kind.as_str()))
              .collect::<Vec<_>>()
              .join(", "),
          ),
        ));
      }
    }
    refuse_a_converter_a_quantified_column_cannot_carry(markers, declaring, name, errors);
    exposed.push((field, declaring));
  }

  let base = block.rename.clone().unwrap_or_else(|| record.clone());
  // FOUR types, one of each per RECORD rather than per backend: a filter and an order-by are WIRE
  // types, and a client must never see a schema that varies with a deployment's storage choice.
  // Their RESOLUTION is per database — the filter crosses into each `*Comparison`, an order-by
  // variant resolves to that database's column name — and that crossing is where storage enters.
  // ONE `rename` per type sets BOTH faces — the Rust identifier and the schema name — so a
  // defaulted type's schema name is its Rust name. Consequence worth knowing: the output's schema
  // name now defaults to `<E>GraphqlOutput` where `graphql(name = "…")` used to make it `<E>`.
  // `from_ident` rather than `new`, so BOTH faces are the identifier as written: a type name is
  // Rust, and `new`'s field-oriented mangling would snake_case it.
  //
  // The ARGUMENT object is the fourth, and it is the one with no `rename`: the grammar has no
  // `graphql(input(rename = "…"))` at container level, and `input` is already a FIELD-level word
  // for the schema position — so a knob here would be one word meaning two things. A collision on
  // its name is the emitted-type rule's refusal like any other.
  let wire = |renamed: Option<syn::Ident>, default: syn::Ident| {
    RustSafeName::from_ident(&renamed.unwrap_or(default))
  };
  let input = wire(None, default_input_name(&base));
  let output = wire(block.output.clone(), default_output_name(&base));
  let key_output = wire(block.key.clone(), default_key_output_name(&base));
  let filter = wire(block.filter.clone(), default_filter_name(&base));

  // THE PAGE'S TWO SDL NAMES, which take neither `wire` nor `base` — and both omissions are the
  // point. They name types in GraphQL's one flat namespace rather than in the declaring scope, so
  // there is no Rust identifier to make safe and nothing for `rename = "…"`'s Rust base to prefix:
  // a page renamed `Reel` and a record renamed `Spool` are two independent facts.
  //
  // The word is held to GraphQL's own Name grammar HERE rather than downstream, for the reason
  // `wire::refuse_invalid_name` states in full: nothing later refuses one. It is also the ONLY fence
  // on the word, per the 2026-08-13 ruling — the two alphabets are not one another's subsets, and
  // each direction of the mismatch is a real declaration: Rust accepts `débit` where GraphQL does
  // not, and GraphQL accepts `type` where a Rust ident parse did not.
  let mut sdl_name = |renamed: Option<syn::LitStr>| -> Option<String> {
    let spelled = renamed?;
    let word = spelled.value();
    wire::refuse_invalid_name(&word, &spelled, errors);
    Some(word)
  };
  let connection = sdl_name(block.connection.clone());
  let edge = sdl_name(block.edge.clone());
  // THE ADDRESS'S TWO FACES, by the page's own reading: schema words, held to GraphQL's Name
  // grammar where the literal is, and taking neither `wire` nor `base` — a face named outright is
  // carried verbatim, which is what makes the base a DEFAULT for it rather than a prefix.
  let key_object = sdl_name(block.key_object.clone());
  let key_argument = sdl_name(block.key_argument.clone());

  let backends = block
    .backends
    .iter()
    .map(|backend| {
      let fields = exposed
        .iter()
        // THIS backend's own withholding, applied where the backend's field list is built: a field
        // absent from one library's rendering and present in the next one's is exactly what the
        // per-backend block exists to say.
        .filter(|(field, _)| {
          let source = field.ident.as_ref().expect("a named field");
          !per_backend_skipped
            .iter()
            .any(|(kind, skipped)| *kind == backend.kind && skipped == source)
        })
        .map(|(field, declaring)| {
          let source = field.ident.clone().expect("a named field");
          let per = declaring
            .per_backend
            .iter()
            .find(|per| per.kind == backend.kind);
          let common = declaring.rename.as_ref();
          let face = |block: Option<&FaceBlock>| Face {
            name: block
              .and_then(|block| block.rename.as_ref())
              .or(common)
              .map_or_else(
                || RustSafeName::from_ident(&source),
                |lit| RustSafeName::new(lit.value(), lit.span()),
              ),
            attrs: block
              .and_then(|block| block.attrs.clone())
              .unwrap_or_default(),
          };
          // The CROSSINGS are the field's own and the same at every graphql backend, because what
          // they cross into is a ROW: the SDL a second library renders is the same SDL, and a
          // conversion is not a fact about which crate serves it.
          let position = |legs: &[WireLeg]| WirePosition {
            legs: legs.to_vec(),
          };
          let output = per.and_then(|per| per.output.as_ref());
          GraphqlField {
            input: face(per.and_then(|per| per.input.as_ref())),
            output: face(output),
            // The Rust member does NOT fall back on `common`, where both faces' names do: the
            // field-level `rename` is a SCHEMA name written once for two positions, and reading it
            // here would re-couple the axes the flip separated.
            output_field: output.and_then(|block| block.rust.clone()),
            wire: declaring.ty.clone(),
            output_crossing: position(&declaring.output),
            input_crossing: position(&declaring.comparison),
            domain: field.ty.clone(),
            source,
          }
        })
        .collect();
      let rendering = AsyncGraphql {
        attrs: backend.attrs.clone().unwrap_or_default(),
        fields,
        skipped: per_backend_skipped
          .iter()
          .filter(|(kind, _)| *kind == backend.kind)
          .map(|(_, source)| source.clone())
          .collect(),
      };
      match backend.kind {
        GraphqlKind::AsyncGraphql => GraphqlBackend::AsyncGraphql(rendering),
      }
    })
    .collect::<Vec<GraphqlBackend>>();

  // Every name that reaches the SDL is held to GraphQL's Name grammar. Over the BUILT faces rather
  // than the declaration, because those are exactly the names emitted — a position that renamed
  // nothing exposes the field's own name, which is how a non-ASCII Rust field reaches the rule
  // without anyone writing a string.
  //
  // ONCE per distinct name, unlike the duplicate check below: that rule is genuinely per position
  // (two fields may collide in the output and not the input), whereas the grammar is ONE authority
  // for the whole schema — so a name renamed once and exposed in both positions is one mistake, and
  // deduplicating on the name also lands the refusal on whichever declaration produced it.
  //
  // The COMPILER hides whether this happens: two errors carrying the same message at the same span
  // are collapsed into one diagnostic, so removing the dedup leaves every `.stderr` unchanged and
  // only the unit tests notice. Measured. Which is the reason to dedup here rather than lean on it:
  // the collapse is rustc's behaviour, not a rule this crate is owed, and the error count a caller
  // reads should be the number of mistakes.
  let mut refused: Vec<(&syn::Ident, &str)> = Vec::new();
  for field in backends.iter().flat_map(GraphqlBackend::fields) {
    for face in [&field.output, &field.input] {
      let name = face.name.external();
      if refused
        .iter()
        .any(|(source, seen)| *source == &field.source && *seen == name)
      {
        continue;
      }
      refused.push((&field.source, name));
      wire::refuse_invalid_name(name, face.name.safe(), errors);
    }
  }

  // Two fields cannot share a name in one schema position, and BOTH positions ask it the same way
  // now: on the EXTERNAL face, because that is the only face a collision can happen on.
  //
  // The input position used to ask it on the mangled RUST face, and the rationale was that the
  // filter's own struct fields ARE the mangled input names. They are not any more — they are the
  // record's own field names, LAYER 1, which no wire word reaches — so the question that rule
  // answered has no subject left. What it caught besides a real collision was `bitRate` beside
  // `bit_rate`: two perfectly good, DISTINCT GraphQL names refused because normalisation happened to
  // collapse them onto one member. That refusal was the violation's own artifact, and it goes with
  // the violation; the pair is legal and compiles.
  //
  // What remains is the collision itself, and it needs saying EXPLICITLY here rather than being left
  // to rustc: with the members distinct by construction there is no duplicate field for the compiler
  // to report, so two fields renamed onto one wire name would otherwise reach a schema and render an
  // input object with the same field twice. The refusal names both fields and the wire name they
  // share, at the declaration's own span.
  //
  // The OUTPUT position asked it this way already. Its struct fields are the domain names too, so
  // mangling has nothing to collapse there either: `bitRate` beside `bit_rate` is two distinct
  // schema fields on two distinct members, and it is legal in both positions.
  //
  // Its struct fields cannot collide AT ALL now: they are the domain names — LAYER 1, which no word
  // reaches — and those are distinct by construction. The third pass moved with the word it is
  // about: `output(field = "…")` names an ACCESSOR, and two fields naming one accessor is the
  // collision that remains.
  //
  // It is not covered by the emitted-method audit beside it, and the guard there says why: that rule
  // skips a pair sharing an ORIGIN, because one duplicate COLUMN NAME collides at every member of a
  // family at once and reporting it five times would bury the rule that broke. Two fields renamed
  // onto one accessor share exactly that origin — one column ident, one `Member::Borrow` — so the
  // audit steps over them and this pass is what is left. Without it the refusal is rustc's `E0592`,
  // inside an expansion, naming neither declaration that asked for it.
  for backend in &backends {
    let mut taken: Vec<&GraphqlField> = Vec::new();
    for field in backend.fields() {
      let name = &field.input.name;
      if let Some(first) = taken
        .iter()
        .find(|first| first.input.name.external() == name.external())
      {
        errors.push(collision(
          backend,
          "input",
          name.safe(),
          first,
          field,
          &format!("one field called `{name}`"),
        ));
      }
      taken.push(field);
    }

    let mut taken: Vec<&GraphqlField> = Vec::new();
    for field in backend.fields() {
      let name = &field.output.name;
      if let Some(first) = taken
        .iter()
        .find(|first| first.output.name.external() == name.external())
      {
        errors.push(collision(
          backend,
          "output",
          name.safe(),
          first,
          field,
          &format!("one field called `{name}`"),
        ));
      }
      taken.push(field);
    }

    let mut taken: Vec<&GraphqlField> = Vec::new();
    for field in backend.fields() {
      let named = field.accessor();
      if let Some(first) = taken.iter().find(|first| first.accessor() == named) {
        errors.push(syn::Error::new_spanned(
          named,
          format!(
            "the output object would read `{first}` and `{second}` through one accessor, \
             `{named}_ref` — a `field = \"…\"` names what the object CALLS a field in Rust, and two \
             of them cannot name one method. The MEMBERS behind them are the domain names and do \
             not collide; the schema names are a third axis again.",
            first = first.source,
            second = field.source,
          ),
        ));
      }
      taken.push(field);
    }
  }

  Some(Graphql {
    backends,
    input,
    output,
    key_output,
    key_object,
    key_argument,
    filter,
    // The declaration's own word, VERBATIM. Its validity as a GraphQL name was settled where the
    // literal was read, at the literal's own span; what it MEANS — whether the language needed
    // correcting at all — is settled against the published name, which only the assembled model
    // knows.
    plural: block.plural.as_ref().map(syn::LitStr::value),
    connection,
    edge,
    skipped,
  })
}

/// The refusal two fields colliding in ONE schema position get.
///
/// Spanned at `at`, which is the LATER field's own name in that position: a [`RustSafeName`] built
/// from a `rename` literal carries that literal's span, and one built from the field's own ident
/// carries the field's — so the report lands on something the author wrote either way.
///
/// `why` is the caller's, because the two positions collide for different reasons and the sentence
/// has to say which.
fn collision(
  backend: &GraphqlBackend,
  position: &str,
  at: &syn::Ident,
  first: &GraphqlField,
  second: &GraphqlField,
  why: &str,
) -> syn::Error {
  syn::Error::new_spanned(
    at,
    format!(
      "the `{backend}` face would expose `{first}` and `{second}` in its {position} as {why}. \
       Within one schema type every field needs its own name.",
      backend = backend.kind().as_str(),
      first = first.source,
      second = second.source,
    ),
  )
}

/// What the ORDER-BY type is called: `graphql(order_by(rename = "…"))` where one was written, and
/// `<Base>OrderBy` otherwise — where the base is `graphql(rename = "…")` if the block gave one and
/// the record's own name if it did not.
///
/// Read off the BLOCK rather than off the settled wire face, because the two no longer stand
/// together: the type is emitted beside the comparison and a record with no `graphql(…)` still has
/// one. The base follows the block where a block exists, so a record that renames its wire family
/// renames this with it and nothing about a spelled declaration moves.
///
/// `from_ident` rather than `new`, as the wire names use: a type name is Rust, and `new`'s
/// field-oriented mangling would snake_case it.
fn order_by_name(record: &syn::Ident, block: Option<&GraphqlBlock>) -> RustSafeName {
  let base = block
    .and_then(|block| block.rename.clone())
    .unwrap_or_else(|| record.clone());
  let named = block
    .and_then(|block| block.order_by.clone())
    .unwrap_or_else(|| default_order_by_name(&base));
  RustSafeName::from_ident(&named)
}

/// Every type this declaration emits into its own scope, and the rule that no two may share a name.
///
/// ONE pass over the WHOLE set rather than a check per category, which is what makes the interesting
/// collisions reachable at all: a row renamed onto the filter's name, a comparison onto the key's, a
/// wire type onto another database's row. Per-category checks could not see across, and a rename
/// onto another type's DEFAULT is the same comparison as a rename onto another rename — a defaulted
/// type's name is simply the name it has.
///
/// WHICH types those are is not listed here. It is [`RecordModel::emitted_types`], for the reason
/// [`emitted_methods`] asks the same crate what a method is called: a list kept on this side would
/// be a second copy of what the emitter writes, and two copies of such a list is how one of them
/// drifts. That half is pinned against the emission itself, by `ingraph-codegen`'s
/// `the_enumeration_names_exactly_the_types_the_emission_declares`.
fn emitted_names(model: &RecordModel, errors: &mut Errors) {
  let named = |declared: Declared| (declared.name, declared.role.to_string());
  let mut declared = model.emitted_types().into_iter();
  // The RECORD is in the list, so a rename onto it reports like any other clash. It is placed after
  // the key so a message about it names the record as the thing already spoken for — and it is
  // added HERE because no emission declares it: it is the declarer's own type, already standing in
  // the scope the emitted ones land in.
  let key = declared.next().expect("an emission declares a key type");
  let mut emitted: Vec<(syn::Ident, String)> = vec![
    named(key),
    (model.record.clone(), "the record's own name".to_owned()),
  ];
  emitted.extend(declared.map(named));

  let mut taken: Vec<&(syn::Ident, String)> = Vec::new();
  for candidate in &emitted {
    if let Some(first) = taken.iter().find(|(name, _)| *name == candidate.0) {
      errors.push(syn::Error::new(
        candidate.0.span(),
        format!(
          "{second} would be named `{name}`, which is already {first} — one declaration emits each \
           of its types into the same scope, so every one needs its own name",
          second = candidate.1,
          name = candidate.0,
          first = first.1,
        ),
      ));
    }
    taken.push(candidate);
  }
}

/// Every METHOD this declaration emits, and the rule that no two on ONE type may share a name.
///
/// [`emitted_names`] one level down: that pass is about the TYPES a declaration emits into its
/// scope, this one about the methods each of those types declares. A column's name reaches an
/// emitted method through five derived shapes — `x`, `x_ref`, `x_slice`, `set_x`, `with_x` — and
/// nothing keeps them clear of each other or of the fixed `new`. A `copy` column called `new`
/// takes its address type's constructor; a `copy` column called `set_x` beside a column called
/// `x` takes that column's setter; and a column called `x_ref` beside one called `set_x` collides
/// at `set_x_ref` with no marker involved at all.
///
/// Each is `E0592` rather than anything silent, so what this buys is not a caught bug but a MOVED
/// error: rustc reports the duplicate at `#[ingraph::record(…)]`, a span the author cannot edit, and
/// its message never names the column.
///
/// The shapes are NOT listed here. They are `ingraph-codegen`'s, asked for through
/// [`RecordModel::emitted_methods`], because 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 — the
/// same reason [`crate::column`]'s fence is a namespace. What that shared function cannot cover is
/// which names a given type declares, and that half is pinned against the emission itself, by
/// `ingraph-codegen`'s `the_enumeration_names_exactly_the_methods_the_emission_declares`.
///
/// The name checked is the one the EMITTER uses, which differs by type and is why the question is
/// asked of the model rather than of the fields: the record's own impl keeps its Rust field names,
/// while a row, a comparison and a wire face take the column's effective name — so a
/// `<db>(rename)` or a `graphql(<backend>(input(rename)))` moves the methods with it, and
/// a check on the Rust name would miss every collision a rename opens.
fn emitted_methods(model: &RecordModel, errors: &mut Errors) {
  let emitted = model.emitted_methods();
  let mut taken: Vec<&Emitted> = Vec::new();
  for candidate in &emitted {
    // Two methods of one ORIGIN are a duplicate column NAME, which has a refusal of its own — and
    // one of those collides at every member of the family at once, so reporting it here would bury
    // the rule that was actually broken under five restatements of it. This rule is about two
    // DIFFERENT columns meeting.
    if let Some(first) = taken.iter().find(|earlier| {
      earlier.owner == candidate.owner
        && earlier.name == candidate.name
        && earlier.origin != candidate.origin
    }) {
      let why = format!(
        "`{owner}` would declare `{name}` twice — {first}, and {second} — and rustc reports that \
         duplicate inside the expansion, where nothing names the column that caused it. Rename \
         the column.",
        owner = candidate.owner_name,
        name = candidate.name,
        first = first.origin,
        second = candidate.origin,
      );
      // At the DECLARED token, which a method's own ident is not: the emitter builds one through
      // `format_ident!`, whose span is the call site — the very span `E0592` already reports at.
      errors.push(
        match candidate.origin.column().or_else(|| first.origin.column()) {
          Some(at) => syn::Error::new_spanned(at, why),
          None => syn::Error::new_spanned(&candidate.owner_name, why),
        },
      );
    }
    taken.push(candidate);
  }
}

/// The PLURAL the pluraliser could not make — a page that would be published under the single's own
/// name, with nothing in the declaration saying so.
///
/// [`emitted_names`] one axis over: that rule is about the TYPES a declaration puts in a scope, this
/// one about the ROOT FIELDS it puts in a schema. The fact is
/// [`RecordModel::degenerate_plural`](ingraph_codegen::model::RecordModel::degenerate_plural)'s —
/// which words have no distinct plural is the emitter's business, and the emitter is where the
/// pluraliser lives — and the SENTENCE is this crate's, like every other refusal a declarer reads.
///
/// # Why it has to be here rather than downstream
///
/// Nothing later would say a word. Measured against async-graphql 7.2.1: two fields of one object
/// sharing a name build a schema without an error, the SDL carries the LAST registration and the
/// resolver answers from the FIRST — so a client reads `media: MediaConnection!` and receives a
/// single `Media`. No compile error, no schema-build error, no query error; just an answer of the
/// wrong shape, forever.
///
/// # What the sentence has to do
///
/// Teach the word. A declarer who reads *`Media` has no plural* and is not told what to write next
/// has been refused without being helped, so the message names the entry, spells it, and says what
/// it is: the entity's plural, not this field's name — because the next reader of that word (a
/// connection, an aggregate) inherits the same correction.
fn derived_plural(model: &RecordModel, errors: &mut Errors) {
  let Some(field) = model.degenerate_plural() else {
    return;
  };
  errors.push(syn::Error::new(
    model.record.span(),
    format!(
      "`{record}`'s page would be published as `{field}`, which is what its single field is already \
       called: the plural derived from the published name is the word itself. Write the plural — \
       `graphql(plural = \"…\")` — which declares this entity's PLURAL rather than this field's \
       name, so every later reader of it inherits the correction. Nothing downstream refuses this: \
       two root fields of one name build a schema whose SDL carries one of them and whose resolver \
       answers from the other.",
      record = model.record,
    ),
  ));
}

/// A declared name, with the literal's own span so a refusal about it points at the declaration.
fn literal_name(literal: &syn::LitStr) -> RustSafeName {
  RustSafeName::new(literal.value(), literal.span())
}

/// The declared databases, as a sentence names them.
fn list(declared: &[DatabaseKind]) -> String {
  declared
    .iter()
    .map(|kind| format!("`{}`", kind.as_str()))
    .collect::<Vec<_>>()
    .join(", ")
}

/// Nodes are concrete. A parameter is refused rather than half-handled: a key column's type is
/// read straight off the declaration, and a type parameter has no type until it is substituted.
fn concrete(generics: &syn::Generics, kind: NodeKind, errors: &mut Errors) {
  let why = format!(
    "generic {plural} are not supported — {article} {noun} must be concrete, because a key \
     column's type is read straight off the declaration",
    plural = kind.plural(),
    article = kind.article(),
    noun = kind.noun(),
  );
  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 node may take, since both markers name
/// FIELDS.
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 — `#[ingraph(id)]` and \
           `lineage(fields(…))` both name fields",
          article = kind.article(),
          noun = kind.noun(),
        ),
      )),
    },
    syn::Data::Enum(_) | syn::Data::Union(_) => Err(syn::Error::new_spanned(
      &input.ident,
      format!(
        "`#[ingraph::{macro_name}]` supports structs only",
        macro_name = kind.as_str()
      ),
    )),
  }
}

/// What a STANDALONE derive reads off ONE field — the same grammar the record takes, through the
/// same reader, projected onto what the three faces spend.
///
/// The projection is what keeps the vocabulary TOTAL without a second grammar existing:
/// [`field_markers`] is the one reader, so a word the record accepts is a word a bare derive
/// accepts, and the only thing this type adds is a list of the words that reach no face — carried
/// with their spans so the bare door can refuse each BY NAME rather than by silence.
pub(crate) struct StandaloneField {
  /// The interpretation word this field's type is read under, if one was written.
  pub(crate) marker: Option<Marker>,
  /// `graphql(type = "…")` — the ONE wire form, which is what the FILTER is projected from.
  pub(crate) wire: Option<syn::Type>,
  /// `rename = "…"` — what a doc sentence calls this column.
  pub(crate) rename: Option<syn::LitStr>,
  /// One entry per database block written on this field, in written order.
  pub(crate) per_db: Vec<StandaloneDatabaseField>,
  /// The words the record takes that reach NO face here — each with the token that wrote it, so the
  /// refusal names the word and points at it.
  pub(crate) beyond: Vec<(&'static str, syn::Path)>,
  /// The CONVERSION legs written anywhere on this field — the words the container's hook governs.
  pub(crate) conversions: Vec<(&'static str, syn::Path)>,
}

/// One database's refinement of one standalone column.
pub(crate) struct StandaloneDatabaseField {
  /// Which database.
  pub(crate) kind: DatabaseKind,
  /// The block's own token — the span a refusal about this column-in-this-database reports at.
  pub(crate) at: syn::Path,
  /// `type = "…"` — what this database stores, when it is not the domain type.
  pub(crate) stored: Option<syn::Type>,
  /// `flatten` — the comparison occupies more than one column.
  pub(crate) flatten: bool,
}

/// Read one field's markers for a standalone derive.
///
/// The reader is the RECORD's, so this function chooses nothing about the grammar: what it does is
/// sort the answer into what the three faces read and what they do not.
pub(crate) fn standalone_field(attrs: &[syn::Attribute], errors: &mut Errors) -> StandaloneField {
  let markers = field_markers(attrs, NodeKind::Record, errors);
  let Markers {
    id,
    copy,
    repeated,
    optional,
    key,
    lineage,
    storage,
    graphql,
    label,
    reference,
    build,
    ..
  } = markers;

  // The words that reach no face here. Each is a fact about a RECORD — an identity, an address
  // segment, an accessor's projection, a relation — and a bare struct declares none of those, so a
  // door that took them silently would be taking a word it does not spend.
  let mut beyond = Vec::new();
  let mut carry = |word: &'static str, at: Option<syn::Path>| {
    if let Some(at) = at {
      beyond.push((word, at));
    }
  };
  carry("id", id);
  carry("copy", copy);
  carry("repeated", repeated);
  carry("optional", optional);
  carry("key", key.map(|rename| rename.at));
  carry("lineage", lineage.map(|rename| rename.at));
  carry("ref", reference);
  // The COLLECTION's storage word, for the same reason: it mirrors a stored order into a companion
  // column beside a row, and a bare struct has no row for one to sit beside.
  carry(SORTABLE, storage.sortable.clone());
  // The COLLECTION's ACCESS word, for the same reason one line up: it puts a second index on the
  // table a collection's elements are rows of, and a bare struct declares no such table.
  carry(INDEXED, storage.indexed.clone());
  // The CONSTRUCTION seat, for the same reason as the rest: a bare struct is built by whoever
  // declared it, so there is no call sequence here for the word to describe — and a word this door
  // does not spend is one its author believes they declared.
  carry(crate::construct::WORD, build.and_then(|written| written.at));

  let mut conversions = Vec::new();
  let mut per_db = Vec::new();
  let rename = storage.rename.clone();
  {
    for database in storage.per_db {
      let FieldDatabase {
        kind,
        at,
        indexed,
        unique,
        copy,
        edge,
        flatten,
        stored,
        from,
        into,
        ..
      } = database;
      // The per-database words that decide a STORAGE LAYOUT rather than a comparison's shape. They
      // are the record's to spend — there is no table here to index, no row to copy out of, and no
      // second table an edge could live in — so each refuses by name beside the ones above.
      carry("indexed", indexed);
      carry("unique", unique);
      carry("copy", copy);
      carry("edge", edge);
      for (word, spec) in [("from", &from), ("into", &into)] {
        if let Some(named) = spec.infallible.as_ref() {
          conversions.push((word, named.at.clone()));
        }
        if let Some(named) = spec.fallible.as_ref() {
          conversions.push((
            if word == "from" {
              "try_from"
            } else {
              "try_into"
            },
            named.at.clone(),
          ));
        }
      }
      per_db.push(StandaloneDatabaseField {
        kind,
        at,
        stored,
        // Either spelling: the field's own dialect-free word speaks to every database it names, and
        // a database's own block speaks to that one.
        flatten: flatten.is_some() || storage.flatten.is_some(),
      });
    }
  }

  let wire = graphql.as_ref().and_then(|field| field.ty.clone());
  if let Some(graphql) = graphql {
    // The WIRE legs carry no span of their own — a `WireLeg` is a database and a conversion — so the
    // refusal points at the `graphql(…)` marker that holds them. It is the token an author would go
    // to anyway: the leg is written inside it and nowhere else.
    if !graphql.output.is_empty() {
      conversions.push(("graphql(output(…))", graphql.at.clone()));
    }
    if !graphql.comparison.is_empty() {
      conversions.push(("graphql(input(comparison(…)))", graphql.at.clone()));
    }
  }

  StandaloneField {
    marker: label.as_ref().map(Written::marker),
    wire,
    rename,
    per_db,
    beyond,
    conversions,
  }
}

#[cfg(test)]
mod channel_tests;
#[cfg(test)]
mod key_faces_tests;
#[cfg(test)]
mod light_tests;
#[cfg(test)]
mod lineage_source_tests;
#[cfg(test)]
mod options_tests;
#[cfg(test)]
mod output_field_tests;
#[cfg(test)]
mod receipt_tests;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod tracing_tests;