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
//! The FIELD-FRAGMENT TIER's acceptance: what a fragment may say, and every family it may not
//! claim.
//!
//! ```text
//! #[ingraph(record(sqlite, postgres), entity, graphql(rename = "…"), crate = "…", remote = "…")]
//! ```
//!
//! # ACTIVATION FIRST, because a fragment answers whoever holds it
//!
//! A fragment is 公用字段抽取 — a group of fields several declarations hold, written once — so it is
//! HELD by whatever declares it, and what it has to ANSWER is whatever the holding kind asks. The two
//! kinds ask different things: a record asks for a width, a bind, a read and a comparison; an entity
//! holds no rows and asks for none of them. So the declaration says which kinds may consume it, and
//! one that says NEITHER is a named refusal — `record[(<db>, …)]`, `entity`, or both, with no
//! shorthand for the pair.
//!
//! `graphql[(…)]` is a third word and not a host kind: it says the declaration has a face a client
//! can reach at all. Without it a fragment is a storage-only value, which is a shape the tier could
//! not express while every declaration published whether anything asked or not.
//!
//! Every block a NODE writes still describes something a fragment does not have: no key, because a
//! fragment bears no identity; no rows, no table, no index and no artifact family, because its
//! columns are the HOLDER's; and no wire ROOT, its presence there being a fragment of whatever holds
//! it. Each of those is refused BY THAT REASON rather than as an unknown word — an author who wrote
//! one has a concrete idea, and the useful answer is which declaration carries it.
//!
//! The word is `fields` because that is the whole of what the tier declares. It used to be spelled
//! `entity`, and the rename is the LADDER's: `entity` now names the identity-bearing node one rung
//! up, which is what the word always meant everywhere else in this framework — the entity binding,
//! a hit's `entity` field, `TypedId`'s entity marker. The tier's own doc confessed the mismatch in
//! as many words (*no stable identity is what the tier means*), and a tier whose name contradicts
//! its meaning is a word every reader has to translate.
//!
//! `crate = "…"` stays because the expansion spends it: a `Vec<_>` field is handed back through
//! `project::Repeated` and an `Option<_>` through `project::Optional`, so a re-export shim has the
//! same say here it has everywhere else.
//!
//! # `remote = "…"` — the tier's second word, and the FOURTH declaration to take it
//!
//! It makes the declaration a transparent wrapper over a type another crate owns, and it earns its
//! place here by the same test every rung is measured by: what a wrapper is FOR is giving a foreign
//! type this framework's faces, and this tier has four to give — the width, the filter, the
//! comparison and the wire object. A `mediaframe::Dimensions` an application cannot implement a
//! trait for is then held by a record exactly as a declared fragment is.
//!
//! What the word does NOT bring is an identity seat, and that is the whole of the difference from
//! the rungs above. A record's rewrite reads an id column BY REFERENCE — this framework's identity
//! seats borrow — and a fragment has no id; the `id` marker stays refused by the tier's own
//! definition, so a manifest here is a list of equal columns and the emission reads every one of
//! them by value.
//!
//! Two rules about ATTRIBUTES come with the mode, both [`crate::remote`]'s and neither restated
//! here: the macro OWNS the wrapper's `#[repr(…)]`, and a manifest field carries no attribute that
//! has nowhere to land. They are checked only when the word is present, a declaration that wrote no
//! `remote` keeping its own item.
//!
//! # THE SADDLE NAMESPACES at a field, and what is still waiting
//!
//! What a field says to a HOST KIND goes inside that kind's own namespace, which is what keeps one
//! ident from meaning two things at two seats: `record(skip)`, `record(flatten)` and the per-dialect
//! claims are the record field seat's own words, letter for letter one level in, and
//! `graphql(rename = "…")` is what a client calls the field.
//!
//! The ruling is that a fragment's fields carry the FULL field grammar — labels, storage legs, wire
//! legs — declared once and inherited by every holder. What reads that inheritance does not exist,
//! and a grammar parsed into a model nothing spends is a promise the next author would have to keep.
//! So a word is admitted only where THIS emission spends it, and every other is a NAMED refuse-until
//! that says what it is waiting for.
//!
//! What a holder may already say is a NAMING act rather than a divergence, and the distinction is
//! the ①′ amendment: composition is stated by the bare TYPE POSITION — a field whose type holds
//! several values is stored as those values, prefixed with the field's own name — and the holder's
//! own `<db>(flatten)` only decides whether that prefix is dropped in that one database. It diverges
//! nothing a fragment declared; a per-segment override, which would, is refused there by name.
//!
//! # NESTING, and the one field word the tier admits for it
//!
//! A fragment holds a fragment by the same bare TYPE POSITION, and everything that follows is the
//! existing laws recursing: the width descends because each segment is its own field's type
//! answering, the filter slot is the inner's filter, the comparison is applied one segment further
//! down, and the decode raises the inner before the outer's construction sees it. None of that is a
//! word.
//!
//! ONE decision is not free, and it is the same one a holder makes: whether the inner mount lends
//! its name. `record(flatten)` is that word, written WITHOUT a database because the layout a fragment
//! publishes is a single `ColumnKind::SEGMENTS` carrying no dialect. It is not an early instalment of
//! the inherited grammar: what a holder inherits is what a fragment says about its FIELDS, and this
//! says nothing about one. It says how the fragment's own column list is laid out, which is a fact
//! the TYPE already publishes and no holder could restate.
//!
//! A cycle is the shape nesting makes reachable, and it is refused: `A` holding `A` here, and `A`
//! through `B` back to `A` by the two `SEGMENTS` consts requiring each other.

use ingraph_codegen::{
  construct::{Build, Construction},
  delegate::Delegate,
  fields::{BuiltFor, Derived, FieldsModel, FragmentField, RecordHost, WireFace},
  name::RustSafeName,
  prelude::*,
};

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

#[cfg(test)]
mod tests;

/// What each STORE WORD is told — one sentence over five entries, because the mistake is one
/// mistake and only the word that spelled it differs.
const STORED_NOWHERE: &str = "a field fragment is stored in no table of its own — its columns are \
                              the HOLDER's row, which is what the holder's own store words name. A \
                              dialect at THIS head is a different claim and has a seat of its own: \
                              `record(sqlite)` names a dialect this fragment is BUILT for, without \
                              claiming a table in it";

/// WHY a fragment claims none of the families — the ruling every one of these refusals shares, so
/// the reason cannot drift between them.
///
/// It names BOTH rungs above it, because the ladder has two and the useful answer says which: a
/// group of fields that bears an identity is an `entity`, and one that bears an identity AND holds
/// rows is a `record`.
const A_FRAGMENT_IS_HELD: &str = "A field fragment is HELD by whatever declares it, so its \
                                 identity, its storage and its place on the wire are all its \
                                 holder's. A group of fields that bears an identity of its own is \
                                 an `entity`, and one that holds rows besides is a `record`.";

/// Validate a decorated declaration into the model the emitter consumes.
///
/// # Errors
/// A [`syn::Error`] carrying EVERY rule the pass could still see violated, each spanned at the
/// token that violated it, so one compile reports the whole declaration's problems.
pub(crate) fn parse(
  input: &syn::DeriveInput,
  arguments: &[syn::Attribute],
) -> syn::Result<FieldsModel> {
  let fragment = &input.ident;
  let mut errors = Errors::default();
  crate::host::refuse_a_moved_option_block(&input.attrs, &mut errors);
  let Declared {
    krate,
    remote,
    record,
    entity,
    wire,
    construction,
    cursor,
    filter,
    delegates,
  } = options(arguments, &mut errors);
  refuse_a_fragment_no_kind_can_hold(fragment, record.as_ref(), entity.as_ref(), &mut errors);
  let activated = Activated {
    record: record.as_ref(),
    wire: wire.is_some(),
  };
  refuse_a_position_no_kind_stores(record.as_ref(), cursor.as_ref(), &mut errors);
  concrete(&input.generics, &mut errors);
  // THE MACRO OWNS THE REPRESENTATION of a wrapper, and it owns it here for the reason it owns it
  // one rung up: `#[repr(transparent)]` is the premise the reference family stands on, so an
  // author's own is refused at the token that wrote it rather than overwritten in silence.
  if remote.is_some() {
    crate::remote::refuse_a_representation(&input.attrs, &mut errors);
  }

  let fields = match named_fields(input) {
    Ok(fields) => fields,
    Err(terminal) => return Err(errors.seal(terminal)),
  };
  if fields.named.is_empty() {
    errors.push(syn::Error::new_spanned(
      fragment,
      "a field fragment with no fields extracts nothing — the tier exists to declare the fields \
       several types hold, so a declaration with none has nothing for a holder to inherit",
    ));
  }

  // The DEFAULT namespace and no other, which is not a shortcut: a fragment declares no storage, so
  // it does not know which record flattens its columns or what THAT declaration's databases mint in.
  // What it can be held to is the namespace every one of them starts from.
  let fence = alias::Fence::default();
  let columns: Vec<FragmentField> = fields
    .named
    .iter()
    .filter_map(|field| {
      let name = field.ident.clone()?;
      column::refuse_framework_namespace(&fence, &name, &mut errors);
      // A MANIFEST FIELD HAS NO REAL BODY, so an attribute with nowhere to land is refused by name
      // rather than swallowed by the rewrite. Doc comments migrate to the reader below; the
      // condition words are read where a record's are.
      if remote.is_some() {
        crate::remote::refuse_an_unplaceable_attribute(field, &mut errors);
      }
      let mut written = Marked::default();
      let project = markers(&field.attrs, &name, &activated, &mut written, &mut errors);
      let Marked {
        build,
        stored,
        wire_name,
      } = written;
      refuse_a_dialect_the_layout_cannot_carry(&name, record.as_ref(), &stored, &mut errors);
      refuse_a_skipped_position(&name, cursor.as_ref(), &stored, &mut errors);
      refuse_a_column_derived_off_a_field_that_has_none(&name, &stored, &mut errors);
      refuse_a_transform_with_nothing_to_transform(&name, &stored, &mut errors);
      crate::construct::refuse_a_whole_non_option(
        matches!(project, Projection::Optional),
        build.as_ref(),
        &mut errors,
      );
      refuse_a_cycle(fragment, &name, &field.ty, &mut errors);
      // THE ONE THING THE SEAT CANNOT HONOUR. Every other artifact a field mints here contracts with
      // it; a cursor KEY does not contract, because the key is the whole declared order and a
      // shorter one is a different order rather than a smaller key.
      if cursor.is_some() {
        attribute::refuse_a_conditional_position(field, &mut errors);
      }
      Some(FragmentField {
        flatten: stored.flatten.is_some(),
        // WHAT THIS COLUMN IS CALLED where it is stored — `record(rename = "…")`, or the field's own
        // name where nothing moved it. Resolved HERE rather than at the emission, so the names const
        // and the shape that reads it cannot come to disagree about which axis they carry.
        stored_name: stored.rename.as_ref().map(syn::LitStr::value),
        skip: stored.skip.as_ref().map(SkipField::fill),
        // THE COLUMNS THE WRITE COMPUTES, in the order they were written — resolved here for
        // `stored_name`'s own reason, so the names const, the shape that reads it and the filter
        // slot named after it cannot come to disagree about which string this column is.
        derived: stored
          .derived
          .iter()
          .map(|one| Derived {
            column: RustSafeName::new(one.column.value(), one.column.span()),
            from: one.from.clone(),
            ty: one.ty.clone(),
          })
          .collect(),
        // THE TWO PATHS ACROSS THE STORAGE BOUNDARY. The word's own span stays behind at the front
        // end where the refusals about it are written; what the emission needs is the FUNCTION, and
        // its span is the literal's, so a signature that disagrees reports at the string the author
        // wrote rather than at the word above it.
        write: stored.write.as_ref().map(|one| one.path.clone()),
        read: stored.read.as_ref().map(|one| one.path.clone()),
        column: Column {
          project,
          ty: field.ty.clone(),
          source: name.clone(),
          name,
        },
        // Carried in BOTH modes, and spent in one. An ordinary fragment keeps its fields, so its
        // documentation stays where the author wrote it and nothing reads this; a rewrite deletes
        // them, and the reader is where the field's question is still askable.
        docs: crate::remote::docs(field),
        // THE CONDITION, read by the family's own reader rather than by a copy here — which is what
        // makes `remote::refuse_an_unplaceable_attribute`'s promise true at this tier: a `cfg` here
        // takes the accessor, the segment, the bind, the read, the filter seat and the place on the
        // wire face, all together. `rewrite` decides whether the decorations are KEPT: an echoed
        // field carries its own, and a deleted one has them ride its reader.
        condition: attribute::condition(field, remote.is_some(), &mut errors),
        wire_name: wire_name.map(|spelled: syn::LitStr| spelled.value()),
        build: build.unwrap_or_default(),
      })
    })
    .collect();

  // A DERIVED NAME IS A COLUMN NAME, so it is held against every other one this fragment publishes
  // — which is a question about the WHOLE field list and therefore asked here rather than per field.
  refuse_a_derived_name_a_column_already_has(&columns, &mut errors);

  // THE CONSTRUCTION WORDS, checked exactly where the record rung checks them and by the same three
  // functions — the suite is one facility, and a second reading of its rules is how two mounts come
  // to disagree about what `finish_arg` needs.
  crate::construct::refuse_without_a_remote(
    remote.as_ref(),
    construction
      .as_ref()
      .and_then(|written| written.at.as_ref()),
    columns.iter().filter_map(|field| field.build.at.clone()),
    "field fragment",
    &mut errors,
  );
  let construction = construction.unwrap_or_default();
  let described: Vec<(syn::Ident, Build)> = columns
    .iter()
    .map(|field| (field.column.source.clone(), field.build.clone()))
    .collect();
  crate::construct::refuse_a_homeless_argument(&construction, &described, &mut errors);
  refuse_an_own_entry_that_publishes_nothing(remote.as_ref(), &delegates, &mut errors);
  refuse_a_word_that_suppresses_nothing(remote.as_ref(), &delegates, &mut errors);
  refuse_a_lifted_entry_without_a_face(&delegates, wire.is_some(), &mut errors);
  refuse_a_codec_with_no_position(record.as_ref(), cursor.as_ref(), &mut errors);
  let cursor = cursor.map(|written| key(&written, &columns, &mut errors));

  let model = FieldsModel {
    fragment: fragment.clone(),
    vis: input.vis.clone(),
    krate,
    remote,
    record: record.map(|written| RecordHost {
      databases: written
        .databases
        .into_iter()
        // The word's own span stays behind at the front end, where the refusals about the ENTRY are
        // written; what the emission needs is the kind and whatever was mounted at it, and a mounted
        // path carries the literal's span so a type that fails its audit reports at the string the
        // author wrote.
        .map(|one| BuiltFor {
          kind: one.kind,
          comparison: one.mounted.comparison,
          cursor: one.mounted.cursor.map(|codec| codec.path),
        })
        .collect(),
      // THE WHOLE-VALUE PATHS, carried the same way a field's are one level down: the WORD's span
      // stays here where the refusals about it are written, and what crosses is the FUNCTION, whose
      // span is the literal's — so a signature that disagrees reports at the string the author
      // wrote rather than at the word above it.
      write: written.write.map(|one| one.path),
      read: written.read.map(|one| one.path),
    }),
    entity: entity.is_some(),
    wire,
    fields: columns,
    construction,
    cursor,
    filter,
    delegates,
  };
  emitted_methods(&model, &mut errors);
  refuse_a_published_collision(&model, &mut errors);
  refuse_an_absent_position(&model, &mut errors);
  refuse_a_fallible_position(&model, &mut errors);
  errors.into_result(model)
}

/// **A FRAGMENT NO HOST KIND CAN CONSUME**, refused at the declaration that activated neither.
///
/// # Why the activation is required rather than defaulted
///
/// A fragment is HELD, and what it has to ANSWER is whatever the holding kind asks. The two kinds
/// ask different things: a record asks for a width, a bind, a read and a comparison; an entity holds
/// no rows and asks for none of them. Emitting both sets for every declaration answered questions no
/// holder had asked — and the storage half is the expensive one, being what puts an `sqlx`-shaped
/// obligation on a fragment nobody stores.
///
/// A DEFAULT would have to pick, and either pick is wrong somewhere: defaulting to `record` charges
/// the value tier for a face it may never be asked for, and defaulting to `entity` drops the storage
/// face out from under a corpus that had it. So the declaration says, and one that says nothing is
/// told what the two words buy.
///
/// There is no shorthand for BOTH — write both — and that is the vocabulary-admission bar rather
/// than terseness: a word whose whole content is a count goes stale the day a third kind arrives.
fn refuse_a_fragment_no_kind_can_hold(
  fragment: &syn::Ident,
  record: Option<&RecordActivation>,
  entity: Option<&syn::Path>,
  errors: &mut Errors,
) {
  if record.is_some() || entity.is_some() {
    return;
  }
  errors.push(syn::Error::new_spanned(
    fragment,
    format!(
      "`{fragment}` activates no host kind, so no declaration can consume it — a fragment is HELD, \
       and WHICH faces it answers with is decided by the kind that holds it. Write \
       `record[(<db>, …)]` to be held by the rung that stores rows, which is what the width, the \
       bind, the read and the comparison are for; write `entity` to be held by the rung that bears \
       an identity and no rows, which asks for the predicate alone. Write BOTH where both hold it — \
       there is no one word for the pair. The accessor family is the tier's own and is emitted \
       either way."
    ),
  ));
}

/// **A PAGING POSITION IS A STORED ORDER**, so `cursor` on a fragment no record may hold is refused.
///
/// The word asserts that this declaration's order is the one legitimate total order over its value,
/// and what SPENDS that assertion is the keyset: a `CursorValue` row written and read as bytes, and a
/// SQL comparison that resumes strictly after a boundary. Both are the record host's. On a fragment
/// that activated `entity` alone there is no statement to page and no row to resume from, so the
/// word would be an assertion with no reader — which this grammar refuses rather than parses.
fn refuse_a_position_no_kind_stores(
  record: Option<&RecordActivation>,
  cursor: Option<&Cursor>,
  errors: &mut Errors,
) {
  let (None, Some(written)) = (record, cursor) else {
    return;
  };
  errors.push(syn::Error::new_spanned(
    &written.at,
    "`cursor` asserts a total order for PAGING, and paging is the record host's: the keyset writes \
     this value's members as cursor bytes and a statement resumes strictly after them, both of which \
     need rows to walk. This fragment activates no `record`, so the assertion has no reader — add \
     `record[(<db>, …)]` beside the word, or drop the word: a fragment without one is filtered and \
     read back exactly as before, and is simply not a paging position",
  ));
}

/// **A CODEC WRITES A POSITION'S BYTES**, so one mounted on a fragment that asserted no order is a
/// name on nothing.
///
/// `<db>(cursor = "…")` says *these bytes are how this value crosses the opaque boundary at this
/// store*, and what SPENDS that is the cursor row the head's own `cursor` word emits — one per
/// declared dialect where a codec was mounted anywhere, a single dialect-free one otherwise. A
/// fragment that wrote no such word gets NONE of them: the assertion an order needs was never made,
/// so the codec would be read by nobody. That is the same sentence a field's `graphql(rename = "…")`
/// earns on a fragment with no wire face, and for the same reason.
///
/// It is stated at the DIALECT's own word rather than at the head's absent one, because the token an
/// author deletes is the mount. The other repair is the other half of the sentence: writing `cursor`
/// at the head is what gives the mount a reader, and it is what the household that mounted a codec
/// almost certainly meant.
fn refuse_a_codec_with_no_position(
  record: Option<&RecordActivation>,
  cursor: Option<&Cursor>,
  errors: &mut Errors,
) {
  let (Some(host), None) = (record, cursor) else {
    return;
  };
  for (db, at) in host.databases.iter().filter_map(|one| {
    one
      .mounted
      .cursor
      .as_ref()
      .map(|codec| (one.kind.as_str(), &codec.at))
  }) {
    errors.push(syn::Error::new_spanned(
      at,
      format!(
        "`{db}(cursor = \"…\")` mounts the codec this fragment's PAGING BOUNDARY is written by at \
         `{db}`, and this fragment is no paging position — the rows a codec is spent at are the \
         cursor rows, and only the bare `cursor` word at the head emits any. So the mount has no \
         reader. Write `cursor` beside `record(…)` to assert that the order you declared these \
         fields in is the one legitimate total order over this value, or drop the mount: a fragment \
         without either is stored, filtered and read back exactly as before"
      ),
    ));
  }
}

/// **THE SEAT NAMES A METHOD REACHABLE ON `Self`, AND DOES NOT CARE WHERE IT CAME FROM** — so what
/// is refused here is an entry with no READER, never an entry's ORIGIN.
///
/// # The ruled letter: origin is method resolution's question
///
/// `delegate(fn …)` names a method reachable on `Self` — one the author wrote in an inherent `impl`,
/// one a wrapper reaches through its own `Deref`, one a trait in scope supplies. The word does not
/// ask which, because the generated call is method-resolution syntax and rustc answers: a name
/// nothing on `Self` answers to is `E0599` at that call, which is this family's honesty pattern
/// rather than a rule a macro could have checked. An earlier reading of this seat refused every
/// entry on a declaration that wrote no `remote`; that was a refusal by ORIGIN, and it is withdrawn.
///
/// # What DOES fork on the mode is the EMISSION, not the acceptance
///
/// A REWRITE mints a forwarding method — `fn m(&self) { (&self.0).m() }` — because the wrapped
/// value's method is otherwise reachable only through `Deref`, and an inherent one is what a caller
/// and a doc page see. An ORDINARY fragment already HAS the method: it is the author's own, on the
/// author's own `impl`. A same-named one emitted beside it would be that method calling itself, so
/// nothing is emitted, and the entry's whole content there is the LIFTED half — the field of the
/// object, whose body is `Self::m(self)` and whose resolution is the paragraph above.
///
/// So an entry that publishes nothing and mints nothing has no reader at all, and that is what this
/// refuses — the same law a `#[graphql]` naming no backend is refused under, one seat over.
///
/// # `on = self` puts a REWRITE's entry in exactly that position
///
/// The word waives the forwarding half, so a wrapping declaration's entry then buys what an ordinary
/// one's does and no more: the lifted field, or nothing. Two sentences under one predicate, because
/// the mistake is one mistake and only what silenced the mint differs — the mode on one side, the
/// author's own word on the other.
fn refuse_an_own_entry_that_publishes_nothing(
  remote: Option<&syn::Path>,
  delegates: &[Delegate],
  errors: &mut Errors,
) {
  const OFFER: &str = "Write `#[graphql(<backend>)]` on the entry to publish it, or drop the entry: \
                       the method is reached exactly as before either way";

  for delegate in delegates
    .iter()
    .filter(|entry| entry.wire.is_empty() && !mints_a_forwarding_half(remote, entry))
  {
    let method = &delegate.signature.ident;
    let why = if remote.is_some() {
      format!(
        "`{method}` publishes nothing and `on = self` waives its forwarding half, so the entry has \
         no reader. Without the word a plain entry earns its keep here — it mints the inherent \
         method a `Deref` would otherwise be needed for — and with it the method is already yours, \
         on your own `impl`, leaving the seat's whole content the wire field. {OFFER}"
      )
    } else {
      format!(
        "`{method}` publishes nothing and this fragment wraps nothing, so the entry has no reader. \
         On a declaration that WRAPS a type a plain entry earns its keep — it mints the inherent \
         forwarding method a `Deref` would otherwise be needed for. Here the method is already \
         yours, on your own `impl`, and the seat's whole content is putting it on the wire beside \
         the columns. {OFFER}"
      )
    };
    errors.push(syn::Error::new_spanned(method, why));
  }
}

/// Whether ONE entry mints the inherent forwarding method — the emission's own predicate, asked here
/// so a refusal about a reader cannot come to disagree with the reader.
///
/// Two conditions and they are independent: the declaration WRAPS something to forward onto, and the
/// entry did not waive the half with `on = self`.
fn mints_a_forwarding_half(remote: Option<&syn::Path>, delegate: &Delegate) -> bool {
  remote.is_some() && delegate.on_self.is_none()
}

/// **A WORD WITH NO MINT TO SUPPRESS**, refused at the token that wrote it.
///
/// `on = self` says *do not mint the forwarding half for this entry*, and the forwarding half is the
/// REWRITE mode's alone: a fragment that wraps nothing mints none to begin with, its entries'
/// methods being the author's already. So the word on such a declaration changes nothing at all —
/// the same expansion before it and after — and a word that changes nothing is one this grammar
/// refuses rather than parses.
///
/// The house law, at the seat one word over: `cursor` on a fragment no record may hold is refused
/// because the assertion has no reader, and a `delegate` entry that publishes nothing on a fragment
/// that wraps nothing is refused because the ENTRY has none. This is the third of the family and it
/// is about the PROPERTY, which is why it is separate: an entry that publishes IS read here, and
/// only the word beside it is not.
fn refuse_a_word_that_suppresses_nothing(
  remote: Option<&syn::Path>,
  delegates: &[Delegate],
  errors: &mut Errors,
) {
  if remote.is_some() {
    return;
  }
  for (delegate, at) in delegates
    .iter()
    .filter_map(|entry| entry.on_self.as_ref().map(|at| (entry, at)))
  {
    errors.push(syn::Error::new_spanned(
      at,
      format!(
        "`on = self` suppresses the FORWARDING method a wrapping declaration mints for `{method}`, \
         and this fragment wraps nothing — so there is no mint here for the word to suppress and \
         the expansion is the same with it and without. The method is the author's own already, \
         which is what an ordinary fragment's entry means: drop the property, and write the entry \
         in the shorthand the tier had before the word existed. `remote = \"…\"` at the head is \
         what gives this word something to say",
        method = delegate.signature.ident,
      ),
    ));
  }
}

/// **A LIFTED ENTRY IS A FIELD OF A FACE**, so publishing one on a fragment that declared no face is
/// a name on nothing.
///
/// `#[graphql(…)]` on an entry says *this method is also a field of the object*, and the object is
/// what the WIRE activation emits. A declaration that wrote none publishes neither the crossing nor
/// the `#[Object]` block, so the attribute would be read by nobody — which is the same sentence a
/// field's own `graphql(rename = "…")` earns one seat down, and for the same reason. The FORWARDING
/// half is untouched: a delegate with the attribute dropped is still the wrapped value's method,
/// reachable from Rust, which is what the refusal offers.
fn refuse_a_lifted_entry_without_a_face(
  delegates: &[Delegate],
  published: bool,
  errors: &mut Errors,
) {
  if published {
    return;
  }
  for delegate in delegates.iter().filter(|entry| !entry.wire.is_empty()) {
    errors.push(syn::Error::new_spanned(
      &delegate.signature.ident,
      format!(
        "`{method}` is published onto a wire face this fragment does not have — the tier publishes \
         nothing unless the declaration asks, so `#[graphql(…)]` here is a field of no object. \
         Write `graphql[(…)]` at the head to give this fragment a face, or drop the attribute: the \
         entry is still forwarded onto the wrapped value either way",
        method = delegate.signature.ident,
      ),
    ));
  }
}

/// **A FRAMED CURSOR HAS NO ERROR ROAD**, so a fallible construction protocol cannot be a paging
/// position on the road that raises.
///
/// `read_cursor` answers an [`Option`] — the codec's whole contract being *these bytes are this
/// type's encoding, or they are not* — and a `fallible` protocol hands the raise a `Result` whose
/// `Err` says something else entirely: *the bytes were right and the value they name is not one this
/// type admits*. There is nowhere in the answer to put that, and swallowing it would report a forged
/// cursor and a rejected value as one thing.
///
/// # The premise is the FRAMED body's, and the refusal is exactly that wide
///
/// The framed read walks the bytes back into one local per key column and then RAISES — the same
/// `remote::build` call a fetched row's assemble spends — so a `fallible` protocol puts a `?` on a
/// `Result` inside a function answering `Option`. A MOUNTED read does not raise at all: the codec
/// hands back a built `Self` and the emission applies only the head `read` mirror to it, so the
/// construction protocol is never consulted and a mounted decode's whole answer is the codec's own
/// [`None`] — which is the answer the trait asked for in the first place.
///
/// So a declaration whose EVERY declared dialect mounts a codec has no framed body left, and is
/// admitted. ANY unmounted dialect keeps the refusal: a dialect a declaration named and mounted
/// nothing at rides the framed default, mixed states being ordinary, and ONE framed row is enough to
/// need the road.
///
/// A declaration that named NO dialect is refused rather than admitted vacuously, which is what the
/// count below is for: the bare `record` word emits one DIALECT-FREE framed row, so there is nothing
/// there for a mount to have replaced.
///
/// The ROW's raise has the road, which is why the two directions differ: a decode may fail and its
/// error joins the one `persist(<db>(try_into(error = "…")))` already types. A framed cursor's may
/// not.
fn refuse_a_fallible_position(model: &FieldsModel, errors: &mut Errors) {
  if model.cursor.is_none() || !model.construction.fallible {
    return;
  }
  let declared = model
    .record
    .as_ref()
    .map_or(&[][..], |host| host.databases.as_slice());
  let unmounted: Vec<&str> = declared
    .iter()
    .filter(|built| built.cursor.is_none())
    .map(|built| built.kind.as_str())
    .collect();
  // EMPTINESS IS NOT THE EXEMPT STATE, which is why the count is asked beside the walk: a
  // declaration naming no dialect emits the dialect-free framed row, and `all` over nothing would
  // have admitted exactly the case with no mount in it.
  if !declared.is_empty() && unmounted.is_empty() {
    return;
  }
  let at = model
    .construction
    .at
    .as_ref()
    .expect("a parsed protocol keeps its word");
  // WHICH dialects are still framed, named where they exist — the author's next edit is at those
  // groups and nowhere else. The list is spelled without a count-sensitive verb, so one unmounted
  // dialect and three read alike.
  let framed = if unmounted.is_empty() {
    "This declaration names no dialect to mount one at, so the framed read is the only one it has"
      .to_owned()
  } else {
    format!(
      "No codec is mounted at `{}`, so the framed read — the one that raises — is what this \
       fragment still writes there",
      unmounted.join("`, `"),
    )
  };
  errors.push(syn::Error::new_spanned(
    at,
    format!(
      "`fallible` says the wrapped type's construction hands back a `Result`, and `cursor` says \
       this fragment is a paging position — a cursor's read answers `Some` or `None`, and there is \
       nowhere in that answer for an `Err`. Swallowing it would report a FORGED frame and a value \
       the remote rejected as one thing, which are the two states a cursor codec exists to tell \
       apart. Drop the `cursor` word, give the protocol an infallible terminal step, or mount a \
       codec at every dialect this fragment declares — a mounted read is the codec's own `Option` \
       from the bytes up and never raises through the protocol at all. {framed}"
    ),
  ));
}

/// The container words a fragment may write, gathered before the fields are read.
///
/// A struct rather than a tuple: four values of three types, two of them optional, is a return an
/// author of the next word would have to count positions in.
struct Declared {
  /// `crate = "…"` — the path to `ingraph` itself.
  krate: syn::Path,
  /// `remote = "…"` — the foreign type this fragment wraps, or [`None`] for an ordinary one.
  remote: Option<syn::Path>,
  /// `record` / `record(<db>, …)` — the RECORD-HOST activation as WRITTEN, before anything reads it.
  record: Option<RecordActivation>,
  /// `entity` — the ENTITY-HOST activation. The word's own path, which is the span a refusal about
  /// the pair reports at.
  entity: Option<syn::Path>,
  /// `graphql` / `graphql(…)` — the WIRE activation and the two SDL names it may move.
  wire: Option<WireFace>,
  /// `builder(…)` — the wrapped type's construction protocol, or [`None`] where none was written.
  ///
  /// Kept OPTIONAL rather than defaulted here, because the refusal a construction word earns on a
  /// declaration that wraps nothing has to know whether anything was written at all.
  construction: Option<Construction>,
  /// `cursor` / `cursor(…)` — the word, and the members it named.
  cursor: Option<Cursor>,
  /// `filter = "…"` — the predicate this fragment MOUNTS in place of the generated one, or [`None`]
  /// where the declaration wrote no such word.
  filter: Option<syn::Path>,
  /// `delegate(fn …)` — the methods this fragment restates, whatever they are reachable on `Self`
  /// through.
  delegates: Vec<Delegate>,
}

/// The `record` activation as WRITTEN: the dialects it named, each with the token that named it.
///
/// EMPTY is the bare word and is not a defect — see [`RecordHost::databases`] for what a named
/// dialect buys that the bare word does not.
struct RecordActivation {
  /// The dialects the block named, in the order it named them.
  databases: Vec<WrittenDialect>,
  /// `record(write = "…")` — the WHOLE VALUE's transform on its way to storage, as written.
  ///
  /// A [`Transform`] rather than a bare path for the field seat's reason, one level up: the word's
  /// own span is where the refusals ABOUT the word report, and the path's span is where a signature
  /// that disagrees does.
  write: Option<Transform>,
  /// `record(read = "…")` — the mirror, as written.
  read: Option<Transform>,
}

/// ONE dialect at a fragment's head as WRITTEN — the word, and whatever it took in a block.
struct WrittenDialect {
  /// Which database the entry named.
  kind: DatabaseKind,
  /// What the entry's block mounted, or the two empties the bare word means.
  mounted: Mounted,
}

/// What ONE dialect's block mounted — the two TYPE-NAMING seats a dialect group has.
///
/// A struct rather than a pair for [`Declared`]'s reason: two optionals of one type is a return an
/// author of the third seat would have to count positions in.
#[derive(Default)]
struct Mounted {
  /// `<db>(comparison = "…")` — the LOWERING this fragment mounts at this dialect, or [`None`]
  /// where the entry is the bare word and the framework's per-field product stands.
  comparison: Option<syn::Path>,
  /// `<db>(cursor = "…")` / `<db>(cursor(codec = "…"))` — the CURSOR CODEC, or [`None`] where the
  /// framed default stands.
  cursor: Option<Codec>,
}

/// `<db>(cursor = "…")` as WRITTEN — the codec, and the word that named it.
///
/// The word's own span rides beside the path for [`Transform`]'s reason: the refusals this seat
/// earns are about the WORD — mounted where the fragment is no paging position, mounted twice at one
/// dialect, disagreeing with a sibling group — and each reports at the `cursor` an author deletes,
/// where a signature or a missing row reports at the string they edit.
struct Codec {
  /// The word's own span.
  at: syn::Path,
  /// The type, parsed out of the string literal that named it.
  path: syn::Path,
}

/// The `cursor` word as WRITTEN, before it is checked against the fields.
struct Cursor {
  /// The word's own path, for the span its refusals report at.
  at: syn::Path,
  /// The members the list named, or empty for the bare word.
  named: Vec<syn::Ident>,
}

/// The `cursor` word CHECKED against the declaration — the key, or the empty key the bare word means.
///
/// # The list is a PIN, and that is the whole of what a list may be
///
/// The bare word says *my declaration order is the one legitimate total order*. A list says the same
/// thing with the order SPELLED OUT, which is not decoration: written down, the key stops depending
/// on the field list's shape, so a later declaration that adds a field or moves one FAILS here
/// instead of silently paging by a different key. That is a real thing to want and it is what makes
/// the list form live.
///
/// What a list may NOT do is name a different order or a smaller one, and both refusals are forced
/// rather than chosen:
///
/// | written | why it cannot stand |
/// |---|---|
/// | a REORDER | the SQL keyset compares this value's columns in `SEGMENTS` order and binds them in `Carrier`'s, which are both the DECLARATION's — so a key in another order would resume a page at a boundary the statement never compared |
/// | a SUBSET | a cursor's slot is the boundary row's WHOLE value, and a key naming some of the fields has nothing to rebuild the rest from |
///
/// The first is the one worth reading twice: it renders and it round-trips, and it is wrong at the
/// engine. Refusing it at the declaration is the only place the mistake is visible at all.
fn key(written: &Cursor, columns: &[FragmentField], errors: &mut Errors) -> Vec<syn::Ident> {
  const WHY: &str = "A cursor's slot is the boundary row's WHOLE value and the SQL keyset compares \
                     its columns in the order they are DECLARED — so a key that names a different \
                     order, or fewer than all of them, is one the engine never pages by. Write the \
                     fields in the order you want them keyed, or take the bare `cursor`, which is \
                     this same key without the pin";

  if written.named.is_empty() {
    return Vec::new();
  }
  let declared: Vec<&syn::Ident> = columns.iter().map(|field| &field.column.name).collect();
  if written.named.len() != declared.len()
    || !written
      .named
      .iter()
      .zip(&declared)
      .all(|(named, column)| &named == column)
  {
    let spelled: Vec<String> = declared.iter().map(ToString::to_string).collect();
    errors.push(syn::Error::new_spanned(
      &written.at,
      format!(
        "`cursor(…)` PINS this fragment's key, and a pin states the declared order in full — this \
         one does not. Written out, the key is `cursor({})`. {WHY}",
        spelled.join(", ")
      ),
    ));
  }
  written.named.clone()
}

/// **AN `Option` COLUMN IS NOT A POSITION**, so a nullable field in the key is refused by name.
///
/// A page resumes STRICTLY AFTER a boundary, and *after* is a question about a value: the framework
/// pins `NULL` below every value at the ordering seam, so a boundary that is absent has no place in
/// the run it would resume. One rung up the question does not arise — a record's cursor slot holds
/// what the column HOLDS and the frame spells the absence itself — and inside a composite there is
/// no second frame to spell it in.
///
/// Read off the `optional` PROJECTION and never off the field's spelled type, per the standing rule:
/// a macro holds tokens, and `type Maybe = Option<T>` is why a spelling is not trusted here.
fn refuse_an_absent_position(model: &FieldsModel, errors: &mut Errors) {
  let Some(key) = model.cursor.as_ref() else {
    return;
  };
  for field in &model.fields {
    let name = &field.column.name;
    if !matches!(field.column.project, Projection::Optional) {
      continue;
    }
    if !key.is_empty() && !key.contains(name) {
      continue;
    }
    errors.push(syn::Error::new_spanned(
      name,
      format!(
        "`{name}` is `optional`, so it cannot be part of this fragment's cursor key — a page \
         resumes STRICTLY AFTER a boundary, and an absent value has no place in the run it would \
         resume. Drop the field from the key, or drop the `cursor` word: a fragment without one is \
         stored, filtered and read back exactly as before, and is simply not a paging position"
      ),
    ));
  }
}

/// The record-level attributes: `crate = "…"`, `remote = "…"`, and one named refusal per family a
/// fragment does not claim.
///
/// The families are walked from a TABLE rather than as an arm apiece, because what each refusal
/// says differs in one clause and the rest is the tier's own sentence — one arm each would be one
/// place each for that sentence to drift.
///
/// The STORE WORDS are one entry apiece, which is the record's unwrap read from this side: rows used
/// to be claimed by a single `persist(…)` and are claimed by four bare words now, so a tier that
/// holds none has four to refuse. `table` rides with them for the reason it rides with them there —
/// it is their common entry, and a fragment has no table to name. The retired wrapper keeps a seat
/// of its own, carrying the migration rather than the tier's sentence alone.
///
/// # `remote = "…"` is ADMITTED, and it is the tier's second word
///
/// The FOURTH declaration to take it. What a wrapper is FOR is giving a foreign type this
/// framework's faces, and this tier has four to give — the width, the filter, the comparison and
/// the wire object — so a `mediaframe::Dimensions` an application cannot implement traits for is
/// held by a record exactly as a declared fragment is.
///
/// It is NOT gated the way the node rungs gate it. There the discriminator is the ADDRESS — see
/// `parse::remote_is_a_published_rung` — because a node that publishes none has no key and no wire
/// root to hand out. A fragment publishes no address either and needs none: its faces are all
/// projections a holder resolves through, and none of them is a key.
///
/// What it does not bring is an identity seat. `id` stays refused where it always was, in
/// [`markers`], so a manifest field claiming one is told the tier bears no identity rather than
/// told a wrapper cannot have one.
fn options(attrs: &[syn::Attribute], errors: &mut Errors) -> Declared {
  /// One family a fragment does not claim: the word, and what a fragment has instead.
  const CLAIMED: [(&str, &str); 13] = [
    (
      "implements",
      "an interface's members are NODES WITH ROWS — a membership is proved by a stored row \
       answering the contract's columns, and a fragment has no row of its own to answer with. \
       Whether the fragment tier can be a member at all is tracked at \
       https://github.com/findit-studio/ingraph/issues/168, with the inheritance round",
    ),
    (
      "subscribe",
      "a field fragment subscribes to nothing — an edge drives a NODE, and a fragment is carried \
       by whatever declares it rather than driven by anything",
    ),
    (
      "key",
      "a field fragment has no key — bearing no identity is what this tier means, and the identity \
       a question about one ever needs is the holder's",
    ),
    (
      "lineage",
      "a field fragment has no lineage — a path to the root is a path between NODES, and a \
       fragment is not one of them",
    ),
    ("sqlite", STORED_NOWHERE),
    ("postgres", STORED_NOWHERE),
    ("mysql", STORED_NOWHERE),
    ("mongo", STORED_NOWHERE),
    ("table", STORED_NOWHERE),
    (
      "persist",
      "a field fragment is stored in no table of its own — and `persist(…)` is gone besides: a \
       record names its stores BARE at its head, and a fragment names the dialects it is built for \
       inside `record(…)`, which is that same head one namespace in",
    ),
    (
      "fulltext",
      "a field fragment owns no full-text index — an index is a node with a storage, and this tier \
       has neither",
    ),
    (
      "vector",
      "a field fragment owns no embedding index — an index is a node with a storage, and this tier \
       has neither",
    ),
    (
      "blob",
      "a field fragment owns no artifact store — an artifact family is a node with a storage, and \
       this tier has neither",
    ),
  ];

  let mut krate = None;
  let mut remote = None;
  let mut construction = None;
  let mut cursor: Option<Cursor> = None;
  let mut record: Option<RecordActivation> = None;
  let mut entity: Option<syn::Path> = None;
  let mut wire: Option<WireFace> = None;
  let mut filter = None;
  let mut delegates = Vec::new();
  attribute::walk(attrs, errors, |meta, errors| {
    // `crate` is a keyword; syn's nested-meta path parser takes it with `Ident::parse_any`, so it
    // arrives here as an ordinary one-segment path.
    if meta.path.is_ident("crate") {
      match value::parse_literal::<syn::Path>(
        &meta,
        "`#[ingraph(crate = \"…\")]` must be a path to the `ingraph` crate, in a string literal",
      ) {
        Ok(path) => set_once(
          &mut krate,
          path,
          &meta.path,
          "`crate` is declared more than once — one declaration names one crate",
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    // THE REWRITE WORD, read exactly as the node rungs read it: a path in a STRING, because it
    // refers to a type this declaration did not mint. Nothing here resolves it — the path is
    // EMITTED, and one naming nothing is `E0412` at the string the author wrote.
    if meta.path.is_ident("remote") {
      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, read by the suite's own front end rather than by a copy here — the
    // grammar is a FAMILY FACILITY, and the mount is exactly this line. What makes it legal at this
    // tier is the storage face: a fragment is HYDRATED now, so a wrapped one has a call sequence to
    // describe, which is the fact the word was waiting for.
    if meta.path.is_ident(crate::construct::WORD) {
      return crate::construct::container(&meta, &mut construction, errors);
    }
    // THE RECORD-HOST ACTIVATION. Bare it says *a record may hold me*; with dialects in it, it says
    // WHICH ones this fragment was built for — the record head's own store words one namespace in,
    // which is the whole of the parity model at this seat. It claims no table: a fragment is HELD,
    // so the table is the holder's, and this list is what a per-field narrowing is measured against.
    if meta.path.is_ident(RECORD) {
      // The word is RECORDED whatever its content earned, so a declaration whose block was refused
      // is not told a second time that it activated nothing. One mistake, one sentence.
      let written = record_activation(&meta, errors).unwrap_or_else(|refusal| {
        errors.push(refusal);
        RecordActivation {
          databases: Vec::new(),
          write: None,
          read: None,
        }
      });
      set_once(
        &mut record,
        written,
        &meta.path,
        "`record` is declared more than once — one declaration names one host kind once",
        errors,
      );
      return Ok(());
    }
    // THE ENTITY-HOST ACTIVATION, bare and nothing else — see [`entity_activation`] for the door
    // that is deliberately not a hole.
    if meta.path.is_ident(ENTITY) {
      // Recorded whatever the door said, for the record arm's reason above: an author who wrote
      // `entity(…)` DID name a host kind, and hearing that they named none would be a second
      // sentence about one mistake.
      if let Err(refusal) = entity_activation(&meta) {
        errors.push(refusal);
      }
      set_once(
        &mut entity,
        meta.path.clone(),
        &meta.path,
        "`entity` is declared more than once — one declaration names one host kind once",
        errors,
      );
      return Ok(());
    }
    // THE WIRE ACTIVATION — a third word, and the one that is not a host kind. It says this
    // declaration has a face a client can reach at all, which is a thing the tier could not say
    // before: every fragment published whether anything asked or not.
    if meta.path.is_ident(GRAPHQL) {
      let written = wire_activation(&meta, errors).unwrap_or_else(|refusal| {
        errors.push(refusal);
        WireFace {
          object: None,
          filter: None,
        }
      });
      set_once(
        &mut wire,
        written,
        &meta.path,
        "`graphql` is declared more than once — one declaration has one wire face",
        errors,
      );
      return Ok(());
    }
    // THE DELEGATE SEAT, read by the grammar's own front end rather than by a copy here. The seat
    // is a FAMILY facility — a vocabulary mirror spends the same words — and the mount is exactly
    // this line, with this tier's sentences beside it.
    if meta.path.is_ident(crate::delegate::WORD) {
      return crate::delegate::block(&meta, &mut delegates, &FRAGMENT, errors);
    }
    // THE SWAP. Read exactly as `remote = "…"` is, and for its reason: it refers to a type this
    // declaration did not mint, so the path is a STRING and nothing here resolves it — one naming
    // nothing is `E0412` at the literal the author wrote. It names WHICH predicate and never
    // WHETHER there is one: that is the host-kind activation's, one word over.
    if meta.path.is_ident(FILTER) {
      match value::parse_literal::<syn::Path>(
        &meta,
        "`filter = \"…\"` names the predicate this fragment mounts in place of the generated one, \
         as a type path in a string literal",
      ) {
        Ok(path) => set_once(
          &mut filter,
          path,
          &meta.path,
          "`filter` is declared more than once — one fragment is compared by one predicate",
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    // THE CURSOR WORD — an assertion rather than a face, which is why it is the one container word
    // here that is OPT-IN and the only one whose absence costs nothing.
    if meta.path.is_ident(CURSOR) {
      match cursor_word(&meta) {
        Ok(written) => set_once(
          &mut cursor,
          written,
          &meta.path,
          "`cursor` is declared more than once — one fragment is a position in one order",
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    for (family, why) in CLAIMED {
      if meta.path.is_ident(family) {
        errors.push(syn::Error::new_spanned(
          &meta.path,
          format!("{why}. {A_FRAGMENT_IS_HELD}"),
        ));
        attribute::skip_entry(&meta);
        return Ok(());
      }
    }
    errors.push(attribute::unknown(
      &meta,
      "unknown entry on a field fragment — it takes its HOST-KIND activations \
       (`record[(<db>, …)]`, `entity`), `crate = \"…\"`, `remote = \"…\"`, `builder(…)`, \
       `cursor[(…)]`, `filter = \"…\"` and `delegate(fn …)`, every other block naming something a \
       fragment does not have",
      &[
        RECORD,
        ENTITY,
        "crate",
        "remote",
        crate::construct::WORD,
        CURSOR,
        FILTER,
        crate::delegate::WORD,
      ],
    ));
    Ok(())
  });
  Declared {
    krate: krate.unwrap_or_else(|| syn::parse_quote!(::ingraph)),
    remote,
    record,
    entity,
    wire,
    construction,
    cursor,
    filter,
    delegates,
  }
}

/// What a FRAGMENT's delegate refusals say — this tier's half of a grammar two declarations share.
///
/// Both sentences differ from a vocabulary mirror's in one fact: a mirror stores a WORD and has to
/// materialize the upstream value it forwards to, where this tier's entry reaches a method already
/// on `Self` — the author's own on an ordinary fragment, the wrapped value's on a rewrite. So an
/// exclusive receiver here mutates in place at no conversion, and the reason a published one is
/// still refused is the resolver's alone.
const FRAGMENT: crate::delegate::Delegation<'static> = crate::delegate::Delegation {
  receiver: "a delegated method BORROWS its receiver — `&self` reaches the method on `Self`, and \
             `&mut self` mutates the value in place. There is no `self` for one to consume, the \
             value being the caller's rather than this seat's, and a signature with no receiver has \
             nothing to reach a method FROM",
  exclusive: "a published delegate takes `&self` — a resolver READS, and an exclusive receiver's \
              body mutates the value it was called on. Drop the `#[graphql(…)]` to keep the method, \
              or take the receiver by shared reference to keep the field",
};

/// The word a fragment MOUNTS its own predicate with.
///
/// # It is a SWAP, and `marker` is a different question
///
/// The generated filter is one slot per participating field — a total, mechanical reading of the
/// declaration. A composite whose vocabulary is its own says something a field list cannot: a
/// `Dimensions` takes `aspectRatio` and `orientation` beside its two columns, and those are
/// questions about the VALUE rather than about a column. So the word replaces rather than refines:
/// the generated predicate is not emitted, and the composite marker row names the author's type.
///
/// What comes with an author's filter is the author's LOWERING — what a predicate compares is part
/// of what it IS — so a mounted one writes its own `ToDatabaseComparison` row and its own crossing.
/// This tier's comparison is still there to be named, which is what buys a hand-written face the
/// mechanical lowering for free.
///
/// It says WHICH predicate and never WHETHER there is one. Whether a predicate is emitted at all is
/// the HOST-KIND activation's answer, and whether a client can name it is the wire activation's —
/// three words, three questions, and none of them overloaded into another.
///
/// `marker = …` is not overloaded into this either. A marker answers *what READING is this column
/// under*, and every reading a composite has resolves through `CompositeMarker` to whatever this
/// names: the two questions are one step apart, and a word answering both would answer neither.
const FILTER: &str = "filter";

/// The word a fragment declares a WIRE FACE with.
const GRAPHQL: &str = "graphql";

/// `graphql` or `graphql(…)` — the wire activation, and the two SDL names its block may move.
///
/// # The old refusal's sentence is the signpost now
///
/// It said a fragment has no wire ROOT, and that is still true: no `Graphql` binding, no place in a
/// schema's `Query`, and what it shows on the wire is a fragment of whatever holds it. What it does
/// NOT say any more is that the tier publishes unconditionally — a storage-only fragment is a shape
/// an author may want, and the word is how they ask for the other one.
///
/// # Two seats close four surfaces
///
/// The fragment mints an OBJECT and a FILTER INPUT OBJECT, and one member name on each per field.
/// The two type names are here; the two field names are one seat at the field, from which the
/// fourth derives — a record's filter slot reads the field's declared wire name for the same reason.
/// That is #340's fourth class answered where its survey said it had to be: at a seat a declaration
/// can say WHICH thing it names from.
///
/// # `filter(rename = "…")` moves a BASE, because the predicate has up to two faces
///
/// The dual-face ruling (2026-08-22) gives a fragment activated for both host kinds two input
/// objects — the full field set and the stored subset — so a word naming ONE of them would leave
/// the other wearing the old stem, which is #340's own *half-working rename* the twin law exists to
/// prevent. The word therefore names the base both compose off: `filter(rename = "Dim")` publishes
/// `DimFilter` beside `DimColumnFilter`, and a declaration writing no word publishes
/// `<Fragment>Filter` — for the full face, the very name the tier already minted.
///
/// # Errors
/// A named refusal for a value — `graphql = "…"` names nothing this word could mean. An entry the
/// block does not take is RECORDED and the walk continues, so one declaration reports every
/// offender.
fn wire_activation(
  meta: &syn::meta::ParseNestedMeta<'_>,
  errors: &mut Errors,
) -> syn::Result<WireFace> {
  const SHAPE: &str = "`graphql` is written bare — the fragment publishes its own name — or as \
                       `graphql(rename = \"…\", filter(rename = \"…\"))`, which names the OBJECT and \
                       the BASE the FILTER's input objects compose off";

  if attribute::has_value(meta) {
    return Err(attribute::named(meta, SHAPE.to_owned()));
  }
  let mut object: Option<syn::LitStr> = None;
  let mut filter: Option<syn::LitStr> = None;
  attribute::options(meta, |inner| {
    if inner.path.is_ident("rename") {
      match value::literal(&inner, OBJECT_NAME) {
        Ok(spelled) => set_once(
          &mut object,
          spelled,
          &inner.path,
          "`rename` is declared more than once in `graphql(…)` — one option, one value",
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    if inner.path.is_ident("filter") {
      return attribute::sdl_name_block(&inner, &mut filter, "filter", errors);
    }
    errors.push(attribute::unknown(
      &inner,
      "unknown entry in `graphql(…)` on a fragment — it names the two TYPES this face mints \
       (`rename = \"…\"` for the object, `filter(rename = \"…\")` for the base its input objects \
       compose off). What a \
       CLIENT calls one field is that field's own `graphql(rename = \"…\")`, and the queryable-root \
       words (`plural`, `connection`, `edge`, `key`, `order_by`) belong to a declaration that IS a \
       root — a fragment shows on the wire as a fragment of whatever holds it",
      &["rename", "filter"],
    ));
    Ok(())
  })?;
  // WHERE IT SETTLES is where the GraphQL Name grammar is applied, so one bad word earns one
  // sentence at the literal the author wrote rather than a schema that builds and cannot be parsed.
  for spelled in [object.as_ref(), filter.as_ref()].into_iter().flatten() {
    crate::wire::refuse_invalid_name(&spelled.value(), spelled, errors);
  }
  Ok(WireFace {
    object: object.map(|spelled| RustSafeName::new(spelled.value(), spelled.span())),
    filter: filter.map(|spelled| RustSafeName::new(spelled.value(), spelled.span())),
  })
}

/// The refusal when the OBJECT's schema name is not written as a string.
///
/// A STRING and not a Rust identifier, for [`attribute::SDL_NAME`]'s reason: a word naming a type in
/// GraphQL's own namespace has no Rust identifier behind it, so a Rust keyword is an ordinary word
/// here.
const OBJECT_NAME: &str = "a fragment's `graphql(rename = \"…\")` names its OBJECT in the schema, as \
                           a word in a string literal";

/// The word a fragment declares itself consumable by the ROW-BEARING rung with.
const RECORD: &str = "record";

/// The word a fragment declares itself consumable by the IDENTITY-BEARING rung with.
const ENTITY: &str = "entity";

/// `record` or `record(<db>, …)` — the activation, and whatever dialects it named.
///
/// # The inner vocabulary is DIALECTS and nothing else
///
/// Every other word a record's head takes describes something a fragment does not have: `table` and
/// a dialect's `schema` name where the ROW lives, `rename` names the row TYPE, `key` and `lineage`
/// name an address, `implements` claims a membership proved by a stored row. So the namespace admits
/// the one entry that crosses — WHICH DATABASE — and the rest are refused with what a fragment has
/// instead.
///
/// A dialect written here is not a store claim and the difference is the namespace's whole point: at
/// the head of a RECORD the bare word says *my rows land here*, and inside `record(…)` on a fragment
/// it says *a record that lands its rows here may hold me*. One ident, two seats, and no sentence
/// has to disambiguate them.
///
/// # A dialect now takes a BLOCK, and the one word in it is [`COMPARISON`]
///
/// `<db>(comparison = "…")` mounts the LOWERING this fragment gets at that dialect, and it is the
/// only thing a dialect's block takes here: everything else a database can say about a column is
/// the COLUMN's, said on the field that holds it, and the refusal for the rest still says so.
///
/// # Errors
/// A named refusal for a value — `record = "…"` names nothing this word could mean. An entry the
/// block does not take is RECORDED and the walk continues, so one declaration reports every
/// offender.
fn record_activation(
  meta: &syn::meta::ParseNestedMeta<'_>,
  errors: &mut Errors,
) -> syn::Result<RecordActivation> {
  const SHAPE: &str = "`record` is written bare — a record of any dialect may hold this fragment — \
                       or as `record(sqlite, postgres)`, which names the dialects it is BUILT for. \
                       A dialect that mounts something of its own writes it in a block — \
                       `sqlite(comparison = \"…\")` for the lowering, `sqlite(cursor = \"…\")` for \
                       the cursor codec — and the WHOLE VALUE's way across the storage boundary is \
                       `record(write = \"…\")` with `record(read = \"…\")` for the mirror";

  if attribute::has_value(meta) {
    return Err(attribute::named(meta, SHAPE.to_owned()));
  }
  let mut databases: Vec<WrittenDialect> = Vec::new();
  let (mut write, mut read): (Option<Transform>, Option<Transform>) = (None, None);
  attribute::options(meta, |inner| {
    if let Some(kind) = crate::parse::database_kind(&inner.path) {
      let db = kind.as_str();
      if attribute::has_value(&inner) {
        errors.push(attribute::named(
          &inner,
          format!(
            "`{db}` at a fragment's head names the DIALECT and takes no value — a word in it is \
             written in a block, as `{db}(comparison = \"…\")` or `{db}(cursor = \"…\")`"
          ),
        ));
        return Ok(());
      }
      if databases.iter().any(|seen| seen.kind == kind) {
        errors.push(syn::Error::new_spanned(
          &inner.path,
          format!("`{db}` is named more than once in `record(…)` — one entry per database"),
        ));
        return Ok(());
      }
      if !attribute::has_block(&inner) {
        attribute::skip_entry(&inner);
        databases.push(WrittenDialect {
          kind,
          mounted: Mounted::default(),
        });
        return Ok(());
      }
      let mounted = dialect_block(&inner, kind, errors)?;
      databases.push(WrittenDialect { kind, mounted });
      return Ok(());
    }
    // THE BARE SEATS, refused by name and with their migration. Both read like the obvious spelling
    // and neither is one this grammar has: see [`BARE_COMPARISON`] for the ruling the pair shares.
    if inner.path.is_ident(COMPARISON) {
      errors.push(attribute::named(&inner, BARE_COMPARISON.to_owned()));
      return Ok(());
    }
    if inner.path.is_ident(CURSOR) {
      errors.push(attribute::named(&inner, BARE_CODEC.to_owned()));
      return Ok(());
    }
    // THE TWO WHOLE-VALUE TRANSFORM SEATS, read as the pair they are — the field seat's own words at
    // the head, over `Self` instead of over one field's type. They live INSIDE `record(…)` and that
    // placement is the activation refusal: a transform is what a value crosses the STORAGE boundary
    // through, so a fragment no record may hold has no site to spend one at, and the namespace makes
    // that unspellable rather than refusable.
    for (word, slot, shape) in [
      (WRITE, &mut write, HEAD_WRITE_PATH),
      (READ, &mut read, HEAD_READ_PATH),
    ] {
      if !inner.path.is_ident(word) {
        continue;
      }
      match crate::value::parse_literal::<syn::Path>(&inner, shape) {
        Ok(path) => set_once(
          slot,
          Transform {
            at: inner.path.clone(),
            path,
          },
          &inner.path,
          &format!(
            "`{word}` is declared more than once in `record(…)` — one fragment crosses the storage \
             boundary by one whole-value path in each direction, and a value with two canonical \
             forms has none"
          ),
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    // THE NEAR-MISS VOCABULARY is the namespace's whole roster and not the dialects alone, so
    // `writes` is told which word it nearly is rather than only which words it is not.
    let known: Vec<&str> = DatabaseKind::ALL
      .map(DatabaseKind::as_str)
      .into_iter()
      .chain([WRITE, READ, CURSOR])
      .collect();
    errors.push(attribute::unknown(
      &inner,
      &format!(
        "unknown entry in `record(…)` on a fragment — the namespace names DIALECTS ({stores}) and \
         the WHOLE VALUE's two paths across the storage boundary, `write = \"…\"` and \
         `read = \"…\"`. A fragment is HELD, so the row's own words stay the holder's: `table` and \
         `schema` name where a row lives, `rename` names the row type, `key` and `lineage` name an \
         address, and none of the four is a thing this tier has",
        stores = crate::parse::shipped(DatabaseKind::ALL.into_iter().map(DatabaseKind::as_str)),
      ),
      &known,
    ));
    Ok(())
  })?;
  Ok(RecordActivation {
    databases,
    write,
    read,
  })
}

/// The refusal a fragment's HEAD `write` earns when it is not a path in a string literal.
///
/// It names the two sites rather than only the shape, for [`WRITE_PATH`]'s reason: what makes the
/// word worth having is that ONE function is spent everywhere the whole value crosses the boundary,
/// and an author reading the sentence should learn which places those are.
const HEAD_WRITE_PATH: &str = "`write` at a fragment's head names the function the WHOLE VALUE \
   passes through on its way to STORAGE, as a path in a string literal — a `fn(&Self) -> Self`. It \
   is the seat a canonical form that reads SEVERAL fields needs: reducing a rational divides both \
   halves by their common factor, so the numerator's stored value is not a function of the \
   numerator and the per-field `record(write = \"…\")` cannot spell it. One function, spent \
   wherever this emission carries the value across the boundary — the bind, and the cursor's write \
   where the fragment is a paging position";

/// The refusal a fragment's HEAD `read` earns when it is not a path in a string literal.
const HEAD_READ_PATH: &str = "`read` at a fragment's head names the function the WHOLE VALUE passes \
   through on its way BACK, as a path in a string literal — a `fn(&Self) -> Self`, spent at the \
   raise and at the cursor's read. Writing none is the IDENTITY, which is what a canonicalisation \
   wants: a reduced value is a valid domain value and there is nothing to undo";

/// The word that mounts a dialect's own lowering — `record(<db>(comparison = "…"))`.
const COMPARISON: &str = "comparison";

/// **THERE IS NO BARE `comparison = "…"`**, and the sentence carries the reason rather than only
/// the shape.
///
/// A bare seat's SCOPE is implicit. A type written once would have to serve whichever dialects it
/// happens to fit, and nothing at the declaration says which those are: a family-generic
/// `SqlXComparison<Db>` silently serves the three SQL dialects and not MongoDB, and the household
/// that adds `mongo` later has no word to say that the mount stops there. Naming the type at each
/// dialect it serves costs one mention per dialect and leaves no reading to infer.
///
/// A FAMILY-level word (`comparison(sql = "…")`) was considered and rejected with it: it mints a
/// family-name vocabulary axis that the per-dialect spelling derives for free, and the audit at each
/// mount already proves the type fits the dialect it was named at.
const BARE_COMPARISON: &str = "there is no bare `comparison = \"…\"` — a lowering is mounted PER \
   DIALECT, as `record(sqlite(comparison = \"…\"), postgres(comparison = \"…\"))`. A bare seat's \
   SCOPE would be implicit: a type generic over the SQL family serves three dialects and not \
   MongoDB, and nothing at the declaration would say so. A family-generic type is simply named at \
   each dialect it serves — two mentions, zero ambiguity — and each mount is audited against the \
   dialect it was written at";

/// **THERE IS NO BARE `cursor = "…"` INSIDE `record(…)` EITHER**, and it is [`BARE_COMPARISON`]'s
/// ruling with one more reason of its own.
///
/// A word that NAMES A TYPE is written where the dialect is. That is the register law this grammar
/// already holds `comparison` to, and holding one type-naming seat to it and not its neighbour is
/// how a namespace comes to have two shapes for one kind of word.
///
/// Here the law is not only tidiness, and the sentence says so: a codec's bytes ARE the dialect's. A
/// page cursor is session-lived pagination state rather than a durable id, so the only engine that
/// ever has to read a token is the one that minted it — which frees a household to keep a dense form
/// per store, and makes *which store* the first thing a mount has to answer. A bare seat would have
/// no answer to give.
const BARE_CODEC: &str = "there is no bare `cursor = \"…\"` in `record(…)` — a type-naming seat is \
   written where the DIALECT is, as `record(sqlite(cursor = \"…\"), postgres(cursor = \"…\"))`, \
   which is the register law `comparison` is mounted under one word over. A codec's bytes are that \
   STORE's: a page cursor is short-lived pagination state rather than a durable id, so the engine \
   that reads a token is the one that minted it, and each dialect may keep a byte form of its own. \
   A dialect you name and mount nothing at rides the framed default there. The bare `cursor` at the \
   HEAD, outside `record(…)`, is a different word entirely: it asserts this fragment's total order, \
   and it is what gives a codec here a reader";

/// The refusal `comparison` earns when it is not a path in a string literal.
const COMPARISON_PATH: &str = "`comparison` names the type this fragment's predicate LOWERS INTO \
   at this dialect, as a path in a string literal. It replaces the per-field product, which is what \
   a whole-value operator needs: `overlaps` spans two columns at once and has no field to hang on. \
   The type owes that dialect's faces — the crossing from this fragment's filter, the empty \
   predicate, and the lowering itself";

/// The word the CURSOR CODEC's group form names its type with.
const CODEC: &str = "codec";

/// The refusal a codec mount earns when it is not a path in a string literal.
const CODEC_PATH: &str = "`cursor` names the type that WRITES AND READS this fragment's cursor \
   bytes, as a path in a string literal. It replaces the emission's framed default — one \
   length-prefixed member per key column — which is what a household with a dense hand-written form \
   needs: eight flat bytes are not four members of two, and the emission cannot know a width. The \
   type owes ONE face, `ingraph::CursorCodec<Self>`, whose `encode` and `decode` are duals and \
   therefore one implementor";

/// What ONE dialect's block at a fragment's head takes — the two TYPE-NAMING seats, and nothing
/// else.
///
/// # Errors
/// Whatever the walk itself refused with. A word the block does not take is RECORDED and the walk
/// continues, so one head reports every offender.
fn dialect_block(
  meta: &syn::meta::ParseNestedMeta<'_>,
  kind: DatabaseKind,
  errors: &mut Errors,
) -> syn::Result<Mounted> {
  let db = kind.as_str();
  if attribute::empty_group(meta) {
    errors.push(attribute::named(
      meta,
      format!(
        "`{db}()` says nothing — write the dialect BARE to name it, \
         `{db}(comparison = \"…\")` to mount the lowering this fragment gets there, or \
         `{db}(cursor = \"…\")` to mount the codec its paging boundary is written by"
      ),
    ));
    attribute::skip_entry(meta);
    return Ok(Mounted::default());
  }
  let mut mounted = Mounted::default();
  attribute::options(meta, |inner| {
    if inner.path.is_ident(COMPARISON) {
      match crate::value::parse_literal::<syn::Path>(&inner, COMPARISON_PATH) {
        Ok(path) => attribute::set_once(
          &mut mounted.comparison,
          path,
          &inner.path,
          &format!("`comparison` is mounted more than once at `{db}` — one dialect, one lowering"),
          errors,
        ),
        Err(why) => errors.push(why),
      }
      return Ok(());
    }
    if inner.path.is_ident(CURSOR) {
      match codec_word(&inner, db, errors) {
        Ok(Some(written)) => attribute::set_once(
          &mut mounted.cursor,
          written,
          &inner.path,
          &format!("`cursor` is mounted more than once at `{db}` — one dialect, one codec"),
          errors,
        ),
        Ok(None) => {}
        Err(why) => errors.push(why),
      }
      return Ok(());
    }
    errors.push(attribute::unknown(
      &inner,
      &format!(
        "unknown entry in `{db}(…)` at a fragment's head — the block takes the two TYPE seats, \
         `comparison = \"…\"` and `cursor[(codec = \"…\")]`, and nothing else. How ONE database \
         renders a COLUMN is that column's to say, on the field that holds it, as \
         `#[ingraph(record({db}(…)))]`; what this seat says is what the whole VALUE lowers into \
         there, and what its paging boundary is written by"
      ),
      &[COMPARISON, CURSOR],
    ));
    Ok(())
  })?;
  Ok(mounted)
}

/// ONE entry `cursor(…)` knows — the word an author writes, and the reader that takes it.
///
/// # A TABLE, because this block is the seat's GROWTH POINT
///
/// The codec is the first entry and it will not be the last: a block is where a seat's next
/// configurable fact lands, and the whole reason the group spelling exists beside the shorthand is
/// that it can take one without breaking the other. A chain of `is_ident` arms would make each
/// addition a small edit in four places — the arm, the near-miss vocabulary, the roster a refusal
/// prints, and the sentence that lists what the block takes.
///
/// So the roster is DATA. A new entry is **one row here and one field on [`CursorBlock`]**; the
/// vocabulary [`cursor_words`] hands a near miss, the roster [`cursor_roster`] prints, and the
/// refusal an unknown word earns all derive from this array and are not restated anywhere.
struct CursorEntry {
  /// The word, as it is written.
  word: &'static str,
  /// What it fills in — and what it refuses with, which is the entry's own business.
  read: fn(&syn::meta::ParseNestedMeta<'_>, &mut CursorBlock, &str, &mut Errors),
}

/// Everything `cursor(…)` takes today.
const CURSOR_ENTRIES: &[CursorEntry] = &[CursorEntry {
  word: CODEC,
  read: read_codec,
}];

/// What one `cursor(…)` block was read into.
///
/// A struct with one field rather than a bare [`Option`], for [`CURSOR_ENTRIES`]'s reason: the next
/// entry adds a field here and changes nothing else.
#[derive(Default)]
struct CursorBlock {
  /// `codec = "…"` — the type that writes this fragment's cursor bytes at this dialect.
  codec: Option<syn::Path>,
}

/// The CODEC entry's reader.
fn read_codec(
  inner: &syn::meta::ParseNestedMeta<'_>,
  block: &mut CursorBlock,
  db: &str,
  errors: &mut Errors,
) {
  match crate::value::parse_literal::<syn::Path>(inner, CODEC_PATH) {
    Ok(path) => attribute::set_once(
      &mut block.codec,
      path,
      &inner.path,
      &format!(
        "`{CODEC}` is declared more than once in `cursor(…)` at `{db}` — one option, one value"
      ),
      errors,
    ),
    Err(why) => errors.push(why),
  }
}

/// The block's vocabulary, for a near miss to be measured against.
fn cursor_words() -> Vec<&'static str> {
  CURSOR_ENTRIES.iter().map(|entry| entry.word).collect()
}

/// The block's roster, as a sentence names it.
fn cursor_roster() -> String {
  format!(
    "`cursor(…)` knows {}",
    crate::parse::shipped(CURSOR_ENTRIES.iter().map(|entry| entry.word))
  )
}

/// `<db>(cursor = "…")` or `<db>(cursor(codec = "…"))` — the codec seat's two spellings.
///
/// # The shorthand is SUGAR for the group, exactly
///
/// `cursor = "X"` and `cursor(codec = "X")` reach the same model by the same reader and the same
/// refusal, which is what makes the short form safe to keep as the block grows: it is the block with
/// its one required entry written inline, never a second grammar. The group is where every further
/// entry lands — see [`CURSOR_ENTRIES`], which is the roster both this walk and its refusals read.
///
/// # Errors
/// A named refusal for every shape that is neither spelling: the bare word, an empty group, a
/// literal that is not a path. An entry the roster does not know is RECORDED and the walk continues,
/// so one block reports every offender.
fn codec_word(
  meta: &syn::meta::ParseNestedMeta<'_>,
  db: &str,
  errors: &mut Errors,
) -> syn::Result<Option<Codec>> {
  let at = meta.path.clone();
  // THE SHORTHAND, read by the codec entry's own reader so the two spellings cannot come to accept
  // different literals or refuse with different words.
  if attribute::has_value(meta) {
    let mut block = CursorBlock::default();
    read_codec(meta, &mut block, db, errors);
    return Ok(block.codec.map(|path| Codec { at, path }));
  }
  if !attribute::has_block(meta) || attribute::empty_group(meta) {
    return Err(attribute::named(
      meta,
      format!(
        "`cursor` says nothing on its own at `{db}` — the seat NAMES a type, in one of two \
         spellings: `{db}(cursor = \"…\")`, or `{db}(cursor(codec = \"…\"))`, which is that same \
         entry in the block every further word will land in. The bare word at a fragment's HEAD is \
         a different seat one level out — `cursor` beside `record(…)` asserts this fragment's total \
         order, and it is what makes a codec here have a reader at all"
      ),
    ));
  }
  let mut block = CursorBlock::default();
  let mut refusal = None;
  meta.parse_nested_meta(|inner| {
    if let Some(entry) = CURSOR_ENTRIES
      .iter()
      .find(|entry| inner.path.is_ident(entry.word))
    {
      (entry.read)(&inner, &mut block, db, errors);
      return Ok(());
    }
    refusal.get_or_insert_with(|| {
      attribute::unknown(
        &inner,
        &format!(
          "unknown entry in `cursor(…)` at `{db}` — {}",
          cursor_roster()
        ),
        &cursor_words(),
      )
    });
    Ok(())
  })?;
  if let Some(why) = refusal {
    errors.push(why);
  }
  // NO SECOND SENTENCE for a group that named no codec. The empty block is refused above by shape,
  // so a walk that reaches here saw entries — and a group with entries and no codec is a group whose
  // entries were each refused by name already. Saying *and therefore it named nothing* on top of
  // that is one mistake reported twice, which is the rule the whole grammar is written under.
  Ok(block.codec.map(|path| Codec { at, path }))
}

/// `entity` — the activation, and the DOOR that is deliberately not a hole.
///
/// # Errors
/// A named refusal for any inner content at all — a value, a block, an empty block. Entity-hosting
/// has nothing to configure YET, and saying so by name is what keeps the seat a door: the tenants are
/// known (an election's projection over an entity-hosted field, a `fulltext` or `vector` label on
/// one, the keys tier's exposure) and each arrives with the consumer that reads it, because a word
/// parsed into a model nothing spends is a promise rather than a rule.
fn entity_activation(meta: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<()> {
  if !attribute::has_value(meta) && !attribute::has_block(meta) {
    attribute::skip_entry(meta);
    return Ok(());
  }
  Err(attribute::named(
    meta,
    "entity-hosting has nothing to configure yet — the bare word `entity` activates the read faces, \
     and a configuration you need is a ruling away. What will live here is known by name: an \
     election's projection over an entity-hosted field, a `fulltext` or `vector` label on one, the \
     keys tier's exposure. Each arrives with the consumer that reads it"
      .to_owned(),
  ))
}

/// The word a fragment asserts its own total order with.
const CURSOR: &str = "cursor";

/// `cursor` or `cursor(a, b, c)` — the word, and whatever it listed.
///
/// # Errors
/// A named refusal where the entry carries a VALUE. `cursor = "…"` names nothing this word could
/// mean: the members are a list and a list is written in brackets.
fn cursor_word(meta: &syn::meta::ParseNestedMeta<'_>) -> syn::Result<Cursor> {
  const SHAPE: &str = "`cursor` is written bare — every field, in declared order — or as \
                       `cursor(a, b, c)`, which PINS that same key by spelling it out";

  if attribute::has_value(meta) {
    return Err(attribute::named(meta, SHAPE.to_owned()));
  }
  let at = meta.path.clone();
  if !attribute::has_block(meta) {
    attribute::skip_entry(meta);
    return Ok(Cursor {
      at,
      named: Vec::new(),
    });
  }
  if attribute::empty_group(meta) {
    return Err(attribute::named(
      meta,
      format!("`cursor()` names no member, which is not the empty key — {SHAPE}"),
    ));
  }
  let mut named = Vec::new();
  let mut refusal = None;
  meta.parse_nested_meta(|inner| {
    match inner.path.get_ident() {
      Some(member) if !attribute::has_value(&inner) && !attribute::has_block(&inner) => {
        named.push(member.clone());
      }
      _ => {
        refusal.get_or_insert_with(|| {
          attribute::named(
            &inner,
            format!("a cursor's members are FIELD NAMES, bare and comma-separated — {SHAPE}"),
          )
        });
        attribute::skip_entry(&inner);
      }
    }
    Ok(())
  })?;
  match refusal {
    Some(e) => Err(e),
    None => Ok(Cursor { at, named }),
  }
}

/// The field markers: the three PROJECTION words, and a named refuse-until for the rest.
///
/// Those three are admitted because this emission SPENDS them — each names one way an accessor
/// hands a field back, and there is nothing else here for a word to decide. Every other word a
/// fragment's field will carry is inherited by a holder, and what would read that inheritance has
/// not arrived; a model carrying a fact nothing spends is one the next author has to keep true for
/// no reader.
fn markers(
  attrs: &[syn::Attribute],
  field: &syn::Ident,
  activated: &Activated<'_>,
  written: &mut Marked,
  errors: &mut Errors,
) -> Projection {
  // A fragment CLAIMS two words of its own beside the three projections — `builder(…)`, which the
  // hydration spends, and the `record(…)` NAMESPACE, which is the record field seat's own storage
  // grammar one level in — and every other marker is refused here, which is what the tier means. See
  // the sentence at the bottom of this walk.
  column::projection_markers(attrs, field, errors, |meta, errors| {
    // THE RECORD-HOST NAMESPACE: what this field says to the rung that stores rows. Its vocabulary
    // is that rung's own field vocabulary, letter for letter one level in — `skip` and its fill,
    // `flatten`, and a database written bare to narrow or with words in it to configure.
    if meta.path.is_ident(RECORD) {
      return match record_column(meta, field, activated.record, &mut written.stored, errors) {
        Ok(()) => column::Claim::Taken,
        Err(e) => column::Claim::Refused(e),
      };
    }
    // WHAT A CLIENT CALLS THIS FIELD — one word for the two surfaces it publishes, the object's
    // member and the filter's slot being one field's name on the wire. Read only where the
    // declaration activated a face for it to be a name ON.
    if meta.path.is_ident(GRAPHQL) {
      return match wire_column(meta, field, activated.wire, &mut written.wire_name, errors) {
        Ok(()) => column::Claim::Taken,
        Err(e) => column::Claim::Refused(e),
      };
    }
    // `persist(flatten)` IS RETIRED, and the refusal is where the migration is taught. The word was
    // this tier's whole storage grammar while there was one word in it; the namespace is that
    // grammar arriving, and the layout word moved into it with everything else.
    if meta.path.is_ident(PERSIST) {
      return column::Claim::Refused(attribute::named(
        meta,
        format!(
          "`persist` is retired at a fragment's field — what it held is the RECORD host's, and that \
           is the namespace it moved into: write `#[ingraph(record(flatten))]` for the layout word \
           this seat used to be the whole of, and `#[ingraph(record(skip))]`, \
           `#[ingraph(record({db}(…)))]` for the rest of the storage grammar `{field}` may now \
           declare. One idiom, one level count: a record names its stores bare at its head and a \
           fragment names them inside `record(…)`.",
          db = DatabaseKind::Sqlite.as_str(),
        ),
      ));
    }
    // THE PER-COLUMN HALF of the construction protocol, read by the suite's own front end. A word
    // written on a fragment that wraps nothing is refused at the assembly rather than here, by the
    // same function the record rung calls: the check needs to see the whole declaration, and one
    // reading of it is what keeps the two mounts saying the same sentence.
    if meta.path.is_ident(crate::construct::WORD) {
      return match crate::construct::field(meta, &mut written.build, errors) {
        Ok(()) => column::Claim::Taken,
        Err(e) => column::Claim::Refused(e),
      };
    }
    // A REF out of a fragment, which is a different question from the ruled one — `ref` AT a
    // fragment is refused by the target's own missing identity, at the holder. Refusing it by name
    // rather than under the general wait, because it is not waiting for the inheritance: what a
    // reference from inside a fragment even MEANS is the open question, tracked rather than guessed.
    if meta.path.is_ident("ref") {
      return column::Claim::Refused(syn::Error::new_spanned(
        &meta.path,
        format!(
          "`{field}` cannot reference another node from inside a fragment — a fragment is HELD, so \
           a reference out of one belongs to whatever holds it, where the key that would carry it \
           lives. Fragment references are wanted and are tracked at \
           https://github.com/findit-studio/ingraph/issues/168; today the holder declares the `ref`"
        ),
      ));
    }
    if meta.path.is_ident("id") {
      return column::Claim::Refused(syn::Error::new_spanned(
        &meta.path,
        format!(
          "`{field}` cannot be a fragment's id, because a fragment has none — bearing no identity \
           is what this tier means, and a group of fields that does bear one is an `entity`. \
           {A_FRAGMENT_IS_HELD}"
        ),
      ));
    }
    column::Claim::Refused(syn::Error::new_spanned(
      &meta.path,
      "a fragment's field takes the projection words — `copy`, `repeated`, `optional` — plus \
       `builder(…)`, the HOST-KIND namespace `record(…)` and the wire face's own \
       `graphql(rename = \"…\")`, and no other word yet. What a field says to a host kind goes \
       inside that kind's own namespace, which is what keeps one ident from meaning two things at \
       two seats; the labels and the wire legs are declared ONCE here and inherited by every holder, \
       and what reads that inheritance has not arrived",
    ))
  })
}

/// WHICH ACTIVATIONS the declaration wrote, as one field's walk needs to see them.
///
/// A word is read only where the thing it speaks to was declared: a column word needs a record host,
/// a wire name needs a face to be a name on. Gathered rather than passed apiece, because the walk
/// takes both and a fourth activation would be a fourth parameter.
struct Activated<'a> {
  /// The record host and the dialects it named, or [`None`] where no record may hold this fragment.
  record: Option<&'a RecordActivation>,
  /// Whether the declaration asked for a wire face at all.
  wire: bool,
}

/// What a field's markers WRITE INTO — one value per walk, so the three seats travel together.
#[derive(Default)]
struct Marked {
  /// `builder(…)` — this column's place in the wrapped type's construction.
  build: Option<Build>,
  /// `record(…)` — what the field said to the record host.
  stored: RecordColumn,
  /// `graphql(rename = "…")` — what a client calls it.
  wire_name: Option<syn::LitStr>,
}

/// `graphql(…)` on a FIELD — what a CLIENT calls it.
///
/// # One word, two surfaces, because they are one name
///
/// A field publishes a member on the fragment's object and a slot on its filter's input object, and
/// both are *what a client calls this field*. A record reads them off one declared name for the same
/// reason. The word moves both, and there is no seat for moving one of them alone — a schema whose
/// input and output spelled one field two ways is a schema a client reads twice.
///
/// # Errors
/// A named refusal where the declaration activated no wire face at all — a name on a face that does
/// not exist is a rule its author believes they declared — and for every shape that is not
/// `graphql(rename = "…")`.
fn wire_column(
  meta: &syn::meta::ParseNestedMeta<'_>,
  field: &syn::Ident,
  published: bool,
  wire_name: &mut Option<syn::LitStr>,
  errors: &mut Errors,
) -> syn::Result<()> {
  const SHAPE: &str = "`graphql(…)` on a fragment's field takes ONE entry — \
                       `graphql(rename = \"…\")`, what a CLIENT calls this field, on the object and \
                       in the filter alike";

  if !published {
    return Err(attribute::named(
      meta,
      format!(
        "`{field}` names itself on a wire face this fragment does not have — the tier publishes \
         nothing unless the declaration asks, so a name here would be a name on nothing. Write \
         `graphql[(…)]` at the head to publish the object and the filter's input face, or drop the \
         word"
      ),
    ));
  }
  if attribute::has_value(meta) {
    return Err(attribute::named(meta, SHAPE.to_owned()));
  }
  if !attribute::has_block(meta) || attribute::empty_group(meta) {
    return Err(attribute::named(
      meta,
      format!("`graphql` says nothing on its own at a field — {SHAPE}"),
    ));
  }
  let mut refusal = None;
  meta.parse_nested_meta(|inner| {
    if inner.path.is_ident("rename") {
      match value::literal(&inner, FIELD_NAME) {
        Ok(spelled) => {
          crate::wire::refuse_invalid_name(&spelled.value(), &spelled, errors);
          set_once(
            wire_name,
            spelled,
            &inner.path,
            &format!(
              "`rename` is declared more than once in `graphql(…)` on `{field}` — one option, one \
               value"
            ),
            errors,
          );
        }
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    refusal.get_or_insert_with(|| {
      attribute::unknown(
        &inner,
        &format!(
          "unknown entry in `graphql(…)` on `{field}` — {SHAPE}. The record seat's other wire words \
           (`skip`, `type = \"…\"`, the per-database crossings, a backend's own cell) each name a \
           per-face or per-backend fact, and this tier publishes ONE object and ONE input face with \
           no backend cell between them — so they arrive with the round that gives them one"
        ),
        &["rename"],
      )
    });
    Ok(())
  })?;
  match refusal {
    Some(e) => Err(e),
    None => Ok(()),
  }
}

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

/// The refusal when a COLUMN's name is not written as a string.
///
/// A STRING and not a Rust identifier, and it is the record seat's own reason: `type` and `bitRate`
/// are ordinary column names, so a field carrying one is mangled rather than refused.
const COLUMN_NAME: &str = "a column's `rename` must be its name where it is stored, in a string \
                           literal";

/// What one field said to the RECORD host — the record field seat's own storage grammar, one level
/// in.
#[derive(Default)]
struct RecordColumn {
  /// `record(skip)` / `record(skip(default = "…"))` — the declared absence and its fill.
  skip: Option<SkipField>,
  /// `record(flatten)` — this field lends no name, so its type's segments join the fragment's own
  /// namespace.
  flatten: Option<syn::Path>,
  /// `record(rename = "…")` — what this column is CALLED where it is stored.
  ///
  /// The record field seat's own bare `rename`, one namespace in and meaning what it means there:
  /// the column's name in every database that holds it. A record scopes a second one per database;
  /// a fragment publishes one dialect-free list, so the dialect-free spelling is the whole of the
  /// word here — the same shape `flatten` takes, for the same reason.
  rename: Option<syn::LitStr>,
  /// `record(<db>)` and `record(<db>(…))` — the presence claims and the per-database configuration,
  /// read by the record seat's own reader.
  per_db: Vec<FieldDatabase>,
  /// `record(derived(…))` — the columns this field's declaration adds to the layout, in the order
  /// they were written. Repeatable, one column apiece.
  derived: Vec<DerivedColumn>,
  /// `record(write = "…")` — the function this field's value passes through on its way to storage.
  ///
  /// A [`syn::Path`] carried beside its own span, for [`DerivedColumn`]'s reason: the refusals this
  /// word earns beside another are refusals about the WORD, and a path parsed out of a string
  /// literal keeps the literal's span so each of them reports where the author wrote it.
  write: Option<Transform>,
  /// `record(read = "…")` — the mirror, for the household whose stored form is not a domain form.
  read: Option<Transform>,
}

/// ONE `record(write = "…")` or `record(read = "…")` as WRITTEN — the path, and the word that named
/// it.
///
/// The word's own span is a seat rather than a field of the path because the two refusals this
/// grammar carries are both about the WORD: written beside `skip` there is no site to spend it at,
/// and written twice there is one field with two canonical forms. Both report at `write`/`read`
/// itself, which is the token an author deletes.
struct Transform {
  /// The word's own span.
  at: syn::Path,
  /// The function, parsed out of the string literal that named it.
  path: syn::Path,
}

/// ONE `record(derived(column = "…", from = "…", type = "…"))` as WRITTEN, before anything reads it.
///
/// [`SkipField`](crate::parse::SkipField)'s mirror image at the parse tier too: that one carries the
/// word's span so an unsatisfied `Default` reports at the word, and this one carries it so a
/// collision and a missing entry both report at the `derived` that made the claim.
struct DerivedColumn {
  /// The `derived` word's own span.
  at: syn::Path,
  /// `column = "…"` — the name, verbatim.
  column: syn::LitStr,
  /// `from = "…"` — the function that computes it.
  from: syn::Path,
  /// `type = "…"` — the function's return type, written where the layout can name it.
  ty: syn::Type,
}

/// The RETIRED word, kept as an ident so its refusal can carry the migration.
const PERSIST: &str = "persist";

/// The word that says *this field lends no name* — `record(flatten)`.
const FLATTEN: &str = "flatten";

/// The declared absence — `record(skip)`, with `record(skip(default = "…"))` naming the fill.
const SKIP: &str = "skip";

/// What this column is CALLED where it is stored — `record(rename = "…")`.
const RENAME: &str = "rename";

/// The COLLECTION-ordering word, mirrored from the record seat so its rule can be mirrored with it.
const SORTABLE: &str = "sortable";

/// The COLLECTION-ACCESS word, mirrored for [`SORTABLE`]'s reason and refused beside it: both speak
/// about a collection, and a fragment's field cannot be one.
const INDEXED: &str = "indexed";

/// The column the WRITE computes — `record(derived(column = "…", from = "…", type = "…"))`.
const DERIVED: &str = "derived";

/// The WRITE-PATH TRANSFORM — `record(write = "path::to::fn")`.
const WRITE: &str = "write";

/// The READ-PATH MIRROR — `record(read = "path::to::fn")`.
const READ: &str = "read";

/// The refusal `write` earns when it is not a path in a string literal.
const WRITE_PATH: &str = "`write` names the function a value passes through on its way to STORAGE, \
                          as a path in a string literal — a `fn(&T) -> T` over this field's own \
                          type. It is spent at BOTH the bind and the crossing's query operand, \
                          which is what makes an index answer `eq` exactly: a value stored in one \
                          spelling and asked in another is a row a client cannot find";

/// The refusal `read` earns when it is not a path in a string literal.
const READ_PATH: &str = "`read` names the function a stored value passes through on its way BACK, \
                         as a path in a string literal — a `fn(&T) -> T` over this field's own \
                         type. Writing none is the identity, which is what a canonicalisation \
                         wants: a reduced value is a valid domain value and there is nothing to \
                         undo";

/// The shape sentence every `derived(…)` refusal ends on.
const DERIVED_SHAPE: &str = "`derived(…)` names a column this fragment's WRITE computes and its \
                             READ never fetches — `derived(column = \"…\", from = \
                             \"path::to::fn\", type = \"…\")`, where `from` is a `fn(&Self) -> T` \
                             reading whatever sibling fields it needs and `type` is that `T`. It is \
                             repeatable: one block, one column";

/// The refusal when a derived column's NAME is not written as a string.
const DERIVED_NAME: &str = "`column` names the derived column where it is stored, in a string \
                            literal — the name a statement renders, an order names and a filter \
                            slot is called after";

/// The refusal when `from` is not a path.
const DERIVED_FROM: &str = "`from` names the function that computes this column, as a path in a \
                            string literal — a `fn(&Self) -> T` taking the whole value, so it may \
                            read every field the column is derived from";

/// The refusal when `type` is not a type.
const DERIVED_TYPE: &str = "`type` names the derived column's own type, as a type in a string \
                            literal — the `T` the function returns, written here because a `where` \
                            clause, a filter slot and a comparison member all need it as TOKENS and \
                            no stable spelling names a function's return";

/// `record(…)` on a FIELD — the record host's own field grammar, one namespace in.
///
/// # Letter for letter, and the level count is the whole of the difference
///
/// A record's field writes `skip`, `derived(…)`, `flatten` and a database bare or blocked; a
/// fragment's field writes the same five words inside `record(…)`. Nothing about what they MEAN
/// moves: `skip` is the declared absence in every database and its block names the fill, `derived`
/// is its mirror image and names a column the write computes, `flatten` drops this field's own name
/// so its type's segments join the holder's namespace, a bare `<db>` narrows the participation the
/// container granted, and `<db>(…)` says how one database renders the column. What the namespace
/// buys is that the same idents at a fragment's own seat — where `flatten` once meant only the inner
/// mount and a bare dialect meant nothing at all — now read as one grammar with one owner.
///
/// # What this round can HONOUR, and what it names by name
///
/// The three dialect-free words are spent here: `skip` contracts every storage face and fills the
/// read, `derived(…)` adds one the write computes and the read never fetches, and `flatten` selects
/// the other segment spelling. The two DIALECT-scoped ones are grammar this round and teeth the
/// next, and each is refused by name rather than accepted and dropped:
///
/// * a bare `<db>` naming FEWER than the head declared asks the fragment for two layouts, and the
///   universal `SEGMENTS` const has one — so the narrowing waits for the per-dialect participation
///   masks, and the refusal says so at the word that narrowed;
/// * `<db>(…)` carrying words asks for a column that renders differently per dialect, and the
///   segment list carries no dialect to render it under, so the same wait answers it;
/// * `<db>(flatten)` is refused for a REASON rather than a wait — the layout a fragment publishes is
///   one dialect-free list, measured not to want a parameter, so a per-dialect layout is not a thing
///   the tier has whatever the participation model grows.
///
/// # Errors
/// A named refusal for a value or an empty block, and for the namespace written at all on a fragment
/// no record may hold. An entry the namespace does not take is RECORDED and the walk continues, so
/// one field reports every offender.
fn record_column(
  meta: &syn::meta::ParseNestedMeta<'_>,
  field: &syn::Ident,
  host: Option<&RecordActivation>,
  stored: &mut RecordColumn,
  errors: &mut Errors,
) -> syn::Result<()> {
  const SHAPE: &str = "`record(…)` on a field takes the storage words — `skip` (with \
                       `skip(default = \"…\")` naming what fills the read), `derived(…)` for a \
                       column the write computes off this field, `write = \"…\"` and `read = \"…\"` \
                       for the transforms a value crosses the storage boundary through, `flatten`, \
                       `rename = \"…\"`, and one database written bare to narrow this field to it \
                       or with words in it to say how that database renders the column";

  if host.is_none() {
    return Err(attribute::named(
      meta,
      format!(
        "`{field}` says something to the RECORD host and this fragment declares none — a word about \
         a column is a word for the rung that has rows, so it is read only where the declaration \
         said that rung may hold it. Write `record[(<db>, …)]` at the head, or drop the namespace \
         here"
      ),
    ));
  }
  if attribute::has_value(meta) {
    return Err(attribute::named(meta, SHAPE.to_owned()));
  }
  if !attribute::has_block(meta) || attribute::empty_group(meta) {
    return Err(attribute::named(
      meta,
      format!("`record` says nothing on its own at a field — {SHAPE}"),
    ));
  }
  let mut refusal = None;
  meta.parse_nested_meta(|inner| {
    if inner.path.is_ident(SKIP) {
      let at = inner.path.clone();
      let declared = crate::parse::skip_word(&inner, "on this field", errors)?;
      set_once(
        &mut stored.skip,
        declared,
        &at,
        &format!("`skip` is declared more than once on `{field}` — one word, one field"),
        errors,
      );
      return Ok(());
    }
    // WHAT THIS COLUMN IS CALLED where it is stored — the record field seat's bare `rename`, one
    // namespace in. The fragment's own segment list is what carries it: the names const holds the
    // STORED name, which is what a statement renders and a read fetches, and `ColumnName` keeps the
    // DECLARED one beside it, which is the axis no database moves.
    if inner.path.is_ident(RENAME) {
      match value::literal(&inner, COLUMN_NAME) {
        Ok(spelled) => set_once(
          &mut stored.rename,
          spelled,
          &inner.path,
          &format!("`rename` is declared more than once on `{field}` — one option, one value"),
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    // THE COLLECTION-ORDERING WORD, refused with the RECORD SEAT'S OWN RULE rather than with a wait.
    // `sortable` orders a collection, a collection is what a `list(…)`/`set(…)` LABEL declares, and
    // this tier admits no label — a fragment's field takes the projection words and nothing that
    // says a value is many. So the word reaches the same sentence it reaches one namespace out, at a
    // seat where no field can satisfy it. That is a fact about the tier rather than about the round.
    if inner.path.is_ident(SORTABLE) {
      refusal.get_or_insert_with(|| {
        attribute::named(
          &inner,
          format!(
            "`sortable` orders a COLLECTION, and a collection is what a `list(…)` or `set(…)` label \
             declares — which a fragment's field cannot write: this tier takes the PROJECTION words \
             (`copy`, `repeated`, `optional`), and none of them says a value is many in the sense a \
             storage plan can order. So there is no order for a companion column to preserve on \
             `{field}`, which is the record seat's own rule read at a seat where nothing can meet \
             it. A collection whose order is stored is a column of the HOLDER's declaration"
          ),
        )
      });
      return Ok(());
    }
    // THE COLLECTION-ACCESS WORD, refused beside the ordering one and for the identical reason: both
    // speak about a collection's ELEMENTS, and this tier admits no label that says a value is many.
    // Read as a WORD rather than left to the unknown-entry list, so the answer is the seat's rule.
    if inner.path.is_ident(INDEXED) {
      refusal.get_or_insert_with(|| {
        attribute::named(
          &inner,
          format!(
            "`indexed` puts a second index on the table a COLLECTION's elements are rows of, and a \
             collection is what a `list(…)` or `set(…)` label declares — which a fragment's field \
             cannot write: this tier takes the PROJECTION words (`copy`, `repeated`, `optional`), \
             and none of them says a value is many in the sense a storage plan can index. So there \
             are no elements on `{field}` for a value-led index to lead on, which is the record \
             seat's own rule read at a seat where nothing can meet it. A collection that is seeked \
             by its elements is a column of the HOLDER's declaration; ONE column's index, in ONE \
             database, is that database's own block — `#[ingraph(sqlite(indexed))]`"
          ),
        )
      });
      return Ok(());
    }
    if inner.path.is_ident(FLATTEN) {
      if attribute::has_value(&inner) || attribute::has_block(&inner) {
        refusal.get_or_insert_with(|| {
          attribute::named(
            &inner,
            "`flatten` is a BARE word — it drops this field's own name so its type's segments become \
             columns of the fragment's namespace, and there is nothing for a value to say about that"
              .to_owned(),
          )
        });
        return Ok(());
      }
      attribute::skip_entry(&inner);
      set_once(
        &mut stored.flatten,
        inner.path.clone(),
        &inner.path,
        &format!("`flatten` is declared more than once on `{field}` — one marker, one layout"),
        errors,
      );
      return Ok(());
    }
    // THE MIRROR IMAGE OF `skip`, and it sits beside it for that reason: one says this field is
    // declared and not stored, the other says a column is stored and not declared. Repeatable, so
    // it accumulates instead of being set once — a field whose value carries two canonical readings
    // derives two columns off one source.
    if inner.path.is_ident(DERIVED) {
      match derived_column(&inner, field, errors) {
        Ok(Some(one)) => stored.derived.push(one),
        Ok(None) => {}
        Err(e) => {
          refusal.get_or_insert(e);
        }
      }
      return Ok(());
    }
    // THE TWO TRANSFORM SEATS — the storage BOUNDARY's own words, where every word above is about a
    // column's name, its place or its absence. They are read as one pair because they are one pair:
    // `write` is the path in and `read` is the path back, and a declaration writing only the first
    // is saying that the stored form IS a domain form, which is the canonicalisation case.
    for (word, slot, shape) in [
      (WRITE, &mut stored.write, WRITE_PATH),
      (READ, &mut stored.read, READ_PATH),
    ] {
      if !inner.path.is_ident(word) {
        continue;
      }
      match value::parse_literal::<syn::Path>(&inner, shape) {
        Ok(path) => set_once(
          slot,
          Transform {
            at: inner.path.clone(),
            path,
          },
          &inner.path,
          &format!(
            "`{word}` is declared more than once on `{field}` — one field, one path to storage"
          ),
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    // ONE DATABASE, read by the RECORD SEAT'S OWN READER — the same function, so `sqlite(skip)`
    // earns the one-storage-shape law here exactly as it does there, `mongo(flatten)` earns its
    // structural refusal, and a word the block does not take earns the block's own list. A second
    // copy of that walk is how the two seats would come to disagree about what a column block is.
    if let Some(kind) = crate::parse::database_kind(&inner.path) {
      return crate::parse::field_database(&inner, kind, &mut stored.per_db, errors);
    }
    refusal.get_or_insert_with(|| {
      attribute::unknown(
        &inner,
        &format!("unknown entry in `record(…)` on `{field}` — {SHAPE}"),
        &[SKIP, FLATTEN, RENAME, SORTABLE, INDEXED, DERIVED, WRITE, READ],
      )
    });
    Ok(())
  })?;
  match refusal {
    Some(e) => Err(e),
    None => Ok(()),
  }
}

/// **A FIELD WITH NO COLUMN HAS NO PLACE FOR ONE TO FOLLOW** — `record(skip)` and
/// `record(derived(…))` on one field are refused together.
///
/// The two words are exact mirror images, which is why writing both is a contradiction rather than a
/// combination: `skip` says this field is declared and stored nowhere, `derived` says a column is
/// stored and declared nowhere. A derived column sits at the position its source field's own columns
/// end at, and a skipped field ends at no position — so the layout would have nothing to put the
/// column after, and a rule that picked one anyway would be answering a question the declaration
/// never asked.
fn refuse_a_column_derived_off_a_field_that_has_none(
  field: &syn::Ident,
  stored: &RecordColumn,
  errors: &mut Errors,
) {
  if stored.skip.is_none() {
    return;
  }
  for one in &stored.derived {
    errors.push(syn::Error::new_spanned(
      &one.at,
      format!(
        "`{field}` carries `skip` and `derived(column = \"{column}\", …)` — one says the field is a \
         column in NO database and the other adds a column beside the ones it would have been. The \
         two words are mirror images: `skip` is declared and not stored, `derived` is stored and \
         not declared, and a field that ends at no position in the layout has nothing for a derived \
         column to follow. Drop whichever is not meant — a computed column whose sources are all \
         skipped belongs to the field that IS stored",
        column = one.column.value(),
      ),
    ));
  }
}

/// **A TRANSFORM NEEDS A SITE TO BE SPENT AT** — `record(write = "…")` and `record(read = "…")` are
/// refused beside `record(skip)`.
///
/// The words-with-no-reader family, and the membership is exact. A transform's whole content is the
/// two crossings of the storage BOUNDARY — the bind and the crossing's query operand on the way in,
/// the fetch on the way back — and `skip` deletes all three: a skipped field is a column of no
/// database, so nothing binds it, no slot compares it, and the read SUPPLIES its value out of the
/// fill rather than fetching one. What is left for a function to sit on is nothing at all.
///
/// It is the same shape `derived` beside `skip` takes and a different reason: that pair is a
/// CONTRADICTION — one word says stored-and-not-declared and the other declared-and-not-stored —
/// and this one is a word whose reader was removed. Two sentences, because an author who wrote them
/// is being told two different things.
fn refuse_a_transform_with_nothing_to_transform(
  field: &syn::Ident,
  stored: &RecordColumn,
  errors: &mut Errors,
) {
  let Some(skip) = stored.skip.as_ref() else {
    return;
  };
  let filled = skip.default.is_some();
  for (word, declared) in [(WRITE, stored.write.as_ref()), (READ, stored.read.as_ref())] {
    let Some(transform) = declared else {
      continue;
    };
    errors.push(syn::Error::new_spanned(
      &transform.at,
      format!(
        "`{field}` carries `skip` and `{word} = \"…\"`, and the word has no site left to be spent \
         at — a skipped field is a column of NO database, so there is no bind to write through, no \
         slot for a query operand to cross at, and a read that {supplies} instead of fetching one. \
         A transform is what a value crosses the STORAGE BOUNDARY through, and this field never \
         crosses it. Drop whichever is not meant",
        supplies = if filled {
          "hands back what `skip(default = \"…\")` named"
        } else {
          "hands back `Default::default()`"
        },
      ),
    ));
  }
}

/// **NO TWO OF THIS FRAGMENT'S COLUMNS SHARE A NAME**, asked once over the whole list.
///
/// The record seat's own collision law read one namespace in, and the reason it is checked HERE
/// rather than at the emission is that a derived column has no field to have been named after: its
/// name is a string an author wrote, so a typo repeating a declared column's name is a declaration
/// that stores one value into another's column. The flattened case has a fence of its own — a
/// `const` assertion over the published `SEGMENTS`, which is where a name a nested type contributes
/// can be seen at all — and this is the half a macro holding tokens really can answer.
fn refuse_a_derived_name_a_column_already_has(columns: &[FragmentField], errors: &mut Errors) {
  let stored_name = |field: &FragmentField| {
    field
      .stored_name
      .clone()
      .unwrap_or_else(|| field.column.name.to_string())
  };
  let mut taken: Vec<(String, &'static str)> = columns
    .iter()
    .filter(|field| field.skip.is_none() && !field.flatten)
    .map(|field| (stored_name(field), "declared field"))
    .collect();
  for field in columns {
    for one in &field.derived {
      let spelled = one.column.external().to_owned();
      if let Some((_, kind)) = taken.iter().find(|(name, _)| *name == spelled) {
        errors.push(syn::Error::new_spanned(
          one.column.safe(),
          format!(
            "`{spelled}` is already a column of this fragment — the {kind} of that name renders it \
             too, and two values written into one column is a row whose second write is the one \
             that survives. A derived column's name is the axis its filter slot, its order and \
             every statement speak in, so it has to be this fragment's alone: rename the derived \
             column, or `record(rename = \"…\")` whichever declared field it met"
          ),
        ));
        continue;
      }
      taken.push((spelled, "derived column"));
    }
  }
}

/// ONE `derived(…)` block, read into the column it declares.
///
/// # All THREE entries or none, and the refusal names the ones that are missing
///
/// A derived column is a column: it needs a name to be stored under, a value to be stored, and a
/// type for the layout to describe. None of the three has a default a declaration could mean by
/// silence — a name folded off the source field would collide with it, a value is the whole of what
/// the word is for, and a type read off the function is exactly what stable Rust cannot spell. So a
/// block naming fewer than three is refused at the word, listing what it did not say.
///
/// # Errors
///
/// A named refusal for a value, for a bare word and for an empty block, each ending on
/// [`DERIVED_SHAPE`]. An entry the block does not take is RECORDED and the walk continues, so one
/// block reports every offender.
fn derived_column(
  meta: &syn::meta::ParseNestedMeta<'_>,
  field: &syn::Ident,
  errors: &mut Errors,
) -> syn::Result<Option<DerivedColumn>> {
  const COLUMN: &str = "column";
  const FROM: &str = "from";
  const TYPE: &str = "type";

  if attribute::has_value(meta) {
    return Err(attribute::named(meta, DERIVED_SHAPE.to_owned()));
  }
  if !attribute::has_block(meta) || attribute::empty_group(meta) {
    return Err(attribute::named(
      meta,
      format!("`derived` says nothing on its own on `{field}` — {DERIVED_SHAPE}"),
    ));
  }
  let at = meta.path.clone();
  let (mut column, mut from, mut ty) = (None, None, None);
  // WHICH WORDS WERE WRITTEN, held apart from which ones READ — a value refused for its own reason
  // has already been reported at the value, and reporting it again as an absence would answer one
  // mistake twice, in two sentences that do not agree about what is wrong.
  let mut written: Vec<&str> = Vec::new();
  attribute::options(meta, |option| {
    if option.path.is_ident(COLUMN) {
      written.push(COLUMN);
      match value::literal(&option, DERIVED_NAME) {
        Ok(spelled) => set_once(
          &mut column,
          spelled,
          &option.path,
          &format!(
            "`column` is declared more than once in `derived(…)` on `{field}` — one block, one column"
          ),
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    if option.path.is_ident(FROM) {
      written.push(FROM);
      match value::parse_literal::<syn::Path>(&option, DERIVED_FROM) {
        Ok(path) => set_once(
          &mut from,
          path,
          &option.path,
          &format!(
            "`from` is declared more than once in `derived(…)` on `{field}` — one column, one function"
          ),
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    if option.path.is_ident(TYPE) {
      written.push(TYPE);
      match value::parse_literal::<syn::Type>(&option, DERIVED_TYPE) {
        Ok(written) => set_once(
          &mut ty,
          written,
          &option.path,
          &format!(
            "`type` is declared more than once in `derived(…)` on `{field}` — one column, one type"
          ),
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    errors.push(attribute::unknown(
      &option,
      &format!("unknown entry in `derived(…)` on `{field}` — {DERIVED_SHAPE}"),
      &[COLUMN, FROM, TYPE],
    ));
    Ok(())
  })?;
  let missing: Vec<&str> = [COLUMN, FROM, TYPE]
    .into_iter()
    .filter(|word| !written.contains(word))
    .collect();
  let (Some(column), Some(from), Some(ty)) = (column, from, ty) else {
    // A word WRITTEN and refused has been reported already, so an empty list here means every entry
    // was written and at least one was refused: that block's mistakes are all told, and this
    // sentence has nothing left to add.
    if !missing.is_empty() {
      errors.push(syn::Error::new_spanned(
        &at,
        format!(
          "`derived(…)` on `{field}` names no {absent} — {DERIVED_SHAPE}",
          absent = crate::parse::shipped(missing.into_iter()),
        ),
      ));
    }
    return Ok(None);
  };
  Ok(Some(DerivedColumn {
    at,
    column,
    from,
    ty,
  }))
}

/// **A FRAGMENT'S LAYOUT CARRIES NO DIALECT**, so every per-dialect claim about one of its columns
/// is refused with the measurement that says why.
///
/// # The wall, measured rather than asserted
///
/// A record's per-dialect participation is real: its rows, its statements and its raise are one per
/// database, so a column can live in some of them and not in others. A fragment has none of that.
/// What it publishes is a layout, and the three faces that state one are dialect-free by
/// construction:
///
/// | face | where its dialect is | can it be split per dialect? |
/// |---|---|---|
/// | `ColumnKind::SEGMENTS` | NOWHERE — the trait takes no parameter | no: one impl, and a holder's `COLUMNS` const descends it with no dialect in hand |
/// | `Assemble<'a, R>` | only through `R::Database` | **no — `E0119`**, measured: two impls constrained to different `Row::Database`s are conflicting implementations, a where-clause equality not being something coherence disjoins |
/// | `Carrier<Db>` | the trait's own parameter | yes — but it must bind exactly what `SEGMENTS` names, so a split bind that the layout does not follow renders a statement the engine refuses |
///
/// So a fragment that narrowed a field per dialect would publish one column list, bind to it, read
/// it back — and be wrong in the dialect it narrowed. The teeth are not missing; the seat is.
///
/// # Which makes it the HOLDER's word, and that is where it already lives
///
/// A record holding a fragment states its own per-dialect participation on the field that MOUNTS
/// it, at the seat that has a row per database to state it in. That is the same answer
/// `record(<db>(flatten))` gets, and for the same reason — a layout that varies per database is a
/// fact about the row, and the row is the holder's.
///
/// | written | answered with |
/// |---|---|
/// | a bare `<db>` the head never declared | the head's own list, exactly as a record answers it |
/// | a bare `<db>` naming FEWER than the head declared | the wall above, and the holder's own seat |
/// | `<db>(skip[(default = "…")])` | the same wall: an absence needs a per-dialect READ, and `Assemble` has none |
/// | `<db>(…)` carrying words | the same wall: a rendering needs a per-dialect column list to render into |
/// | `<db>(flatten)` | the dialect-free `SEGMENTS` measurement, said in its own words |
///
/// Naming the whole declared set takes nothing away and is accepted as the restatement it is —
/// the record seat's own reading of the same words.
fn refuse_a_dialect_the_layout_cannot_carry(
  field: &syn::Ident,
  host: Option<&RecordActivation>,
  stored: &RecordColumn,
  errors: &mut Errors,
) {
  const WALL: &str = "a fragment publishes ONE dialect-free layout and there is no second list for \
                      a second database to differ in: `ColumnKind` takes no dialect at all, and the \
                      READ that would have to differ cannot be split — two `Assemble` impls \
                      constrained to different `Row::Database`s are `E0119`, conflicting \
                      implementations. A layout that really does vary per database is the HOLDER's \
                      to write, on the field that mounts this fragment, where there is a row per \
                      database to write it in. What a dialect at THIS head still buys is the \
                      comparison pair a wire-faced holder asks for at that backend";

  let Some(host) = host else {
    return;
  };
  let declared: Vec<DatabaseKind> = host.databases.iter().map(|one| one.kind).collect();
  for per in &stored.per_db {
    let db = per.kind.as_str();
    if !declared.contains(&per.kind) {
      let head = if declared.is_empty() {
        "the head is the bare `record` word, which fixes no dialect for a field to speak about"
          .to_owned()
      } else {
        format!(
          "this fragment is built for {list}",
          list = crate::parse::shipped(declared.iter().map(|kind| kind.as_str()))
        )
      };
      errors.push(syn::Error::new_spanned(
        &per.at,
        format!(
          "`{db}` is not a database this fragment names — {head}. A field names a database to narrow \
           itself to it or to say how it renders the column there, and both need the head to have \
           named it first: write `#[ingraph::fields(record({db}, …))]`."
        ),
      ));
      continue;
    }
    if let Some(at) = per.flatten.as_ref() {
      errors.push(syn::Error::new_spanned(
        at,
        format!(
          "`flatten` inside `record({db}(…))` scopes a LAYOUT to one dialect, and a fragment's \
           layout carries none: what it publishes is a single `ColumnKind::SEGMENTS`, and that \
           trait's own note records the measurement that keeps a dialect out of it. Write \
           `record(flatten)`, which is the same decision for every database that holds `{field}`. A \
           layout that really does vary per database is the HOLDER's to write, on the field that \
           mounts this fragment"
        ),
      ));
      continue;
    }
    // THE PER-DIALECT ABSENCE, which is the record seat's own `<db>(skip(default = "…"))` reaching
    // this seat through the shared reader. It is refused for the READ rather than for the layout:
    // a column absent at one dialect is a column the decode has to fill at that dialect and at no
    // other, and a fragment has one `Assemble` for every dialect there is.
    if let Some(skip) = per.skip.as_ref() {
      errors.push(syn::Error::new_spanned(
        &skip.at,
        format!(
          "`record({db}(skip(…)))` withholds `{field}` from ONE dialect, and the fill it names is \
           what a read of THAT dialect would supply — {WALL}. Write `record(skip(default = \"…\"))` \
           for a field no database holds, which is one absence with one fill and needs no dialect \
           to state"
        ),
      ));
      continue;
    }
    if per.configured() {
      errors.push(syn::Error::new_spanned(
        &per.at,
        format!("`record({db}(…))` says how ONE database renders `{field}`, and {WALL}"),
      ));
    }
  }
  let narrowed: Vec<DatabaseKind> = stored
    .per_db
    .iter()
    .filter(|per| per.bare && declared.contains(&per.kind))
    .map(|per| per.kind)
    .collect();
  if narrowed.is_empty() || declared.iter().all(|kind| narrowed.contains(kind)) {
    return;
  }
  let absent: Vec<DatabaseKind> = declared
    .iter()
    .copied()
    .filter(|kind| !narrowed.contains(kind))
    .collect();
  // ONE error for the whole list, at the first word of it — the record seat's own arrangement: a
  // narrowing is a single claim about one field however many words spell it.
  if let Some(per) = stored.per_db.iter().find(|per| per.bare) {
    errors.push(syn::Error::new_spanned(
      &per.at,
      format!(
        "`{field}` names {kept} and this fragment is built for {all}, so the word withholds the \
         column from {gone} — and {WALL}. Write `record(skip)` for a field no database holds, or \
         name every database the head does, which is the restatement it is",
        kept = crate::parse::shipped(narrowed.iter().map(|kind| kind.as_str())),
        all = crate::parse::shipped(declared.iter().map(|kind| kind.as_str())),
        gone = crate::parse::shipped(absent.iter().map(|kind| kind.as_str())),
      ),
    ));
  }
}

/// **A SKIPPED COLUMN IS NO PAGING POSITION**, so `record(skip)` beside `cursor` is refused.
///
/// A fragment's key is EVERY declared field in declared order — the pin form refuses anything else —
/// and the SQL keyset compares those fields' columns. A field with no column in any database has
/// nothing to compare, so a key holding one is a key the engine cannot page by. It is the same shape
/// as the `optional` refusal beside it: the codec would round-trip and the statement would not.
fn refuse_a_skipped_position(
  field: &syn::Ident,
  cursor: Option<&Cursor>,
  stored: &RecordColumn,
  errors: &mut Errors,
) {
  let (Some(skip), Some(_)) = (stored.skip.as_ref(), cursor) else {
    return;
  };
  errors.push(syn::Error::new_spanned(
    &skip.at,
    format!(
      "`{field}` is skipped, so it is a column of no database — and this fragment is a `cursor` \
       position, whose key is every declared field in declared order. The SQL keyset compares those \
       fields' columns, and a field that has none is one the engine cannot resume a page at. Drop \
       the `skip`, or drop the `cursor` word: a fragment without one is stored, filtered and read \
       back exactly as before, and is simply not a paging position"
    ),
  ));
}

/// **A FRAGMENT THAT HOLDS ITSELF HAS NO WIDTH**, refused at the field that spelled the cycle.
///
/// # One step of it is the macro's, and the rest is the compiler's
///
/// A cycle is a fact about a GRAPH of declarations and this pass sees ONE of them, so the reach here
/// is exactly the step it can take: a field whose written type is this fragment's own name. A
/// transitive one — `A` holding `B` holding `A` — is invisible from either declaration, `B` being a
/// token this pass cannot resolve, and it is refused by the type system instead: the two
/// `ColumnKind::SEGMENTS` consts each require the other, which is `E0391` naming every step of the
/// cycle in turn. Both are pinned as goldens.
///
/// `Option<Self>` is caught with the bare spelling, because `Option`'s own width row DELEGATES —
/// nullability decides what a column may hold and not how many there are — so an optional self-hold
/// is the same infinite descent one word longer. `Vec<Self>` is NOT a cycle and is not refused here:
/// a collection rides ONE column, and its width row says so without ever reading the element's.
fn refuse_a_cycle(fragment: &syn::Ident, field: &syn::Ident, ty: &syn::Type, errors: &mut Errors) {
  if !holds(fragment, ty) {
    return;
  }
  errors.push(syn::Error::new_spanned(
    ty,
    format!(
      "`{field}` gives `{fragment}` a field of its own type, so `{fragment}` → `{fragment}` is a \
       cycle — and a fragment is HELD, which means its columns are laid out inside whatever holds \
       it. A value that holds itself has no width: its column list would contain its column list. \
       The rung that can point at another instance of a type is `entity`, whose `ref` names one by \
       ID rather than laying it out inline"
    ),
  ));
}

/// Whether `ty` is `fragment`, or an `Option` of it — the one step [`refuse_a_cycle`] can see.
fn holds(fragment: &syn::Ident, ty: &syn::Type) -> bool {
  let syn::Type::Path(path) = ty else {
    return false;
  };
  let Some(last) = path.path.segments.last() else {
    return false;
  };
  match &last.arguments {
    syn::PathArguments::None => last.ident == *fragment,
    // `Option<Self>` and nothing else: a collection's width row answers ONE column without reading
    // its element's, so `Vec<Self>` descends nowhere and is a different question entirely.
    syn::PathArguments::AngleBracketed(inner) if last.ident == "Option" => {
      inner.args.iter().any(|argument| match argument {
        syn::GenericArgument::Type(inner) => holds(fragment, inner),
        _ => false,
      })
    }
    _ => false,
  }
}

/// Two of a fragment's fields reaching ONE method name.
///
/// A record's rule, in this tier's terms and for its reason: a column reaches an accessor through a
/// derived shape, so `x` beside a `copy` `set_x` gives the type two `set_x`. Both would be
/// duplicate definitions inside the expansion, at a span the declaration cannot edit.
fn emitted_methods(model: &FieldsModel, errors: &mut Errors) {
  let mut taken: Vec<&Emitted> = Vec::new();
  for emitted in &model.emitted_methods() {
    if let Some(first) = taken.iter().find(|seen| seen.name == emitted.name) {
      errors.push(syn::Error::new_spanned(
        &emitted.name,
        format!(
          "`{owner}` would declare `{name}` twice — {this}, and {that} already reaches it",
          owner = emitted.owner_name,
          name = emitted.name,
          this = emitted.origin,
          that = first.origin,
        ),
      ));
    }
    taken.push(emitted);
  }
}

/// **ONE WORD, ONE FIELD** — a published delegate and a column that reach the same word on the
/// fragment's object.
///
/// A fragment's wire face publishes one field per column under that column's camel-cased name, and a
/// lifted delegate publishes one beside them. Two of them at one word would be two entries of one
/// `#[Object]` block, which is `E0592` inside an expansion whose author cannot edit either — and the
/// useful answer names which column the word already belongs to.
///
/// The word is asked of the MODEL rather than rebuilt here: `Delegate::word` is the one authority on
/// what a client writes, and a second spelling on this side is how a refusal and an emission come to
/// disagree about a name nobody moved.
fn refuse_a_published_collision(model: &FieldsModel, errors: &mut Errors) {
  for kind in GraphqlKind::ALL {
    let mut taken: Vec<(String, syn::Ident)> = Vec::new();
    for (word, at) in model.wire_words(kind) {
      if let Some((_, first)) = taken.iter().find(|(seen, _)| *seen == word) {
        errors.push(syn::Error::new_spanned(
          &at,
          format!(
            "`{at}` publishes `{word}` on this fragment's object, and `{first}` already does — one \
             word is one field of the emitted object, and two entries reaching it are two members \
             of one `#[Object]` block. Move one of them with \
             `#[graphql({kind}(rename = \"…\"))]`, or rename the field",
            kind = kind.as_str(),
          ),
        ));
        continue;
      }
      taken.push((word, at));
    }
  }
}

/// Fragments are concrete, for the reason a node is: a field's type is read straight off the
/// declaration, and a type parameter has none until it is substituted.
fn concrete(generics: &syn::Generics, errors: &mut Errors) {
  const WHY: &str = "generic field fragments are not supported — a fragment must be concrete, \
                     because a field's type is read straight off the declaration";
  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 fragment may take, its whole content being
/// the fields a holder inherits BY NAME.
fn named_fields(input: &syn::DeriveInput) -> 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,
        "a field fragment must be a struct with named fields — what a holder inherits is a field's \
         name as much as its type, and a positional one has none to inherit",
      )),
    },
    syn::Data::Enum(_) | syn::Data::Union(_) => Err(syn::Error::new_spanned(
      &input.ident,
      "`#[ingraph::fields(record, entity)]` supports structs only",
    )),
  }
}