ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
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
//! The TOWER declaration's emission: the CONNECTIVITY, which is what makes a question pipeline a
//! compile-time theorem, and the WALK that spends it.
//!
//! ```ignore
//! #[ingraph::tower(question(type = "String"))]
//! pub struct ClipText {
//!   #[ingraph(answer = "Vec<String>")]        tokenize: Tokenize,
//!   #[ingraph(answer = "Vec<f32>", async)]    encode:   ClipTextTower,
//! }
//!
//! impl SearchTower for ClipText
//! where
//!   Tokenize:      Serves<String, Vec<String>>,          // spanned at `tokenize`
//!   ClipTextTower: AsyncServes<Vec<String>, Vec<f32>>,   // spanned at `encode`
//! {
//!   type Question = String;
//!   type Answer = Vec<f32>;
//!   type Steps = ClipText;
//! }
//!
//! pub enum ClipTextError {
//!   Tokenize(<Tokenize as Serves<String, Vec<String>>>::Error),
//!   Encode(<ClipTextTower as AsyncServes<Vec<String>, Vec<f32>>>::Error),
//! }
//! ```
//!
//! # THE AMENDMENT: a tower MAY FAN, and every fan folds before the mouth
//!
//! The tower law gained its amendment with the search pipeline's design: **a tower may contain
//! FANNING SEGMENTS — expansion × lane routing — and every fan must fold before the tower's mouth,
//! so the OUTER contract stays 1 → 1.** A segment is opened by a step word ([`Fan`]) and closed by
//! the walk, which is why no word names a fold: where it happens is the law's, not an author's.
//!
//! **TODAY'S TOWERS ARE THE DEGENERATE CASE**, and that is a fact about this file rather than a
//! promise: a declaration that writes no fan word has [`StepModel::fan`] [`None`] at every step,
//! [`TowerModel::fanned`] answers false, and not one line of the emission below asks. The
//! expansion such a tower gets is the expansion it got before the amendment, token for token.
//!
//! **THE FAN WALK IS HERE** — `fanned_body` below emits the nesting: the widening once, the
//! crossing per arm, the tail per `(arm × lane)` cell, and the fold that closes every segment before
//! the mouth.
//!
//! **AND SO IS THE ASSEMBLY ROW.** `assembly` emits the third impl a declaration states: the GATE
//! (`check`, one reading per declared stage word, at that step's own field) and the UNIFORM RUN
//! (`run`, the walk at an arity that does not move with the step count — which is what a search
//! recipe's resolver can call and `walk` itself never was). The gate is EMITTED and not a roster
//! row, and that is the fan model's own note read back: what a gate reads is a SEAT, and a seat is a
//! value no `const` could carry across the expansion wall. A tower that opened no segment emits NO
//! gate and inherits the row that refuses nothing.
//!
//! # ⟂ THE STAGE BEFORE THE FAN: a step that ANNOTATES rather than transforms
//!
//! A third step word opens a third stage, and it is the one whose ends are the SAME TYPE.
//! `annotate(type = "…")` says *this step hands back the question it was given, one fact richer* —
//! and the fan words downstream READ that fact, which is the whole reason the stage exists and
//! cannot be an ordinary hop: a step's answer travels downstream, so a datum a WIDENING needs
//! cannot arrive as the answer of a step that runs after it.
//!
//! The seat is [`StepModel::annotation`] and the order is [`Stage::Annotate`], which sorts before
//! both fan words. Three consequences, all emitted below: the chain's type does NOT move across the
//! step (`flows`), the walk asks the QUESTION before it calls the operator (`annotating`), and the
//! step is an ordinary `Serves`/`AsyncServes` hop at both ends — so a `Door` onto a graph resident
//! mounts here with no bridge and no wrapper, which is what the resident-hop stage was named for.
//!
//! # THE CHAIN IS DERIVED, so there is nothing for two words to disagree about
//!
//! One question is written — the tower's — and one answer per step. Every question after the first
//! IS the answer before it, so an author never states an adjacency and the emission never checks
//! one: what it does is DEMAND each hop, at the type the chain arrived at. A step that does not
//! serve the question it is handed is `E0277` at the impl, and the predicate carries that step's
//! own span, so the caret is on the field an author has to change.
//!
//! A trivially-false `where` predicate on a concrete impl is a hard error on stable — that is what
//! puts the refusal AT THE IMPL rather than leaving an impl that silently never applies — and it is
//! why the connectivity is stated as a `where` clause rather than as a helper call beside it.
//!
//! # THE WORD SELECTS THE FACE, one step at a time
//!
//! A bare step field binds the blocking [`Serves`]; `#[ingraph(async)]` binds [`AsyncServes`].
//! This is the fifth position in the framework where a word chooses a face — after
//! `source(async)`, `handler(async)`, `operator(async)` and `resource(async)` — and it is the first
//! that is PER FIELD rather than per declaration, which is the whole of what makes a MIXED tower
//! expressible: a blocking tokenizer and an awaited encoder are one chain.
//!
//! Words CHOOSE; bounds PROVE. Nothing here checks that a step's body really is awaited — a word
//! that lied names a face the type does not wear, and the same `E0277` on the same step field says
//! so.
//!
//! # THE WORDS ARE OMISSIBLE, and what fills their place is a PROJECTION
//!
//! `question(type = "…")` and `answer = "…"` are OVERRIDE words. A step's type may carry its own
//! canonical line — `impl DefaultServe for Tokenize { type Question = …; type Answer = …; }`, the
//! one-time *what this server is usually asked* — and a declaration that omits a word gets that
//! line's projection wherever the written type would have gone:
//!
//! ```ignore
//! #[ingraph::tower]                      // no question: step0's canonical one
//! pub struct ClipText {
//!   tokenize: Tokenize,                  // no answer: `<Tokenize as DefaultServe>::Answer`
//!   #[ingraph(async)] encode: ClipTextTower,
//! }
//! ```
//!
//! **SELECTION NEVER COMES FROM INFERENCE.** `DefaultServe` takes no parameter, so
//! `<Tokenize as DefaultServe>::Answer` is one concrete type rather than a variable the compiler is
//! asked to solve for. A step with several `Serves` impls is therefore no more ambiguous omitted
//! than written — `E0283` is not reachable by this road, and a chain still selects among a step's
//! impls by the types the declaration arrived at.
//!
//! **THE CHAIN'S `where` CLAUSE STILL NAMES FACES AND NOTHING ELSE**, which is what makes the
//! canonical line free of a mode. `DefaultServe`'s own supertrait is the BASE `Serve` — the seat a
//! server's knobs sit in — and never a face, so an awaited-only server can declare its canonical
//! line and a blocking one can declare the same. Landing that supertrait on a face instead would
//! make the omissible word available only to steps wearing that face, and the shipped towers in
//! this tree wear the awaited one: a declaration word available in only one mode is a mode-coupled
//! authoring surface, which is the thing *the word selects the face* exists to prevent.
//!
//! What proves the canonical line HONEST is therefore not the supertrait but this emission's own
//! predicate: an omitted `answer` puts `<Ty as DefaultServe>::Answer` on both sides of the hop, so
//! a server whose canonical line names a `Q → A` it does not serve is `E0277` at that step's field,
//! exactly where a written word that lied would be.
//!
//! # THE HEAD'S OWN `answer` — the one word here that DECIDES NOTHING
//!
//! ```ignore
//! #[ingraph::tower(question(type = "String"), answer = "Vec<f32>")]
//! pub struct ClipText { … }                  // ← what this tower is FOR, said at its head
//! ```
//!
//! A tower's answer is DERIVED — it is the last step's, and no word can make it anything else. So
//! this word is not a third override beside the two above: what it writes down is an INTENT, and
//! what the emission does with it is demand that the derivation agree. That is a DOUBLE ENTRY, the
//! source layer's own shape one axis over: the WORD is what a reader, a manifest front end and a
//! search recipe's author see, the DERIVATION is what the compiler resolves a binding through, and
//! neither can mint the other — so the join is written as one bound, and the two are checked against
//! each other AT THE DECLARATION.
//!
//! | written | what happens |
//! |---|---|
//! | `answer = "Vec<f32>"` over a chain arriving at `Vec<f32>` | it compiles, and costs nothing |
//! | `answer = "Vec<f32>"` over a chain arriving at `Vec<f64>` | `E0271` at the WORD |
//! | no word | nothing is emitted and nothing is checked |
//!
//! **WHAT IT BUYS is WHERE the drift is reported, and never whether it is.** A tower whose last step
//! quietly moved is already caught — by the binding that named the coordinate type it expected —
//! but that refusal lands in the recipe, at a declaration whose author changed nothing. The pin puts
//! the same fact at the tower, beside the step that moved. So the two ends of the entry each name
//! it, which is what `tests/tower_pin` holds.
//!
//! **The word is OPTIONAL and a tower that omits it pays nothing**: no bound, no obligation, and not
//! one token in the expansion. Absence is a road here as it is above — a tower whose answer is
//! whatever its steps arrive at has an intent nobody needed to write down.
//!
//! It is spent through [`SearchTower`]'s own `Answer` seat rather than through a fresh one, which is
//! what keeps the pin honest for a chain written EITHER way: a written last `answer` and a projected
//! canonical line are the same associated type by the time this bound is resolved, so a wholly
//! canonical tower states its intent once here and has every step's line checked against it.
//!
//! # THE WALK'S FACE IS THE OR OF ITS STEPS'
//!
//! The mutation node's assembled face one layer over, verbatim: a tower whose every step is
//! blocking walks in a blocking function, and one awaited step makes the whole walk awaited. The
//! dividend is the same one — a deployment walking a wholly synchronous tower needs no runtime —
//! and so is the reason it is an OR rather than *always async*: an awaited walk is the more general
//! and the more expensive shape, and paying for it where nothing awaits would be the framework
//! choosing a runtime on an application's behalf.
//!
//! | the tower's steps | the walk |
//! |---|---|
//! | every one blocking | `fn walk(…)` |
//! | at least one awaited | `async fn walk(…)` |
//!
//! # WHY THE STEPS ARE PARAMETERS AND NOT `&mut self`
//!
//! `type Steps = ClipText` says the declaration holds its own servers, and a walk taking `&mut
//! self` would still compile. The parameters are what make the walk callable by a deployment that
//! holds its steps ANYWHERE — one behind a door, one in a registry, one on the stack — and a caller
//! that does hold the struct passes `&mut tower.tokenize, &mut tower.encode`, which the borrow
//! checker takes as the disjoint borrows they are.
//!
//! A step's PARAMETER is positional and `__`-pinned, so a field called `question` or `options`
//! cannot shadow the two seats it sits between. `walk` itself is the declaration's own name and is
//! the one thing this expansion adds to a declaring scope: a tower whose author already wrote an
//! inherent `walk` is `E0592` naming both, which is the honest collision rather than a silent
//! shadow.
//!
//! # THE WALK REFUSES IN THE TOWER'S OWN SUM, one arm per step
//!
//! A chain of N hops has N error types and one `Result` has one. The answer is a SUM the
//! declaration mints: `<Tower>Error`, an arm per step named after the step's field, each carrying
//! that step's own `Serves::Error` / `AsyncServes::Error` PROJECTION. The assembled face's revived
//! node sum one layer over, at the one grain a tower has.
//!
//! A projection rather than an erasure is the whole of what this buys. The alternative — one named,
//! boxed refusal — costs a bound at every step (`Error + Send + Sync + 'static`) and hands a caller
//! a `dyn` it can only print; the sum costs nothing at the declaration and hands a caller back the
//! very type the step declared, so `match` on the arm reaches the error's own data.
//!
//! What the sum does demand is one thing, at one place: `source` reaches the cause, so a step's
//! error has to BE an error. That demand lands at the step's own field, per `Serves::Error`'s own
//! discipline — bound-free where it is DECLARED, demanded where it is SPENT.
//!
//! `<Tower>Error` is minted in the declaring scope, so a tower beside an author's own `<Tower>Error`
//! is `E0428` naming both — the honest collision the walk's own `E0592` already takes.
//!
//! It takes the DECLARATION's visibility, which makes a step's own visibility matter in a way the
//! walk's parameters did not: an enum arm is exactly as public as its enum, so a `pub` tower over a
//! private step is `E0446` rather than the `private_interfaces` lint. That is the projection's price
//! and it is the honest one — a tower published across a crate boundary publishes what its steps
//! refuse with, because that is what its callers have to match on.
//!
//! # THE TOWER'S OWN OPTIONS — one field per step, and the walk is what projects it
//!
//! `Serve::Options` is per SERVER and the walk's tail seat is per TOWER, so the declaration mints
//! the object that joins them: `<Tower>StepOptions`, ONE FIELD PER STEP, each field the projection
//! `Option<<Step as Serve>::Options>` of that step's own seat. A caller names some, all or none of
//! them in one value, and the walk hands each hop the field belonging to it:
//!
//! ```ignore
//! pub struct ClipTextStepOptions {
//!   tokenize: Option<<Tokenize as Serve>::Options>,      // named through `with_tokenize`
//!   encode:   Option<<ClipTextTower as Serve>::Options>, // and read back through `tokenize()`
//! }
//!
//! ClipText::walk(question, &mut tokenize, &mut encode, Some(&options))
//! ```
//!
//! # THE REQUEST'S OWN OPTIONS — one field per WORD, and the walk never learns it exists
//!
//! The object above is keyed by STEP and named at INSTALL. Its twin is keyed by the declaration's own
//! WORDS and named per REQUEST: `<Tower>SearchOptions`, whose rows are the FRAMEWORK's knobs — a walk
//! budget always, an arm weight where `expand` was written, a lane emphasis where `route(…)` named
//! the shipped weighted fan.
//!
//! ```ignore
//! pub struct ClipTextSearchOptions {
//!   budget:     Option<SearchBudget>,   // ALWAYS — no word writes it and no word takes it away
//!   arm_weight: Option<f64>,            // `expand = "Synonyms"` minted this
//! }
//! ```
//!
//! **BOTH OBJECTS EXIST BECAUSE ONLY ONE OF THEM CAN CROSS.** A step's seat is the application's own
//! type and whether it is `()` is a fact only the compiler holds, so the step-keyed object has no
//! wire face a macro could mint. Every row of the word-keyed one is a type this framework owns, so
//! all of it crosses — and the words that key it are HERE, which is why it is minted at the tower
//! grammar and not at the recipe that publishes it.
//!
//! The WALK's arity, parameters and hand-call road are untouched by any of it: the emitted `run`
//! composes tier three into a step-keyed package (`ArmWeights::over`) or into this read's own minted
//! router (`with_emphasis`) and hands the walk exactly what it always took.
//!
//! **`None` IS A LEVEL, at both grains, and it means the same thing at each**: *this call named
//! nothing*, under which a step runs at its own floor. A walk handed no options at all hands every
//! hop `None`; a walk handed options that named nothing FOR ONE STEP hands that hop `None` too. The
//! walk never invents a default on a step author's behalf, which is why the fields are `Option` and
//! not the bare seat — a bare one would need `Default`, and a projected seat is bound-free by
//! `Serve::Options`' own discipline.
//!
//! **A `()`-SEATED STEP STILL HAS A FIELD, and that is the half-row law's Rust half.** Whether
//! `<Step as Serve>::Options` is `()` is a fact only the COMPILER holds — this emission sees a type
//! and never resolves it — so the struct carries a row for every step and the `()` ones are
//! zero-sized and unreadable. What a `()` seat publishes NOTHING of is the WIRE row, and that law is
//! already shipped one emitter over: [`fuse::Row`](crate::fuse::Row) carries a `crosses` flag, its
//! Rust struct keeps every field, and its `InputObject` face publishes only the rows that cross —
//! a row that does not is simply [`None`] on the way in. The division here is the same one, with a
//! harder half for whoever emits the wire face: `fuse`'s non-crossing row is a FRAMEWORK type it
//! recognises by name, and a step's seat is a projection of somebody else's, so the decision moves
//! to where the recipe wires the arm.
//!
//! A caller who nonetheless names knobs for a `()`-seated step is refused at that step's own
//! `with_…`, whose parameter IS the seat: *expected `()`, found `Flow`*, with the caret on the knobs
//! and `note: method defined here` on the step's own field. `tests/tower_knobs` pins it.
//!
//! # THE RECORD — `DeclaredTower`, and why the tokens are restated
//!
//! A search recipe binding `crate::ClipText` expands in a pass that has never seen these tokens, so
//! four facts it needs are STATED rather than guessed: `ALL_SYNC` (whether the walk it emits is
//! awaited), `StepOptions` and `SearchOptions` (the two objects above, which a recipe could otherwise
//! only reach by mangling a name), and `STEPS` (the roster, in declaration order). The two ENDS are
//! not restated — the record's supertrait is `SearchTower`, which already carries them.
//!
//! [`Serves`]: https://docs.rs/ingraph
//! [`AsyncServes`]: https://docs.rs/ingraph
//! [`SearchTower`]: https://docs.rs/ingraph

use quote::{quote, quote_spanned};

use crate::emit::respan;

#[cfg(test)]
mod tests;

/// ONE STEP of a tower — the field that holds the server, what it answers, and which face it wears.
///
/// PLAIN, for the reason every model in this crate has plain fields: the derive today and a
/// manifest front end later reach the same emitter.
#[derive(Debug, Clone)]
pub struct StepModel {
  /// The field that holds this step's server — the step's ONE name, and the span every refusal
  /// about this step is reported at.
  pub field: syn::Ident,
  /// The server's type, as the field declared it.
  pub ty: syn::Type,
  /// What this step ANSWERS — the `answer = "…"` word, and the next step's question.
  ///
  /// [`None`] where the word was OMITTED, which is not a gap: the answer is then the step's own
  /// canonical line, `<Ty as DefaultServe>::Answer`, and the emission spells that projection
  /// wherever it would have spelled the written type. A tower's chain is derived from these and
  /// from the tower's own question either way, so nothing here is a pair that could disagree.
  pub answer: Option<syn::Type>,
  /// Whether this step wore the `async` word — which is what names the face its hop demands.
  pub awaited: bool,
  /// **THE FAN THIS STEP OPENS**, or [`None`] where the step is an ordinary 1 → 1 hop.
  ///
  /// A step's POSITION in [`TowerModel::steps`] is the segment's position, and there is no second
  /// seat that could disagree with it about where a fan starts. What a segment ENDS at is the
  /// tower's own mouth: the amendment's law is that every fan folds before it, so the fold is a
  /// fact of the walk rather than a word an author writes, and nothing here names one.
  pub fan: Option<Fan>,
  /// ⟂ **WHAT THIS STEP ANNOTATES THE QUESTION WITH** — the `annotate(type = "…")` word's type, or
  /// [`None`] where the step opens no annotation stage.
  ///
  /// A SEPARATE SEAT FROM [`fan`](Self::fan), and that separation is the model refusing to lie
  /// about itself: [`Fan`] is *one fan segment*, and an annotation neither widens nor crosses. What
  /// the two seats share is [`Stage`] — the pipeline's ORDER is the one thing all three words are
  /// about — so [`stage`](Self::stage) reads whichever seat is filled and the order check reads
  /// only that.
  ///
  /// A step fills AT MOST ONE of the two. Both written is refused at the front end, where the
  /// declaration that wrote them can be pointed at.
  pub annotation: Option<syn::Type>,
}

/// ONE ROW OF A TOWER'S REQUEST PACKAGE — the Rust member, the wire word, the type and the sentence
/// both faces spell.
///
/// A record rather than four parallel iterators, for the emitted packages' own reason one emitter
/// over: the struct field, the accessor trio, the schema entry, the `parse` arm and the `to_value`
/// arm are FIVE readings of one row, and a row carried as five lists is a row five places could come
/// to disagree about.
struct SearchRow {
  /// The Rust member — what the struct field, the accessors and both wire arms are named after.
  member: syn::Ident,
  /// The word a schema publishes it under — the member's own, in the house's camel case.
  wire: &'static str,
  /// The row's type, spanned at the word that minted it.
  ty: proc_macro2::TokenStream,
  /// What this row IS, as one sentence both the rustdoc and the schema description spend.
  noun: &'static str,
  /// WHY a request would name it — the paragraph both the rustdoc and the schema description carry,
  /// so a client reading the SDL and an author reading the docs are told the same thing.
  why: &'static str,
}

impl StepModel {
  /// **WHICH STAGE THIS STEP OPENS**, or [`None`] where it opens none and is an ordinary hop.
  ///
  /// The ONE reader of both segment seats, which is what keeps the order law a single comparison
  /// over a single roster however many words open a stage.
  #[must_use]
  pub fn stage(&self) -> Option<Stage> {
    match (&self.annotation, &self.fan) {
      (Some(_), _) => Some(Stage::Annotate),
      (None, Some(fan)) => Some(fan.stage()),
      (None, None) => None,
    }
  }
}

/// **WHERE A FAN SEGMENT SITS IN THE PIPELINE'S OWN ORDER** — the ②-before-④ opinion, as data.
///
/// The framework owns this opinion now. A question is WIDENED before it is CROSSED, because the
/// crossing turns a question into probes and a widening is an endomorphism over questions: an
/// expansion after a routing would have to widen a probe, which is a different type in a different
/// currency, chosen by whatever store the lane belongs to.
///
/// It is [`Ord`] BY DECLARATION ORDER, which is what makes the rule a comparison rather than a pair
/// of hand-written arms — and what makes the next stage one variant rather than a rewrite. The
/// resident-hop word the closed design records as stage ⟂ arrived exactly that way: one variant
/// BEFORE [`Expand`](Self::Expand), and not one line of the check that reads this enum moved.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Stage {
  /// ⟂ — the question is ANNOTATED: one question in, THE SAME question out, one fact richer.
  Annotate,
  /// ② — the question WIDENS: one question in, several questions of the same type out.
  Expand,
  /// ④ — the question CROSSES: one question in, one probe per lane out.
  Route,
}

impl Stage {
  /// The WORD a declaration opens this stage with.
  ///
  /// Here rather than on [`Fan`], because a refusal about the ORDER names a stage it has no fan in
  /// hand for: the check reads stages, and a sentence that hard-coded two spellings would start
  /// lying the round a third stage arrives.
  #[must_use]
  pub const fn word(self) -> &'static str {
    match self {
      Self::Annotate => "annotate",
      Self::Expand => "expand",
      Self::Route => "route",
    }
  }

  /// **WHY THIS STAGE RUNS WHERE IT DOES** — the clause an out-of-order refusal quotes.
  ///
  /// It hangs on the stage that was written LATE rather than on the pair, because that is what the
  /// reason is a fact about: a widening comes before a crossing because of what a WIDENING is, and
  /// an annotation comes before both because of what stages READ. A per-pair table would be `n²`
  /// sentences for a rule that has `n`.
  #[must_use]
  pub const fn why_first(self) -> &'static str {
    match self {
      Self::Annotate => {
        "a question is ANNOTATED before it is anything else, because the stages after it READ what \
         it wrote — the widening's targets and the crossing's lanes both come off the annotation — \
         and a step's answer travels downstream only, so a stage that filled the seat later would \
         fill it for nobody"
      }
      Self::Expand => {
        "a question is WIDENED before it is CROSSED, because a widening is an endomorphism over \
         QUESTIONS and a crossing turns one into PROBES — so an expansion after a routing would \
         have to widen a probe, in whatever currency the store behind that lane chose"
      }
      Self::Route => {
        "a question is CROSSED last, because a crossing is what stops there being a question: what \
         it answers is one probe per lane, and every stage of this pipeline that takes a question \
         has already run"
      }
    }
  }
}

/// **WHO CHOOSES THE LANES** — the router a `route(…)` mounted, shipped or the declaring crate's.
///
/// # The axis is CLOSED on the framework's side and OPEN past it
///
/// A BARE word is one of the routers this framework ships, and that vocabulary is closed for the
/// reason every bare vocabulary in this grammar is: a word is a promise this crate can write the
/// whole binding, which it can only keep for a type it SHIPS. A QUOTED PATH is every other router
/// there is — a type the declaring crate wrote, named the way this grammar names every type it did
/// not mint, with no vocabulary to be admitted to. MINT BARE, REFER QUOTED, read at one more
/// position.
///
/// # There is no `Owed`-shaped axis here, and that is an ANSWER rather than an omission
///
/// The aggregate's fold vocabulary carries one: the framework knows what `summing` reads and what
/// `counting` does not, so the grammar can refuse an entry that names the wrong thing. This
/// position has no such fact to check. Every shipped router is built from the ROSTER alone — the
/// lanes the slot already declares — and the one knob any of them has
/// (`ScriptWeightedFan`'s emphasis) is the lane emphasis the closed design homed in the tower's own
/// OPTIONS rather than at this word — and it lands there: the shipped weighted word mints a
/// `lane_emphasis` row on `<Tower>SearchOptions`, read off the WORD rather than off an axis entry.
/// So a shipped router owes its entry nothing beyond the wiring
/// both halves of the entry already name, and an axis answering *nothing, for all three* would be a
/// seat with one arm.
///
/// # The SHIPPED SPELLINGS are the types' own, in snake case
///
/// `fan_all`, `script_router`, `script_weighted_fan` — one word per shipped type, mechanically its
/// name. The measure vocabulary's own note records that this grammar's other closed VALUE
/// vocabularies are short nouns (`dedup(hash)`, `fold(max)`); a router is a NAMED TYPE a reader
/// looks up rather than a concept with a short noun, so the spelling that cannot drift from the
/// type it binds is the type's own. [`SHIPPED`](Self::SHIPPED) and [`shipped`](Self::shipped) are
/// the whole of the roster, and the near-miss list, the printed roster and the refusal all read off
/// them.
#[derive(Debug, Clone)]
pub enum Router {
  /// `fan_all` — every lane asked, flat.
  FanAll,
  /// `script_router` — the text cut by writing system, and only the lanes it reached asked.
  ScriptRouter,
  /// `script_weighted_fan` — every lane asked, the ones the question is written in leaned on.
  ScriptWeightedFan,
  /// A router the declaring crate wrote, as `router = "path::to::Router"` named it.
  ///
  /// Nothing here resolves it, which is the mechanism rather than a limitation: two macro
  /// expansions cannot see each other, so the path is EMITTED and rustc resolves it at the span of
  /// the string its author wrote.
  Declared(syn::Path),
}

impl Router {
  /// The routers this framework ships, in the order a refusal lists them.
  ///
  /// The near-miss list for a bare word inside `route(…)` is read off this, so the words a
  /// suggestion offers and the words a sentence names cannot drift apart.
  pub const SHIPPED: [&'static str; 3] = ["fan_all", "script_router", "script_weighted_fan"];

  /// The shipped router a bare word names, or [`None`] where the word is none of them.
  #[must_use]
  pub fn shipped(word: &str) -> Option<Self> {
    match word {
      "fan_all" => Some(Self::FanAll),
      "script_router" => Some(Self::ScriptRouter),
      "script_weighted_fan" => Some(Self::ScriptWeightedFan),
      _ => None,
    }
  }

  /// The word this router was written as — a shipped one's own spelling, or the declared path's.
  #[must_use]
  pub fn as_written(&self) -> String {
    match self {
      Self::FanAll => Self::SHIPPED[0].to_owned(),
      Self::ScriptRouter => Self::SHIPPED[1].to_owned(),
      Self::ScriptWeightedFan => Self::SHIPPED[2].to_owned(),
      Self::Declared(path) => quote::ToTokens::to_token_stream(path).to_string(),
    }
  }

  /// **THE TYPE A WORD NAMES**, as the emission spells it — a shipped router's path, or the
  /// declaring crate's own verbatim.
  ///
  /// `question` is what the step is HANDED, and it fills the two shipped routers that carry a
  /// question parameter. [`ScriptRouter`](Self::ScriptRouter) carries none — it is spelled for text
  /// and says so in its own `Question = str` — so the argument goes unspent there, which is a fact
  /// about those three types rather than a case this function invents.
  ///
  /// A DECLARED router is emitted exactly as it was written and resolved by rustc at the span of the
  /// string its author wrote, which is the same mechanism [`Declared`](Self::Declared) states: two
  /// macro expansions cannot see each other, so nothing here looks a path up.
  #[must_use]
  pub fn spelled(
    &self,
    krate: &syn::Path,
    question: &proc_macro2::TokenStream,
  ) -> proc_macro2::TokenStream {
    match self {
      Self::FanAll => quote!(#krate::__private::route::FanAll<#question>),
      Self::ScriptRouter => quote!(#krate::__private::route::ScriptRouter),
      Self::ScriptWeightedFan => quote!(#krate::__private::route::ScriptWeightedFan<#question>),
      Self::Declared(path) => quote!(#path),
    }
  }
}

/// **ONE FAN SEGMENT** — which kind of fan a step opens, and the types the segment is wired with.
///
/// The amendment's law in the model: a tower MAY contain fanning segments, every fan folds before
/// the tower's mouth, and the OUTER contract stays 1 → 1. What is recorded here is the OPENING —
/// which segments a declaration wrote, what mounts each, and (through the step that holds it) where
/// it starts. The walk that spends them is the emission's, and the fold is the walk's.
///
/// # Every question a fan segment must answer is answered HERE, and none by silence
///
/// | the question | where the answer is |
/// |---|---|
/// | which KIND of fan | this enum's own variant, and [`stage`](Self::stage) for the order it sits in |
/// | what MOUNTS it | [`Expand::expander`](Self::Expand) / [`Route::router`](Self::Route) |
/// | what it is WIRED TO | [`Route::slot`](Self::Route) — and ② is wired to nothing, because an endomorphism crosses no boundary |
/// | WHERE it opens | the position of the [`StepModel`] that holds it |
/// | which WORD wrote it | [`word`](Self::word) |
/// | which FACE it wears | the SEAM's and never the step's `async` word — see below |
/// | where it FOLDS | the tower's mouth, by the amendment's law; no word names one |
/// | what a reader ACROSS THE WALL sees | nothing, on purpose — see below |
/// | what a shipped router OWES its entry | nothing, for all three — see [`Router`] |
///
/// # WHAT A READER ACROSS THE EXPANSION WALL SEES, which is STILL NOTHING — and the assembly is why
///
/// `DeclaredTower` — the record a search recipe reads a bound tower through — is deliberately not
/// extended here. Its three facts are what a RECIPE needs to write a binding (the walk's face, the
/// options object, the roster), and a recipe binds a tower by its outer contract, which the
/// amendment leaves 1 → 1 exactly as it was.
///
/// The assembly has since arrived, which is when that sentence was owed a re-reading, and the answer
/// held: what the assembly needs is to read a fan step's own FIELD — is an expander mounted, does
/// this fan have a router — and no roster row could carry that, because a row is a `const` and a
/// seat is a value. So the gate is EMITTED, where the field is concrete, and what crosses the wall
/// is the two methods of [`AssembledTower`] rather than a fact about the words. A fan row on the
/// record would still be a fact nothing reads.
///
/// [`AssembledTower`]: https://docs.rs/ingraph
///
/// # THE FAN'S FACE IS THE SEAM'S, and the step's own word still means what it meant
///
/// A step's `async` names the face THAT STEP'S SERVER wears, and a fan word does not touch it.
/// What face the FAN itself wears is not an author's to choose: routing is pure computation over a
/// question and a roster, so `LaneRouter` has one face and it is the blocking one, and the
/// expansion seam's call seat is the awaited `AsyncQueryExpander` that a blocking expander reaches
/// through the lift bridge. Neither is a word, so neither is a seat here.
///
/// # The two halves are DELIBERATELY UNLIKE, and this model does not make them rhyme
///
/// An EXPANDER is a hook — a policy a deployment picks at launch, held erased — so ② names one
/// type and the declaration's word is the DEFAULT a deployment may override. A ROUTER is a
/// capability — known at the call, mounted monomorphised — so ④ names the router AND the slot it is
/// wired to, because what makes a mis-wiring `E0271` at the seat rather than a conversion in the
/// middle is an EQUALITY between two types this model has to be holding both of.
#[derive(Debug, Clone)]
pub enum Fan {
  /// ② **EXPAND** — the endomorphism: one question in, several questions of the SAME type out.
  Expand {
    /// The expander this declaration DEFAULTS to, as `expand(type = "…")` named it.
    ///
    /// A path and never a bare word: this framework ships no expander at all, so there is nothing
    /// for a bare vocabulary to name. A synonym table, a spelling fixer and a translator are all
    /// the declaring crate's, which is why the seam is public and the escape is the only road.
    expander: syn::Path,
  },
  /// ④ **ROUTE** — the crossing: one question in, one probe per lane out.
  Route {
    /// Who chooses the lanes — a shipped router's bare word, or a path to the declaring crate's.
    router: Router,
    /// The SLOT whose lanes are asked, as `slot = "…"` named it.
    ///
    /// This is the other half of the equality the wiring is checked by: a router mounted here
    /// answers in `<Slot as LanedStore>::Probe` and anything else is `E0271` at the seat. The slot
    /// is the pairing `(elected field × engine)` a declaration's own expansion minted, so it is a
    /// type this declaration did not mint and it arrives QUOTED.
    slot: syn::Path,
  },
}

impl Fan {
  /// WHICH STAGE this segment is — the ②-before-④ order, read off the fan itself.
  #[must_use]
  pub const fn stage(&self) -> Stage {
    match self {
      Self::Expand { .. } => Stage::Expand,
      Self::Route { .. } => Stage::Route,
    }
  }

  /// The WORD that wrote this fan, as a declaration spells it.
  ///
  /// The STAGE's own, rather than a second table: a refusal about a fan and a refusal about the
  /// order between two both name a word, and a spelling written twice is a spelling two places
  /// could disagree about.
  #[must_use]
  pub const fn word(&self) -> &'static str {
    self.stage().word()
  }
}

/// A validated tower declaration, ready to emit.
///
/// PLAIN, for [`StepModel`]'s reason.
#[derive(Debug, Clone)]
pub struct TowerModel {
  /// The path to the `ingraph` crate itself — `::ingraph` unless `#[ingraph(crate = "…")]` named
  /// another.
  pub krate: syn::Path,
  /// The declared type — what the connectivity is stated over and what the walk is minted on.
  pub name: syn::Ident,
  /// The declaration's own visibility, which the walk takes: a tower nobody outside the crate can
  /// name has no walk anybody outside it could call.
  pub vis: syn::Visibility,
  /// What the WHOLE tower is asked — the `question(type = "…")` word, and the first step's
  /// question.
  ///
  /// [`None`] where the word was OMITTED, on [`StepModel::answer`]'s road: the tower is then asked
  /// what its FIRST STEP is canonically asked, `<Ty as DefaultServe>::Question`.
  pub question: Option<syn::Type>,
  /// **THE HEAD PIN** — the `answer = "…"` word at the tower, and the one word in this model that
  /// DECIDES NOTHING.
  ///
  /// A tower answers what its LAST STEP answers, whatever is written here: this seat holds an
  /// author's stated INTENT, and what the emission does with it is demand that the derivation agree.
  /// See the module note for the double entry it is one half of.
  ///
  /// [`None`] where the word was omitted, under which nothing is emitted and nothing is demanded —
  /// so it is the one seat whose absence costs a declaration not one token.
  pub answer: Option<syn::Type>,
  /// The steps, in declaration order. NEVER EMPTY: a tower with no step is refused at the front
  /// end, there being no chain to state and no answer to name.
  pub steps: Vec<StepModel>,
}

impl TowerModel {
  /// The CONNECTIVITY, the HEAD PIN, the TWO OPTIONS OBJECTS, the RECORD, the REFUSAL SUM, the WALK
  /// and the ASSEMBLY ROW — see the module note for what each says.
  ///
  /// The pin comes second because it is a claim ABOUT the impl above it, and it is [`Option`]
  /// because a tower that wrote no head word emits nothing here at all. The assembly row comes LAST
  /// because it is the only one that CALLS another: its run is the walk above it at a fixed arity.
  #[must_use]
  pub fn emit(&self) -> proc_macro2::TokenStream {
    let connectivity = self.connectivity();
    let pin = self.pin();
    let options = self.options();
    let asked = self.search_options();
    let declared = self.declared();
    let refusal = self.refusal();
    let rendering = self.rendering();
    let walk = self.walk();
    let assembly = self.assembly();
    quote! {
      #connectivity
      #pin
      #options
      #asked
      #declared
      #refusal
      #rendering
      #walk
      #assembly
    }
  }

  /// Whether the walk is AWAITED — the OR law over the steps' own words, AND the widening.
  ///
  /// **A WIDENING MAKES A WALK AWAITED WHATEVER ITS STEPS SAY.** The expand seam's call face is the
  /// awaited [`AsyncQueryExpander`], which is where a deployment's own expander reaches a model; a
  /// blocking one rides it through the lift bridge and the bridge runs one way, there being no
  /// `block_on` in this framework. So the segment's face is not an author's word to choose, and this
  /// is where the OR law reads it — the same law, one more term.
  ///
  /// [`AsyncQueryExpander`]: https://docs.rs/ingraph
  #[must_use]
  pub fn awaited(&self) -> bool {
    self.steps.iter().any(|step| step.awaited) || self.expand_at().is_some()
  }

  /// WHERE THE WIDENING OPENS, or [`None`] where this tower opens none.
  ///
  /// One position and never a list: the grammar holds a tower to ONE segment of each kind, so the
  /// first is the only one.
  #[must_use]
  pub fn expand_at(&self) -> Option<usize> {
    self
      .fans()
      .find(|(_, _, fan)| fan.stage() == Stage::Expand)
      .map(|(at, _, _)| at)
  }

  /// ⟂ WHERE THE ANNOTATION STAGE OPENS, or [`None`] where this tower opens none.
  ///
  /// One position and never a list, for [`expand_at`](Self::expand_at)'s reason at the one word
  /// whose second occurrence would be dead rather than merely unlawful: fill-if-absent means a
  /// second stage over the same seat runs only where the first did not fill it, which is nowhere.
  #[must_use]
  pub fn annotate_at(&self) -> Option<usize> {
    self.steps.iter().position(|step| step.annotation.is_some())
  }

  /// WHERE THE CROSSING OPENS, or [`None`] where this tower opens none.
  #[must_use]
  pub fn route_at(&self) -> Option<usize> {
    self
      .fans()
      .find(|(_, _, fan)| fan.stage() == Stage::Route)
      .map(|(at, _, _)| at)
  }

  /// **EVERY FAN SEGMENT THIS TOWER OPENS**, in declaration order — the position, and the fan.
  ///
  /// The position is the step's own index, which is the segment's: a fan is a fact ABOUT a step, so
  /// there is one roster and the place a segment starts is where it sits in it.
  pub fn fans(&self) -> impl Iterator<Item = (usize, &StepModel, &Fan)> {
    self
      .steps
      .iter()
      .enumerate()
      .filter_map(|(at, step)| step.fan.as_ref().map(|fan| (at, step, fan)))
  }

  /// Whether this tower FANS AT ALL — false for every tower written before the amendment, which is
  /// what makes those the degenerate case rather than a case.
  #[must_use]
  pub fn fanned(&self) -> bool {
    self.steps.iter().any(|step| step.fan.is_some())
  }

  /// The STEP-KEYED options object's name — the declaration's own, with `StepOptions` after it.
  ///
  /// Derived rather than declared, for [`error_name`](Self::error_name)'s reason and with the same
  /// price: this is one of the names a tower mints in its declaring scope, so a tower beside an
  /// author's own `<Tower>StepOptions` is `E0428` naming both.
  ///
  /// The word STEP is load-bearing rather than decorative. There are two options objects now and
  /// they are two CLOCKS — this one is keyed by step and named at INSTALL, and
  /// [`search_options_name`](Self::search_options_name)'s is keyed by the declaration's own words and
  /// named per REQUEST — so a bare `<Tower>Options` would have been the one name that could not say
  /// which of them a reader was holding.
  #[must_use]
  pub fn step_options_name(&self) -> syn::Ident {
    quote::format_ident!("{}StepOptions", self.name, span = self.name.span())
  }

  /// The WORD-KEYED options object's name — the declaration's own, with `SearchOptions` after it.
  ///
  /// [`step_options_name`](Self::step_options_name)'s twin at the other clock, minted under the same
  /// collision rule and for the same reason.
  #[must_use]
  pub fn search_options_name(&self) -> syn::Ident {
    quote::format_ident!("{}SearchOptions", self.name, span = self.name.span())
  }

  /// **WHETHER THIS DECLARATION'S ④ WORD NAMED THE SHIPPED WEIGHTED FAN** — the one token that mints
  /// a lane-emphasis row.
  ///
  /// TOKEN-KEYED and never type-resolved, which is the whole of why the row is mintable at all: a
  /// bare word in `route(router = …)` is one of the routers this framework SHIPS, so the emitter
  /// knows the type, its knob and its constructor. A QUOTED PATH is the declaring crate's own router
  /// and this answers [`None`] for it — not because such a router has no knobs but because nothing
  /// here can know what they are, and a published field the emission could never spend is worse than
  /// no field at all.
  #[must_use]
  pub fn weighted_crossing(&self) -> Option<(usize, &StepModel)> {
    self.fans().find_map(|(at, step, fan)| match fan {
      Fan::Route {
        router: Router::ScriptWeightedFan,
        ..
      } => Some((at, step)),
      Fan::Route { .. } | Fan::Expand { .. } => None,
    })
  }

  /// The refusal sum's name — the declaration's own, with `Error` after it.
  ///
  /// Derived rather than declared, which is the assembled face's rule one layer over: the
  /// declaration's name IS the vocabulary's name, and a second word for it would be a name two
  /// spellings could disagree about. Minted at the declaration's own ident, so a tower beside an
  /// author's existing `<Tower>Error` collides where a reader can see both.
  #[must_use]
  pub fn error_name(&self) -> syn::Ident {
    quote::format_ident!("{}Error", self.name, span = self.name.span())
  }

  /// A step's ARM in the refusal sum — the field's own name, translated to a variant's casing.
  ///
  /// `heck`'s upper camel case rather than a raised initial, which is the assembled face's own
  /// choice and law: a Rust field name is snake case by the language's convention rather than by
  /// anybody's word, so re-casing it is a translation and not a rewrite of somebody's name.
  fn variant(step: &StepModel) -> syn::Ident {
    use heck::ToUpperCamelCase as _;
    use syn::ext::IdentExt as _;

    quote::format_ident!(
      "{}",
      step.field.unraw().to_string().to_upper_camel_case(),
      span = step.field.span()
    )
  }

  /// One seat of a step's own CANONICAL LINE, spelled as the projection it is.
  ///
  /// This is the whole mechanism of the omissible words: a written `answer = "…"` names the type
  /// itself, and an omitted one names `<Ty as DefaultServe>::Answer`, which is a CONCRETE
  /// projection rather than a variable the compiler is asked to solve for. Selection therefore
  /// never comes from inference — a step with several `Serves` impls is still unambiguous, because
  /// the canonical line is one line per TYPE and names no face.
  ///
  /// Spanned at the step's own field, so a type with no canonical line is `E0277` where the type
  /// was written, and `DefaultServe`'s own `on_unimplemented` note is what names the two roads out.
  fn canonical(&self, step: &StepModel, seat: &str) -> proc_macro2::TokenStream {
    let at_field = step.field.span();
    let ty = &step.ty;
    let line = respan(
      {
        let krate = &self.krate;
        quote!(#krate::__private::drive::DefaultServe)
      },
      at_field,
    );
    let seat = quote::format_ident!("{seat}", span = at_field);
    quote_spanned!(at_field=> <#ty as #line>::#seat)
  }

  /// What the WHOLE tower is asked — the written word, or the first step's canonical question.
  ///
  /// The model is never built empty, so the last fallback is a shape rather than a case.
  fn asked(&self) -> proc_macro2::TokenStream {
    match (&self.question, self.steps.first()) {
      (Some(question), _) => quote!(#question),
      (None, Some(head)) => self.canonical(head, "Question"),
      (None, None) => quote!(()),
    }
  }

  /// What ONE STEP answers — the written word, or that step's own canonical answer.
  fn answered(&self, step: &StepModel) -> proc_macro2::TokenStream {
    step
      .answer
      .as_ref()
      .map_or_else(|| self.canonical(step, "Answer"), |answer| quote!(#answer))
  }

  /// What the whole tower ANSWERS — the last step's answer, DERIVED and never declared.
  ///
  /// Named for what it is rather than for the word beside it, because there IS a word beside it now:
  /// [`answer`](Self::answer) is an author's stated intent and this is what the chain arrives at, and
  /// the whole of the head pin is that the second is demanded to be the first.
  ///
  /// The model is never built empty, so the fallback is a shape rather than a case: a hand-built
  /// model with no step would state a tower answering nothing, which is what `()` says.
  ///
  /// # A FANNED TOWER ANSWERS THE FUSED LIST, and it is still ONE value
  ///
  /// The amendment's outer contract is 1 → 1, so the mouth hands back one thing — and what a fan
  /// produces before it folds is N ranked streams, so the one thing is what the fold makes of them:
  /// `Vec<Fused<Root, Evidence>>`. The two parameters are PROJECTED off the tail's own answer through
  /// [`RankedStream`], because they are the tail author's types and this pass sees only the tokens
  /// that named them — see [`tail`](Self::tail) for the seam's whole reason.
  fn derived(&self) -> proc_macro2::TokenStream {
    let Some(tail) = self.steps.last() else {
      return quote!(());
    };
    let answers = self.flows(self.steps.len() - 1);
    if !self.fanned() {
      return answers;
    }
    let krate = &self.krate;
    let at_field = tail.field.span();
    let stream = respan(quote!(#krate::__private::retrieve::RankedStream), at_field);
    let fused = respan(quote!(#krate::__private::retrieve::Fused), at_field);
    quote_spanned! {at_field=>
      ::std::vec::Vec<#fused<
        <#answers as #stream>::Root,
        <#answers as #stream>::Evidence,
      >>
    }
  }

  /// THE TAIL'S OWN ANSWER — what one `(arm × lane)` cell of a fan found, before the fold.
  ///
  /// The LAST step's, whatever else the tower does: a fan folds at the mouth, so the value the fold
  /// is handed is the value the chain arrived at.
  fn tail(&self) -> proc_macro2::TokenStream {
    match self.steps.len().checked_sub(1) {
      Some(last) => self.flows(last),
      None => quote!(()),
    }
  }

  /// What step `at` is HANDED: the tower's own question at the head of the chain, and what the step
  /// before it HANDS ON everywhere after.
  fn takes(&self, at: usize) -> proc_macro2::TokenStream {
    match at
      .checked_sub(1)
      .filter(|before| *before < self.steps.len())
    {
      Some(before) => self.flows(before),
      None => self.asked(),
    }
  }

  /// **WHAT STEP `at` HANDS ON** — the chain's type on the far side of it, which is the next step's
  /// question.
  ///
  /// For every step but one this is simply what that step ANSWERS. **⟂ is the exception, and being
  /// the exception is what the stage IS**: an annotation step is asked a question and hands back the
  /// same question, so the chain's type does not move across it and what it hands on is what it
  /// took. That is why the seat has no `answer` word to read — there is nothing there a word could
  /// decide, and the front end refuses one by name rather than accepting a second spelling of the
  /// type one line above.
  ///
  /// It recurses through [`takes`](Self::takes) and terminates on the tower's own question: each
  /// step asks only about the step BEFORE it, and step `0` asks nothing.
  fn flows(&self, at: usize) -> proc_macro2::TokenStream {
    match self.steps.get(at) {
      Some(step) if step.annotation.is_some() => self.takes(at),
      Some(step) => self.answered(step),
      None => quote!(()),
    }
  }

  /// The FACE this step's word chose, reached through the shelf.
  fn face(&self, step: &StepModel) -> proc_macro2::TokenStream {
    let krate = &self.krate;
    if step.awaited {
      quote!(#krate::__private::drive::AsyncServes)
    } else {
      quote!(#krate::__private::drive::Serves)
    }
  }

  /// The tower's citizenship, and the chain in its `where` clause — one predicate per step, each
  /// spanned at the field it is about.
  fn connectivity(&self) -> proc_macro2::TokenStream {
    let krate = &self.krate;
    let name = &self.name;
    let question = self.asked();
    let answer = self.derived();
    let hops = self.hops();
    quote! {
      impl #krate::__private::retrieve::SearchTower for #name
      where
        #(#hops,)*
      {
        type Question = #question;
        type Answer = #answer;
        type Steps = #name;
      }
    }
  }

  /// **THE CHAIN, AS PREDICATES** — one per step, each spanned at the field it is about.
  ///
  /// A function rather than a closure inside [`connectivity`](Self::connectivity) because the chain
  /// is stated at TWO impls now: the citizenship, which is what it says, and the assembly row, which
  /// RESTATES it in its own `where` clause so that a tower whose chain is broken earns no second
  /// diagnostic there. Both spend one derivation, so no two impls can disagree about which hops a
  /// tower has.
  fn hops(&self) -> Vec<proc_macro2::TokenStream> {
    let krate = &self.krate;
    self
      .steps
      .iter()
      .enumerate()
      .flat_map(|(at, step)| {
        let at_field = step.field.span();
        let ty = &step.ty;
        let takes = self.takes(at);
        let answers = self.flows(at);
        // ⟂ **AN ANNOTATION STEP IS A HOP WITH BOTH ENDS PINNED TO ONE TYPE**, and one more predicate
        // beside it. The endomorphism is not an author's claim here — it is the STAGE, so the two ends
        // are written from `takes` alone and a server that answers something else is `E0277` at the
        // field naming the impl it does not have. The second predicate is what makes fill-if-absent
        // real: the question has to be able to SAY whether the caller already filled the seat, and a
        // question type that cannot is refused at the step rather than at whatever line first read it.
        if let Some(annotation) = &step.annotation {
          let seam = respan(
            quote!(#krate::__private::retrieve::AnnotatedQuestion),
            at_field,
          );
          let face = respan(self.face(step), at_field);
          return vec![
            quote_spanned!(at_field=> #ty: #face<#takes, #takes>),
            quote_spanned!(at_field=> #takes: #seam<#annotation>),
          ];
        }
        // A FAN STEP IS NOT A HOP, and that is the emission's own finding rather than a choice. Its
        // field holds the SEGMENT'S SEAT — the value a deployment assembles an expander or a router
        // into — and a seat answers no `Serves` verb, so what is demanded here is the CANONICAL LINE
        // that seat states, at both of the chain's ends. A widening's line is the endomorphism
        // (`Question = Answer = Q`), so a seat mounted for one question inside a chain carrying
        // another is `E0271` naming both, at the field.
        if step.fan.is_some() {
          let line = respan(
            {
              let krate = &self.krate;
              quote!(#krate::__private::drive::DefaultServe)
            },
            at_field,
          );
          // **ONLY THE ENDS A DECLARATION WROTE ARE BOUND**, and that is the language rather than a
          // choice: an omitted word makes the end the seat's OWN projection, so binding it would state
          // `T: DefaultServe<Answer = <T as DefaultServe>::Answer>` — a predicate that refers to
          // itself, which rustc reports as `E0275` *overflow evaluating the requirement* at the
          // attribute. What is left when both are omitted is the demand that the seat state a
          // canonical line at all, which is the one thing still worth saying.
          let mut bindings: Vec<proc_macro2::TokenStream> = Vec::new();
          if at > 0 || self.question.is_some() {
            bindings.push(quote_spanned!(at_field=> Question = #takes));
          }
          if step.answer.is_some() {
            bindings.push(quote_spanned!(at_field=> Answer = #answers));
          }
          let stated = if bindings.is_empty() {
            quote_spanned!(at_field=> #ty: #line)
          } else {
            quote_spanned!(at_field=> #ty: #line<#(#bindings),*>)
          };
          let mut demanded = vec![stated];
          // **THE DECLARED DEFAULT IS CHECKED HERE**, even though mounting it is the assembly's. What
          // `expand = "…"` names is the expander a deployment gets unless it names another, and the
          // one thing this pass can say about it is the one thing that matters: it must be able to
          // widen the question this chain is carrying. A table written for some other question type is
          // `E0277` at the field, in the round the word was written, rather than at whatever later
          // round tries to mount it.
          if let Some(Fan::Expand { expander }) = &step.fan {
            let krate = &self.krate;
            let seam = respan(
              quote!(#krate::__private::retrieve::AsyncQueryExpander),
              at_field,
            );
            demanded.push(quote_spanned!(at_field=> #expander: #seam<#takes>));
          }
          // **THE WIRING'S OWN EQUALITY**, and the reason the crossing names two things rather than
          // one: a router answers in some currency and a slot's lanes are asked in some currency, and
          // the whole of what makes a mis-wiring a compile error AT THE SEAT is that this predicate is
          // holding both halves. A router bolted to the wrong slot is `E0271` here, at the step's own
          // field, rather than a conversion failure somewhere in the middle of a read.
          if let Some(Fan::Route { router, slot }) = &step.fan {
            let krate = &self.krate;
            let router = router.spelled(krate, &takes);
            let seam = respan(quote!(#krate::__private::route::LaneRouter), at_field);
            let laned = respan(quote!(#krate::__private::lane::LanedStore), at_field);
            demanded
              .push(quote_spanned!(at_field=> #router: #seam<Routed = <#slot as #laned>::Probe>));
          }
          return demanded;
        }
        // The FACE is respanned rather than merely minted at the field, for the reason the origin
        // layer's double entry respans its own subject: `quote_spanned!` sets the span of the tokens
        // it MINTS and an interpolated path keeps the one it was written with, so a predicate whose
        // trait path still carried the emitter's span would report the broken hop at the macro
        // instead of at the step. Respanning is safe where the span is a real one from the same file,
        // which a field's name always is: resolution is unchanged and only the report moves.
        let face = respan(self.face(step), at_field);
        vec![quote_spanned!(at_field=> #ty: #face<#takes, #answers>)]
      })
      .collect()
  }

  /// **THE HEAD PIN** — the word's half of the double entry, and [`None`] where no word was written.
  ///
  /// One anonymous `const`, the source layer's own shape: a helper whose `where` clause names the
  /// answer the WORD claimed, spent over the declared type, so the compiler resolves the tower's own
  /// `SearchTower::Answer` — which the chain DERIVED — against it. Agreement compiles to nothing;
  /// disagreement is `E0271` naming both types.
  ///
  /// # Two spans, and each is chosen for what lands on it
  ///
  /// The CALL carries the word's span, because rustc reports a projection mismatch at the site that
  /// instantiated it: the caret has to land on the type an author wrote, that being the one token of
  /// this pair a tower's own declaration can change. The declared type is respanned onto the word for
  /// the reason the source layer's is — [`quote_spanned!`] sets the span of the tokens it MINTS and
  /// an interpolated ident keeps its own, so a turbofish left at the declaration would put the
  /// primary caret on the struct and leave the word in a note.
  ///
  /// The HELPER keeps the emitter's span and is reported at the attribute, which is where its
  /// *required by a bound in …* note lands. Its NAME is half the diagnostic and is written as a
  /// sentence for that reason: a projection has no `on_unimplemented` to carry one, so the
  /// identifier is the only place this join can say what it was checking.
  ///
  /// # It demands `SearchTower` and nothing beyond it
  ///
  /// The bound is over the tower's own citizenship, so a tower whose CHAIN is broken has already
  /// been refused by [`connectivity`](Self::connectivity) and earns one more `E0277` here saying it
  /// is not a search tower. That cost is real and it is paid only by declarations that wrote the
  /// word — a tower with no pin emits none of this, so no golden that does not pin can move.
  fn pin(&self) -> Option<proc_macro2::TokenStream> {
    use syn::spanned::Spanned as _;

    let claimed = self.answer.as_ref()?;
    let krate = &self.krate;
    let at = claimed.span();
    let audit = quote::format_ident!("__ingraph_a_tower_answers_the_type_its_answer_word_named");
    let spent = respan(
      {
        let name = &self.name;
        quote!(#name)
      },
      at,
    );
    let spend = quote_spanned!(at=> const _: fn() = #audit::<#spent>;);
    Some(quote! {
      const _: () = {
        fn #audit<__IgTower>()
        where
          __IgTower: #krate::__private::retrieve::SearchTower<Answer = #claimed>,
        {
        }

        #spend
      };
    })
  }

  /// ONE STEP'S KNOBS SEAT, spelled as the projection it is — `<Ty as Serve>::Options`.
  ///
  /// The BASE and never a face, which is the whole reason the seat came down there: a projection
  /// calls no verb, so naming a face here would decide the step's MODE on the wire's behalf and a
  /// tower is kind-agnostic. Spanned at the step's own field, so a type that is no server at all is
  /// `E0277` where it was written.
  fn seat(&self, step: &StepModel) -> proc_macro2::TokenStream {
    let at_field = step.field.span();
    let ty = &step.ty;
    let base = respan(
      {
        let krate = &self.krate;
        quote!(#krate::__private::drive::Serve)
      },
      at_field,
    );
    quote_spanned!(at_field=> <#ty as #base>::Options)
  }

  /// **THE TOWER'S OWN OPTIONS** — one field per step, and the three ways a caller names one.
  ///
  /// See the module note for the shape and for why the fields are `Option`. What is here is the
  /// SURFACE, and it is the crate's own options discipline rather than a public-field struct: the
  /// fields are private, so the only roads to a step's knobs are the two the emission writes, and a
  /// value parsed off a wire can be narrowed in place afterwards.
  ///
  /// | road | shape | who writes it |
  /// |---|---|---|
  /// | `with_<step>(knobs)` | consuming, takes the seat | a caller BUILDING a request |
  /// | `set_<step>(Option)` | in place, takes the option | a holder NARROWING somebody else's |
  /// | `<step>()` | `Option<&seat>` | the walk, and anybody reading one back |
  ///
  /// `set_…` takes an [`Option`] where `with_…` takes the seat, which is [`Flow`]'s own division one
  /// layer down: *this call names nothing* has to stay sayable after construction, and that is what
  /// a holder narrowing a parsed package needs and a builder never does.
  ///
  /// # The one collision it can have, and it is the honest one
  ///
  /// A getter is named after its step, so a tower with a step called `new` mints two `new`s and is
  /// `E0592` naming both. The family already takes that trade at `walk` and at `<Tower>Error`; it is
  /// stated here because a STEP's name is an author's own word rather than the declaration's.
  ///
  /// [`Flow`]: https://docs.rs/ingraph
  fn options(&self) -> proc_macro2::TokenStream {
    use syn::ext::IdentExt as _;

    let vis = &self.vis;
    let name = self.step_options_name();
    let rows = self.steps.iter().map(|step| {
      let field = &step.field;
      let seat = self.seat(step);
      let doc = crate::emit::leading(&format!(
        "What the `{field}` step is served with, where this call names it.",
        field = step.field,
      ));
      quote! {
        #[doc = #doc]
        #field: ::core::option::Option<#seat>
      }
    });
    let nothing = self.steps.iter().map(|step| {
      let field = &step.field;
      quote!(#field: ::core::option::Option::None,)
    });
    let knobs = self.steps.iter().map(|step| {
      let field = &step.field;
      let bare = field.unraw();
      let seat = self.seat(step);
      let with = quote::format_ident!("with_{bare}", span = step.field.span());
      let set = quote::format_ident!("set_{bare}", span = step.field.span());
      // The PARAMETER keeps the field's own `r#`, because a step legally called `r#type` unraw'd
      // into a parameter position would be the keyword itself. The two GLUED names take the unraw'd
      // spelling, since `with_type` is a name and not a keyword.
      let named = crate::emit::leading(&format!(
        "The same options, naming what the `{field}` step is served with.\n\nA step whose server \
         seats `()` takes NO knobs — its seat is the ANSWER *this server is configured with \
         nothing* — so this parameter is `()` there and knobs written for one are refused right \
         here, at the step's own name.",
        field = step.field,
      ));
      let narrowed = crate::emit::leading(&format!(
        "What the `{field}` step is served with, named IN PLACE — including named back to nothing.",
        field = step.field,
      ));
      let read = crate::emit::leading(&format!(
        "What this call names for the `{field}` step, or [`None`] where it names nothing — under \
         which that step runs at its own floor.",
        field = step.field,
      ));
      quote! {
        #[doc = #named]
        #[inline]
        #[must_use]
        #vis fn #with(mut self, #field: #seat) -> Self {
          self.#field = ::core::option::Option::Some(#field);
          self
        }

        #[doc = #narrowed]
        #[inline]
        #vis fn #set(&mut self, #field: ::core::option::Option<#seat>) -> &mut Self {
          self.#field = #field;
          self
        }

        #[doc = #read]
        #[inline]
        #[must_use]
        #vis fn #field(&self) -> ::core::option::Option<&#seat> {
          ::core::option::Option::as_ref(&self.#field)
        }
      }
    });
    let doc = crate::emit::leading(&format!(
      "What a caller names for [`{name}`]'s steps — ONE FIELD PER STEP, each that step's own \
       `Serve::Options` seat.\n\nEvery field starts at nothing, and nothing is a LEVEL rather than \
       a gap: a step this names nothing for is served under `None` and runs at its own floor, which \
       is what a step author's own default is for. A step whose server seats `()` takes no knobs at \
       all, so its row here is zero-sized and nothing reads it.",
      name = self.name,
    ));
    let fresh = crate::emit::leading(&format!(
      "Options that name NOTHING — every step of [`{name}`] at its own floor.",
      name = self.name,
    ));
    let defaulted = crate::emit::leading(&format!(
      "The unnamed options — [`{name}::new`], and one source of truth for them.",
      name = name,
    ));
    quote! {
      #[doc = #doc]
      // THE PACKAGE FAMILY'S OWN THREE, and a tower's options join them rather than standing apart.
      //
      // MEASURED, at the first real binding: a search recipe seats a bound tower's options on its own
      // package — `Option<<Tower as DeclaredTower>::StepOptions>` — and every package in this framework
      // is built through one emitter that derives exactly these. A tower whose options derived
      // nothing could be walked from Rust and could not be BOUND, and the refusal was an `E0277`
      // about `Debug` reported at the recipe's attribute, naming a type the recipe's author never
      // wrote.
      //
      // The demand lands on `Serve::Options`, where a server's own knobs are declared. That is where
      // every other options object in this tree already pays it, and a configuration type that
      // cannot be compared or printed is the exception rather than the rule.
      #[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq)]
      #vis struct #name {
        #(#rows,)*
      }

      impl #name {
        #[doc = #fresh]
        #[inline]
        #[must_use]
        #vis const fn new() -> Self {
          Self {
            #(#nothing)*
          }
        }

        #(#knobs)*
      }

      #[doc = #defaulted]
      impl ::core::default::Default for #name {
        #[inline]
        fn default() -> Self {
          Self::new()
        }
      }
    }
  }

  /// **THE RECORD** — what this declaration said, for the readers that cannot see these tokens.
  ///
  /// Four facts and no fifth: the walk's face, the TWO options objects, and the roster. The two ENDS
  /// ride the supertrait, so nothing here can disagree with the connectivity about what a tower is
  /// asked.
  ///
  /// It carries NO `where` clause, and that is deliberate: the connectivity states the chain once,
  /// and a broken tower that restated it here would report every broken hop twice. What a broken
  /// tower gets instead is one refusal saying it is not a search tower — which is the truth the
  /// connectivity already reported the reason for.
  fn declared(&self) -> proc_macro2::TokenStream {
    let krate = &self.krate;
    let name = &self.name;
    let step_options = self.step_options_name();
    let search_options = self.search_options_name();
    let all_sync = !self.awaited();
    let rows = self.steps.iter().map(|step| {
      use syn::ext::IdentExt as _;

      let field = step.field.unraw().to_string();
      let row = quote!(#krate::__private::retrieve::Step::of(#field));
      if step.awaited {
        quote!(#row.awaited())
      } else {
        row
      }
    });
    quote! {
      impl #krate::__private::retrieve::DeclaredTower for #name {
        type StepOptions = #step_options;
        type SearchOptions = #search_options;
        const ALL_SYNC: bool = #all_sync;
        const STEPS: &'static [#krate::__private::retrieve::Step] = &[
          #(#rows),*
        ];
      }
    }
  }

  /// **THE REQUEST'S OWN OPTIONS** — one row per WORD this declaration wrote, and one that no word
  /// has to write.
  ///
  /// ```ignore
  /// pub struct ClipTextSearchOptions {
  ///   budget:        Option<SearchBudget>,  // ALWAYS — the framework's universal minimum
  ///   arm_weight:    Option<f64>,           // where `expand = "…"` opened a widening
  ///   lane_emphasis: Option<f64>,           // where `route(router = script_weighted_fan, …)` did
  /// }
  /// ```
  ///
  /// # It is TOKEN-KEYED, and that is what makes it mintable at all
  ///
  /// The 2026-08-27 census measured why a request object could not be minted at the RECIPE grain:
  /// what crosses the expansion wall is `DeclaredTower` — the two options types, `ALL_SYNC` and the
  /// roster — and a `Step` carries a field name and an `async` flag, so nothing a recipe can read
  /// says whether the tower it bound widens or crosses. The words are HERE. So the object is minted
  /// here, and the recipe publishes it by projection without ever knowing what is in it.
  ///
  /// # The BUDGET row is unconditional, and it is the keystone's universality read forwards
  ///
  /// A walk budget means the same thing for every tower ever declared, because it is about the
  /// deployment's TIME rather than about the search — so it is not keyed by a word and no word can
  /// take it away. It is also what keeps the wire face SPELLABLE: a GraphQL input object may not
  /// define zero fields, so a tower whose grammar wrote nothing would otherwise have no face to
  /// publish and the recipe's `options` argument would have no type to be.
  ///
  /// # NO STEP ROWS, ever
  ///
  /// A step's `Serve::Options` is the application's own type and whether it is `()` is a fact only
  /// the compiler holds, so a per-step row cannot be published by a macro that cannot know which
  /// rows are empty. That is `<Tower>StepOptions`' whole job and it stays on the install clock.
  fn search_options(&self) -> proc_macro2::TokenStream {
    let krate = &self.krate;
    let vis = &self.vis;
    let name = self.search_options_name();
    let sdl = name.to_string();
    let at = self.name.span();
    let budget = respan(quote!(#krate::__private::retrieve::SearchBudget), at);
    let mut rows: Vec<SearchRow> = vec![SearchRow {
      member: quote::format_ident!("budget", span = at),
      wire: "budget",
      ty: budget,
      noun: "walk budget",
      why: "How long this request will wait for the whole walk. The deployment's own wall CAPS it: \
            a request asking for less waits less, and one asking for more waits the deployment's \
            number.",
    }];
    if let Some(at_expand) = self.expand_at() {
      let at_field = self.steps[at_expand].field.span();
      rows.push(SearchRow {
        member: quote::format_ident!("arm_weight", span = at_field),
        wire: "armWeight",
        ty: quote_spanned!(at_field=> ::core::primitive::f64),
        noun: "arm weight",
        why: "What an arm the expander minted counts for, against the 1.0 of what was actually \
              asked. A PREFERENCE, so a request that names it wins outright over the deployment's.",
      });
    }
    if let Some((_, step)) = self.weighted_crossing() {
      let at_field = step.field.span();
      rows.push(SearchRow {
        member: quote::format_ident!("lane_emphasis", span = at_field),
        wire: "laneEmphasis",
        ty: quote_spanned!(at_field=> ::core::primitive::f64),
        noun: "lane emphasis",
        why: "What a lane this question is written in counts for, against the 1.0 of every other \
              lane. A PREFERENCE, and 1.0 asks every lane flat.",
      });
    }
    let fields = rows.iter().map(
      |SearchRow {
         member,
         ty,
         noun,
         why,
         ..
       }| {
        let doc = crate::emit::leading(&format!(
          "The {noun}, where this request names one.\n\n{why}\n\nAbsent means THIS REQUEST NAMED \
           NOTHING, under which the deployment's own value stands.",
        ));
        quote!(#[doc = #doc] #member: ::core::option::Option<#ty>)
      },
    );
    let nothing = rows
      .iter()
      .map(|SearchRow { member, .. }| quote!(#member: ::core::option::Option::None,));
    let knobs = rows.iter().map(
      |SearchRow {
         member, ty, noun, ..
       }| {
        let with = quote::format_ident!("with_{member}", span = member.span());
        let set = quote::format_ident!("set_{member}", span = member.span());
        let named = crate::emit::leading(&format!("The same request, naming the {noun}."));
        let narrowed = crate::emit::leading(&format!(
          "The {noun}, named IN PLACE — including named back to nothing.",
        ));
        let read = crate::emit::leading(&format!(
          "The {noun}, or [`None`] where this request named nothing.",
        ));
        quote! {
          #[doc = #named]
          #[inline]
          #[must_use]
          #vis fn #with(mut self, #member: #ty) -> Self {
            self.#member = ::core::option::Option::Some(#member);
            self
          }

          #[doc = #narrowed]
          #[inline]
          #vis fn #set(&mut self, #member: ::core::option::Option<#ty>) -> &mut Self {
            self.#member = #member;
            self
          }

          #[doc = #read]
          #[inline]
          #[must_use]
          #vis fn #member(&self) -> ::core::option::Option<&#ty> {
            ::core::option::Option::as_ref(&self.#member)
          }
        }
      },
    );
    let doc = crate::emit::leading(&format!(
      "What ONE REQUEST names for [`{name}`] — the tier-three package, keyed by the words this \
       declaration wrote.\n\nEvery field starts at nothing, and nothing is a DEFERRAL rather than a \
       gap: a row this names nothing for leaves the deployment's own value standing. A PREFERENCE \
       row that IS named wins outright; the budget is PROTECTIVE and may only tighten.",
      name = self.name,
    ));
    let fresh = crate::emit::leading(
      "A request that names NOTHING — every tier-three row deferred to the \
                           deployment's.",
    );
    let defaulted = crate::emit::leading(&format!(
      "The unnamed request — [`{name}::new`], and one source of truth for it.",
      name = name,
    ));
    let face = self.search_options_face(&name, &sdl, &rows);
    quote! {
      #[doc = #doc]
      #[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq)]
      #vis struct #name {
        #(#fields,)*
      }

      impl #name {
        #[doc = #fresh]
        #[inline]
        #[must_use]
        #vis const fn new() -> Self {
          Self {
            #(#nothing)*
          }
        }

        #(#knobs)*
      }

      #[doc = #defaulted]
      impl ::core::default::Default for #name {
        #[inline]
        fn default() -> Self {
          Self::new()
        }
      }

      #face
    }
  }

  /// **THE REQUEST PACKAGE'S WIRE FACE** — an ordinary input object, every field nullable and
  /// therefore wholly omissible.
  ///
  /// HAND-WRITTEN rather than derived, and it rides `if_async_graphql!`, which is the emitted
  /// packages' own measured shape one emitter over. A derive belongs to the type's own DECLARATION,
  /// which is written outside the binding gate — so a `#[derive(InputObject)]` here would demand
  /// async-graphql of every tower ever declared, and a tower walked from Rust alone owes a schema
  /// nothing.
  ///
  /// The gate asks `ingraph`'s OWN feature rather than the declaring crate's, which is why it is a
  /// macro and not a `#[cfg]`: a `#[cfg(feature = "async-graphql")]` written inside an expansion asks
  /// a different manifest.
  fn search_options_face(
    &self,
    name: &syn::Ident,
    sdl: &str,
    rows: &[SearchRow],
  ) -> proc_macro2::TokenStream {
    let krate = &self.krate;
    let gate = quote!(#krate::__private::gate::if_async_graphql);
    let ag = quote!(#krate::__private::async_graphql);
    let entries = rows.iter().map(|SearchRow { wire, ty, why, .. }| {
      let description = *why;
      quote! {
        __ingraph_fields.insert(
          ::std::string::String::from(#wire),
          #ag::registry::MetaInputValue {
            name: ::std::string::String::from(#wire),
            description: ::core::option::Option::Some(::std::string::String::from(#description)),
            ty: <::core::option::Option<#ty> as #ag::InputType>::create_type_info(
              __ingraph_registry,
            ),
            deprecation: #ag::registry::Deprecation::NoDeprecated,
            default_value: ::core::option::Option::None,
            visible: ::core::option::Option::None,
            inaccessible: false,
            tags: ::std::vec::Vec::new(),
            is_secret: false,
            directive_invocations: ::std::vec::Vec::new(),
          },
        );
      }
    });
    let reads = rows.iter().map(
      |SearchRow {
         member, wire, ty, ..
       }| {
        quote! {
          // `.cloned()` in METHOD position, and it has to be: `Option::cloned` is `E0034` as a path,
          // there being one on `Option<&T>` and one on `Option<&mut T>` with nothing at the call site
          // to pick between them.
          #member: <::core::option::Option<#ty> as #ag::InputType>::parse(
            #ag::indexmap::IndexMap::get(&__ingraph_object, #wire).cloned(),
          )
          .map_err(#ag::InputValueError::propagate)?
        }
      },
    );
    let writes = rows.iter().map(|SearchRow { member, wire, .. }| {
      quote! {
        __ingraph_map.insert(
          #ag::Name::new(#wire),
          #ag::InputType::to_value(&self.#member),
        );
      }
    });
    let description = format!(
      "What one request names for `{name}` — every row absent by default, and an absent row leaves \
       the deployment's own value standing.",
      name = self.name,
    );
    quote! {
      #gate! {
        const _: () = {
          #[automatically_derived]
          impl #ag::InputType for #name {
            type RawValueType = Self;

            #[inline]
            fn type_name() -> ::std::borrow::Cow<'static, ::core::primitive::str> {
              ::std::borrow::Cow::Borrowed(#sdl)
            }

            fn create_type_info(
              __ingraph_registry: &mut #ag::registry::Registry,
            ) -> ::std::string::String {
              __ingraph_registry.create_input_type::<Self, _>(
                #ag::registry::MetaTypeId::InputObject,
                |__ingraph_registry| #ag::registry::MetaType::InputObject {
                  name: ::std::string::String::from(#sdl),
                  description: ::core::option::Option::Some(
                    ::std::string::String::from(#description),
                  ),
                  input_fields: {
                    let mut __ingraph_fields = #ag::indexmap::IndexMap::new();
                    #(#entries)*
                    __ingraph_fields
                  },
                  visible: ::core::option::Option::None,
                  inaccessible: false,
                  tags: ::std::vec::Vec::new(),
                  rust_typename: ::core::option::Option::Some(::core::any::type_name::<Self>()),
                  oneof: false,
                  directive_invocations: ::std::vec::Vec::new(),
                },
              )
            }

            fn parse(
              __ingraph_value: ::core::option::Option<#ag::Value>,
            ) -> #ag::InputValueResult<Self> {
              if let ::core::option::Option::Some(#ag::Value::Object(__ingraph_object)) =
                __ingraph_value
              {
                return ::core::result::Result::Ok(Self { #(#reads,)* });
              }
              ::core::result::Result::Err(#ag::InputValueError::expected_type(
                ::core::option::Option::unwrap_or_default(__ingraph_value),
              ))
            }

            fn to_value(&self) -> #ag::Value {
              let mut __ingraph_map = #ag::indexmap::IndexMap::new();
              #(#writes)*
              #ag::Value::Object(__ingraph_map)
            }

            #[inline]
            fn as_raw_value(&self) -> ::core::option::Option<&Self::RawValueType> {
              ::core::option::Option::Some(self)
            }
          }

          #[automatically_derived]
          impl #ag::InputObjectType for #name {}
        };
      }
    }
  }

  /// **THE ASSEMBLY ROW** — the boot gate over a deployment's filled seats, and the uniform run a
  /// resolver calls.
  ///
  /// # It RESTATES the chain in its own `where` clause, where the record deliberately does not
  ///
  /// [`declared`](Self::declared) carries none, so a broken tower earns exactly one *is not a search
  /// tower* beside the hops the connectivity already reported. This impl carries the chain instead,
  /// and the difference is what each impl's SIGNATURE names: a record states three seats and can be
  /// written unconditionally, where every row here is spelled in the tower's own two ends — so an
  /// unconditional one would ask rustc to normalise `<Self as SearchTower>::Question` for a tower
  /// whose `SearchTower` impl does not apply, and report the same broken hops a second time under a
  /// second heading. The clause is ASSUMED at an impl and PROVEN at a call, so a good tower pays
  /// nothing for it and a broken one is refused once, where the fault is.
  ///
  /// # The RUN is awaited whatever the walk's face is
  ///
  /// Its caller is a resolver and a resolver is already async, so a blocking tower's `run` wraps its
  /// blocking walk here rather than making every caller branch on
  /// `DeclaredTower::ALL_SYNC` — the one-call-seat division the expand seam already makes over its
  /// own blocking half. `ALL_SYNC` still answers the HAND-CALL road, where a caller spelling `walk`
  /// itself needs to know.
  fn assembly(&self) -> proc_macro2::TokenStream {
    let krate = &self.krate;
    let name = &self.name;
    let question = self.asked();
    let answer = self.derived();
    let refusal = self.error_name();
    let options = self.step_options_name();
    let mut hops = self.canonical_demands();
    hops.extend(self.hops());
    let awaited = self.awaited().then(|| quote!(.await));
    let gate = self.gate();
    let borrowed = self.steps.iter().map(|step| {
      let field = &step.field;
      quote!(&mut __ingraph_steps__.#field,)
    });
    let asked = self.search_options_name();
    let retuned = self.retuned();
    let composed = self.composed();
    quote! {
      impl #krate::__private::retrieve::AssembledTower for #name
      where
        #(#hops,)*
      {
        type Refusal = #refusal;

        #gate

        #[inline]
        fn asked_budget(
          __ingraph_asked__: ::core::option::Option<&#asked>,
        ) -> ::core::option::Option<#krate::__private::jiff::SignedDuration> {
          // THE ONE ROW READ FROM OUTSIDE THE WALK, because the wall is built round the whole run
          // and cannot be raised from inside it. The COMPOSITION is still `tightened_budget`'s, at
          // `walk_within`; this is the projection that gets the number there.
          ::core::option::Option::and_then(
            ::core::option::Option::and_then(__ingraph_asked__, #asked::budget),
            #krate::__private::retrieve::SearchBudget::walk,
          )
        }

        async fn run(
          __ingraph_steps__: &mut #name,
          question: #question,
          options: ::core::option::Option<&#options>,
          asked: ::core::option::Option<#asked>,
        ) -> ::core::result::Result<#answer, #refusal> {
          #retuned
          #composed
          #name::walk(question, #(#borrowed)* options)#awaited
        }
      }
    }
  }

  /// ④ **THE REQUEST'S OWN ROUTER, RETUNED** — the lane emphasis laid on the value THIS READ minted,
  /// or nothing at all where no word could carry one.
  ///
  /// # The MINT is what makes per-request configuration free
  ///
  /// `TowerDoor` builds one exclusive set of steps per read, so the `LaneFan` this run is about to
  /// route through is this request's own value and nobody else's. Retuning it is therefore a local
  /// write rather than a shared mutation — no lock, no clone of the roster, and nothing held across
  /// an `await`.
  ///
  /// # `LaneRouter` DID NOT MOVE, and that is the road's whole point
  ///
  /// A per-query emphasis could have been a parameter on the routing trait — a surface end users
  /// extend — which would have spent every third-party router's signature for a knob only the shipped
  /// routers have. `ScriptWeightedFan::with_emphasis` is the seam instead, and it was already there.
  ///
  /// # NOTHING IS EMITTED for a router this framework did not ship
  ///
  /// [`weighted_crossing`](Self::weighted_crossing) answers [`None`] for a quoted path, so the row is
  /// never minted and this writes nothing. A published knob the emission could not spend would be
  /// worse than the silence.
  fn retuned(&self) -> Option<proc_macro2::TokenStream> {
    let krate = &self.krate;
    let (at, step) = self.weighted_crossing()?;
    let at_field = step.field.span();
    let field = &step.field;
    let asked = self.search_options_name();
    let takes = self.takes(at);
    let fan = respan(quote!(#krate::__private::route::LaneFan), at_field);
    let router = respan(
      quote!(#krate::__private::route::ScriptWeightedFan<#takes>),
      at_field,
    );
    Some(quote_spanned! {at_field=>
      // TWO STATEMENTS AND NOT ONE, because the mounted router is read through a BORROW of the very
      // field the write lands on. The retuned value is built first and the fan is written second.
      let __ingraph_retuned__: ::core::option::Option<#router> = match (
        ::core::option::Option::and_then(
          ::core::option::Option::as_ref(&asked),
          #asked::lane_emphasis,
        ),
        #fan::router(&__ingraph_steps__.#field),
      ) {
        (
          ::core::option::Option::Some(__ingraph_emphasis__),
          ::core::option::Option::Some(__ingraph_router__),
        ) => ::core::option::Option::Some(<#router>::with_emphasis(
          // THE ROSTER IS THE MOUNTED ROUTER'S OWN, carried across unchanged: what a request may
          // name is the EMPHASIS, and a rebuilt router that took its lanes from anywhere else would
          // be a different router wearing this one's number.
          <#router>::new(<#router>::lanes(__ingraph_router__)),
          *__ingraph_emphasis__,
        )),
        _ => ::core::option::Option::None,
      };
      if let ::core::option::Option::Some(__ingraph_router__) = __ingraph_retuned__ {
        #fan::set_router(
          &mut __ingraph_steps__.#field,
          ::core::option::Option::Some(__ingraph_router__),
        );
      }
    })
  }

  /// ② **THE REQUEST'S ARM WEIGHT, LAID OVER THE DEPLOYMENT'S** — `ArmWeights::over`, spent once, and
  /// the composed package handed to the walk in the deployment's place.
  ///
  /// # The WALK does not learn that a request exists
  ///
  /// A widening step's `Serve::Options` IS `ArmWeights`, so the fan walk already reads the tier it is
  /// handed at the one place the coefficient is computed. Composing HERE — into a step-keyed package
  /// the walk takes exactly as it always did — is what keeps the walk's arity, its parameters and its
  /// hand-call road untouched by tier three.
  ///
  /// # A request that named NOTHING costs nothing
  ///
  /// The clone happens only inside the `Some` arm, so a read whose request named no weight hands the
  /// walk the very borrow the door lent it — absence is identity, at this seat as at the budget's.
  fn composed(&self) -> Option<proc_macro2::TokenStream> {
    let krate = &self.krate;
    let at = self.expand_at()?;
    let step = &self.steps[at];
    let at_field = step.field.span();
    let field = &step.field;
    let with = {
      use syn::ext::IdentExt as _;
      quote::format_ident!("with_{}", step.field.unraw(), span = at_field)
    };
    let asked = self.search_options_name();
    let options = self.step_options_name();
    let weights = respan(quote!(#krate::__private::retrieve::ArmWeights), at_field);
    Some(quote_spanned! {at_field=>
      let __ingraph_composed__: ::core::option::Option<#options> = ::core::option::Option::map(
        ::core::option::Option::and_then(
          ::core::option::Option::as_ref(&asked),
          #asked::arm_weight,
        ),
        |__ingraph_weight__| {
          // TIER THREE OVER TIER TWO, through the one function that spells the preference law.
          // Neither side is defaulted on the way: `DEFAULT` is the SHIPPED weights and not a filled
          // number, so a deployment that named nothing still loses to a request that did and beats
          // one that did not.
          let __ingraph_over__ = #weights::over(
            &#weights::with_paraphrase(#weights::new(), *__ingraph_weight__),
            ::core::option::Option::unwrap_or(
              ::core::option::Option::and_then(options, |__ingraph_options__| {
                ::core::option::Option::as_ref(&__ingraph_options__.#field)
              }),
              &#weights::DEFAULT,
            ),
          );
          #options::#with(
            match options {
              ::core::option::Option::Some(__ingraph_options__) => {
                ::core::clone::Clone::clone(__ingraph_options__)
              }
              ::core::option::Option::None => #options::new(),
            },
            __ingraph_over__,
          )
        },
      );
      let options = match &__ingraph_composed__ {
        ::core::option::Option::Some(__ingraph_options__) => {
          ::core::option::Option::Some(__ingraph_options__)
        }
        ::core::option::Option::None => options,
      };
    })
  }

  /// **THE CANONICAL LINES THE CHAIN IS SPELLED THROUGH**, stated as predicates — one per step whose
  /// end this declaration OMITTED.
  ///
  /// A `where` clause is ASSUMED at an impl and its own well-formedness is checked in its own
  /// environment, so a predicate naming `<Ty as DefaultServe>::Answer` is only well formed where
  /// `Ty: DefaultServe` is in that environment. The connectivity does not need these because its
  /// refusal IS the missing line — a step with no canonical road is what that impl is there to
  /// report. The assembly row restates the chain precisely so that it reports NOTHING, so it states
  /// these too and a tower with no canonical line earns its refusal once, at the impl that is about
  /// it.
  ///
  /// It narrows nothing a caller did not already owe: a step that omitted its answer word has its
  /// canonical line demanded by the connectivity's own predicates, so this is that same demand
  /// written where the compiler can see it. A step whose ends were both WRITTEN appears nowhere
  /// here.
  fn canonical_demands(&self) -> Vec<proc_macro2::TokenStream> {
    let krate = &self.krate;
    let mut demanded: Vec<proc_macro2::TokenStream> = Vec::new();
    let mut spell = |step: &StepModel| {
      let at_field = step.field.span();
      let ty = &step.ty;
      let line = respan(quote!(#krate::__private::drive::DefaultServe), at_field);
      demanded.push(quote_spanned!(at_field=> #ty: #line));
    };
    // THE HEAD, where the tower wrote no `question` word: what it is asked is the first step's own
    // canonical question.
    if self.question.is_none()
      && let Some(head) = self.steps.first()
    {
      spell(head);
    }
    // EVERY STEP whose `answer` word was omitted. An ⟂ step has none by law and spells no canonical
    // line — the chain's type does not move across it — so it is not here.
    for step in &self.steps {
      if step.answer.is_none() && step.annotation.is_none() {
        spell(step);
      }
    }
    demanded
  }

  /// **THE GATE** — one reading per declared fan word, or NOTHING AT ALL for a tower that wrote
  /// none.
  ///
  /// [`None`] is the absence-identity, at the assembly: a tower with no fan word inherits
  /// `AssembledTower::check`'s own default, which reads no field and refuses nothing, so a
  /// deployment assembling an unfanned tower meets not one token of this machinery.
  ///
  /// Each reading ASCRIBES the seat before it reads it, which is the walk's own pin at the walk's
  /// own price: a field carrying anything but the segment's seat is `E0308` naming both types, at
  /// the field. So the gate and the walk agree about what a fan step's field holds by construction
  /// rather than by two matching guesses.
  ///
  /// A CROSSING carries [`LaneFan::check`]'s refusal whole rather than restating it: the roster and
  /// both escapes are that seat's own sentence, and a gap that re-worded them would be a second
  /// spelling of one vocabulary.
  ///
  /// [`LaneFan::check`]: https://docs.rs/ingraph
  fn gate(&self) -> Option<proc_macro2::TokenStream> {
    if !self.fanned() {
      return None;
    }
    let krate = &self.krate;
    let name = &self.name;
    let tower = name.to_string();
    let readings = self.fans().map(|(at, step, fan)| {
      let at_field = step.field.span();
      let field = &step.field;
      let takes = self.takes(at);
      let seat = quote_spanned!(at_field=> &__ingraph_steps__.#field);
      let unfilled = respan(quote!(#krate::__private::retrieve::UnfilledSeat), at_field);
      let named = step.field.to_string();
      match fan {
        Fan::Expand { expander } => {
          let road = respan(quote!(#krate::__private::retrieve::Expansion), at_field);
          let declared = spelled(&quote!(#expander));
          quote_spanned! {at_field=>
            let __ingraph_road__: &#road<#takes> = #seat;
            if !#road::is_mounted(__ingraph_road__) {
              ::std::vec::Vec::push(
                &mut __ingraph_unfilled__,
                #unfilled::widening(#named, #declared),
              );
            }
          }
        }
        Fan::Route { router, .. } => {
          let router = router.spelled(krate, &takes);
          let fan = respan(quote!(#krate::__private::route::LaneFan), at_field);
          quote_spanned! {at_field=>
            let __ingraph_fan__: &#fan<#router> = #seat;
            if let ::core::result::Result::Err(__ingraph_missing__) = #fan::check(__ingraph_fan__) {
              ::std::vec::Vec::push(
                &mut __ingraph_unfilled__,
                #unfilled::crossing(#named, __ingraph_missing__),
              );
            }
          }
        }
      }
    });
    Some(quote! {
      fn check(
        __ingraph_steps__: &#name,
      ) -> ::core::result::Result<(), #krate::__private::retrieve::SeatsUnfilled> {
        let mut __ingraph_unfilled__ = ::std::vec::Vec::new();
        #(#readings)*
        #krate::__private::retrieve::SeatsUnfilled::checked(#tower, __ingraph_unfilled__)
      }
    })
  }

  /// What ONE STEP refuses with — the projection `<Ty as Serves<Q, A>>::Error`, at the face the
  /// step's own word chose.
  ///
  /// A PROJECTION and never an erasure, which is the whole difference this sum makes: nothing here
  /// demands that a step's error be boxable, or `Send`, or `'static`, so a step keeps the error type
  /// it declared and a caller that matched an arm holds THAT type rather than a `dyn` behind a name.
  fn refused_with(&self, at: usize, step: &StepModel) -> proc_macro2::TokenStream {
    let at_field = step.field.span();
    let ty = &step.ty;
    let takes = self.takes(at);
    let answers = self.flows(at);
    // **A CROSSING REFUSES THE FAN'S OWN SUM**, carried whole. `FanError` already names the three
    // causes a routed question has — nothing mounted, a lane this corpus does not hold, and the
    // router's own refusal — so an arm that flattened them would be re-stating a vocabulary the
    // seat publishes, and a caller that matched this arm would have lost which of them happened.
    if let Some(Fan::Route { router, .. }) = &step.fan {
      let krate = &self.krate;
      let router = router.spelled(krate, &takes);
      let seam = respan(quote!(#krate::__private::route::LaneRouter), at_field);
      let sum = respan(quote!(#krate::__private::route::FanError), at_field);
      return quote_spanned!(at_field=> #sum<<#router as #seam>::Error>);
    }
    let face = respan(self.face(step), at_field);
    quote_spanned!(at_field=> <#ty as #face<#takes, #answers>>::Error)
  }

  /// **THE STEPS THAT CAN REFUSE** — every step but a widening.
  ///
  /// A widening CANNOT fail, and that is the expand seam's contract rather than an oversight of this
  /// emission: an expander answers a list that may be empty, trouble is digested inside it, and a
  /// search that died because its optional widening did would be a worse answer than the unwidened
  /// one. So there is no arm for it — an arm nothing can ever construct is a variant a reader has to
  /// rule out by hand.
  fn refusing(&self) -> impl Iterator<Item = (usize, &StepModel)> {
    self
      .steps
      .iter()
      .enumerate()
      .filter(|(_, step)| !matches!(step.fan, Some(Fan::Expand { .. })))
  }

  /// THE REFUSAL SUM — one arm per step, named by the step, carrying that step's own error.
  ///
  /// See the module note for why a sum rather than an erasure, and [`rendering`](Self::rendering)
  /// for the three faces beneath it.
  fn refusal(&self) -> proc_macro2::TokenStream {
    let vis = &self.vis;
    let name = self.error_name();
    let arms = self.refusing().map(|(at, step)| {
      let variant = Self::variant(step);
      let refused_with = self.refused_with(at, step);
      let doc = crate::emit::leading(&format!(
        "The `{field}` step refused, and this is what it refused with.",
        field = step.field,
      ));
      quote! {
        #[doc = #doc]
        #variant(#refused_with)
      }
    });
    let doc = crate::emit::leading(&format!(
      "How [`{name}`]'s walk refuses — ONE ARM PER STEP, carrying that step's own error.\n\nA \
       chain of N hops has N error types and one `Result` has one, so the walk answers this sum: \
       the arm NAMES the step that refused, and its payload is the very type that step's `Serves` \
       impl declared. Nothing is boxed and nothing is erased, so a caller that matched an arm holds \
       the error it was going to inspect anyway.",
      name = self.name,
    ));
    quote! {
      #[doc = #doc]
      #vis enum #name {
        #(#arms),*
      }
    }
  }

  /// The refusal sum's own faces: what it prints, what it debugs as, and where the cause is
  /// reached.
  ///
  /// # `Display` NAMES THE STEP; `Debug` CARRIES WHAT IT REFUSED WITH
  ///
  /// `Display` is a sentence and takes only the arm's name. `Debug` prints the arm AND its payload,
  /// which is the shape a derived one has and the shape a caller unwrapping a walk expects — a
  /// `.unwrap()` that printed `Tokenize` and nothing else would name the hop and hide the reason.
  ///
  /// **The payload costs no bound**, and that is measured rather than assumed:
  /// [`source`](core::error::Error::source) already coerces every arm's payload to `&dyn Error`, and
  /// [`Error`](core::error::Error) has [`Debug`](core::fmt::Debug) as a supertrait — so every step's
  /// error is `Debug` before this impl asks. What it does cost is a REPORT: naming a step's error
  /// once more is one more place a broken chain is re-derived, so the goldens carry one extra
  /// `E0277` per broken hop. The cause is worth the line.
  ///
  /// The cause travels under [`source`](core::error::Error::source) — the ONE place a step's error
  /// is required to BE an error, and it lands at that step's own field.
  fn rendering(&self) -> proc_macro2::TokenStream {
    let name = self.error_name();
    // An arm-less sum is matched through the PLACE rather than through arms — there is no value of
    // it, so there is no arm to write. The model is never built empty; this is the shape of that
    // fact rather than a case.
    let (displayed, debugged, sourced) = if self.refusing().next().is_none() {
      (
        quote!(match *self {}),
        quote!(match *self {}),
        quote!(match *self {}),
      )
    } else {
      let displayed = self.refusing().map(|(_, step)| {
        let variant = Self::variant(step);
        let said = format!(
          "the step `{field}` refused the question",
          field = step.field
        );
        quote!(Self::#variant(_) => ::core::fmt::Formatter::write_str(__ingraph_f, #said))
      });
      let debugged = self.refusing().map(|(_, step)| {
        let at_field = step.field.span();
        let variant = Self::variant(step);
        let printed = variant.to_string();
        // SPANNED AT THE STEP, for the reason `source`'s arm is: this is where the payload's own
        // `Debug` is spent, and a step whose error cannot be printed should be told so at the field
        // that holds it. The demand is already paid — `Error: Debug` — so what the span moves is
        // only where a BROKEN CHAIN's re-derivation is reported.
        quote_spanned! {at_field=>
          Self::#variant(__ingraph_refused__) => ::core::fmt::DebugTuple::finish(
            ::core::fmt::DebugTuple::field(
              &mut ::core::fmt::Formatter::debug_tuple(__ingraph_f, #printed),
              __ingraph_refused__,
            ),
          )
        }
      });
      let sourced = self.refusing().map(|(_, step)| {
        let at_field = step.field.span();
        let variant = Self::variant(step);
        // SPANNED AT THE STEP, because this coercion is where a step's error is required to BE an
        // error: a walk whose refusal could not be asked for its cause would be publishing a
        // refusal nobody can inspect. The three impl HEADERS around it keep the emitter's own span
        // and are reported at the attribute, which is what an unspanned arm would earn too.
        quote_spanned! {at_field=>
          Self::#variant(__ingraph_refused__) =>
            ::core::option::Option::Some(__ingraph_refused__)
        }
      });
      (
        quote!(match self { #(#displayed,)* }),
        quote!(match self { #(#debugged,)* }),
        quote!(match self { #(#sourced,)* }),
      )
    };
    quote! {
      impl ::core::fmt::Display for #name {
        fn fmt(&self, __ingraph_f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
          #displayed
        }
      }

      impl ::core::fmt::Debug for #name {
        fn fmt(&self, __ingraph_f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
          #debugged
        }
      }

      impl ::core::error::Error for #name {
        fn source(&self) -> ::core::option::Option<&(dyn ::core::error::Error + 'static)> {
          #sourced
        }
      }
    }
  }

  /// THE WALK — the question, the steps, the tail seat, and one hop per step.
  fn walk(&self) -> proc_macro2::TokenStream {
    let name = &self.name;
    let vis = &self.vis;
    let question = self.asked();
    let answer = self.derived();
    let refusal = self.error_name();
    let awaited = self.awaited().then(|| quote!(async));

    let parameters = self.steps.iter().enumerate().map(|(at, step)| {
      let held = held(at, step.field.span());
      let ty = &step.ty;
      quote!(#held: &mut #ty,)
    });
    let body = if self.fanned() {
      self.fanned_body(&refusal)
    } else {
      let hops = self
        .steps
        .iter()
        .enumerate()
        .map(|(at, step)| self.hop(at, step, &refusal, false));
      quote! {
        #(#hops)*
        ::core::result::Result::Ok(__ingraph_answered__)
      }
    };
    let doc = crate::emit::leading(&self.doc());
    let options = self.step_options_name();

    quote! {
      impl #name {
        #[doc = #doc]
        #[allow(clippy::too_many_arguments)]
        #vis #awaited fn walk(
          question: #question,
          #(#parameters)*
          options: ::core::option::Option<&#options>,
        ) -> ::core::result::Result<#answer, #refusal> {
          #body
        }
      }
    }
  }

  /// **THE FAN WALK** — the pre-fan chain once, the family, the lanes, the tail per cell, and the
  /// fold that closes every segment before the mouth.
  ///
  /// ```text
  /// [ steps before the fan ]          once
  ///   ② the widening                  once  — the family, the original pinned first
  ///   for each ARM:
  ///     [ steps between ② and ④ ]     per arm
  ///       ④ the crossing              per arm — one dispatch per lane
  ///       for each LANE:
  ///         [ the tail ]              per (arm × lane)
  ///         one grid cell             arm × lane, MULTIPLIED
  /// the fold                          once  — ONE value out, and the contract stays 1 → 1
  /// ```
  ///
  /// # Either segment may be absent, and neither absence is a second shape
  ///
  /// A tower that only widens has one lane — [`LaneIdent::UND`], which is what a slot that declared
  /// no lanes holds — and a tower that only crosses has one arm, the original's. Both are spelled at
  /// the cell rather than branched on here, so the two degenerate fans walk the nesting the full one
  /// walks.
  ///
  /// # EVERY STEP INSIDE A LOOP IS REBORROWED, and every step outside one is not
  ///
  /// A step is held as `&mut`, and a `&mut` handed to a call inside a loop is moved out of on the
  /// first turn. So the hops the fan puts under a loop are emitted as `&mut *step` — and the hops
  /// before the fan are emitted exactly as they always were, which is what keeps an UNFANNED tower's
  /// expansion the one it had before the amendment, token for token.
  ///
  /// [`LaneIdent::UND`]: https://docs.rs/ingraph
  fn fanned_body(&self, refusal: &syn::Ident) -> proc_macro2::TokenStream {
    let krate = &self.krate;
    let expand_at = self.expand_at();
    let route_at = self.route_at();
    // The model is only fanned if one of the two is present, so the fallback is a shape rather than
    // a case.
    let Some(opens_at) = expand_at.or(route_at) else {
      return quote!(::core::result::Result::Ok(__ingraph_answered__));
    };
    let ends_at = route_at.unwrap_or(self.steps.len());

    let lead = (0..opens_at).map(|at| self.hop(at, &self.steps[at], refusal, false));
    let per_arm = expand_at
      .map(|at| at + 1..ends_at)
      .unwrap_or(0..0)
      .map(|at| self.hop(at, &self.steps[at], refusal, true));
    let per_cell = route_at
      .map(|at| at + 1..self.steps.len())
      .unwrap_or(0..0)
      .map(|at| self.hop(at, &self.steps[at], refusal, true));

    let widening = expand_at.map(|at| self.widening(at, &self.steps[at]));
    let crossing = route_at.map(|at| self.crossing(at, &self.steps[at], refusal));
    let cell = self.cell(expand_at.is_some(), route_at.is_some());
    let fold = self.fold();

    let arm_taken = expand_at.map(|at| {
      let at_field = self.steps[at].field.span();
      let arms = Self::named(&self.steps[at], at_field);
      quote_spanned! {at_field=>
        let (__ingraph_answered__, __ingraph_origin__) =
          #krate::__private::retrieve::Expanded::into_components(__ingraph_widened__);
        let __ingraph_arm_weight__ = #krate::__private::retrieve::ArmWeights::weight(
          ::core::option::Option::unwrap_or(
            #arms,
            &#krate::__private::retrieve::ArmWeights::DEFAULT,
          ),
          &__ingraph_origin__,
        );
      }
    });
    let lane_taken = route_at.map(|at| {
      let at_field = self.steps[at].field.span();
      let answers = self.answered(&self.steps[at]);
      let probe = respan(quote!(#krate::__private::route::RoutedProbe), at_field);
      quote_spanned! {at_field=>
        let __ingraph_lane__ = #probe::lane(&__ingraph_probe__);
        let __ingraph_lane_weight__ = #probe::weight(&__ingraph_probe__);
        let __ingraph_answered__: #answers = __ingraph_probe__;
      }
    });

    // THE NESTING IS BUILT FROM THE INSIDE OUT, one loop at a time, because a `quote!` holds
    // BALANCED tokens: a loop cannot be opened in one fragment and closed in another. Each wrap adds
    // the run of hops that belongs to ITS depth, which is what keeps the steps between ② and ④
    // inside the arm loop and outside the lane one.
    let mut nested = quote! {
      #lane_taken
      #(#per_cell)*
      #cell
    };
    if route_at.is_some() {
      nested = quote! {
        for __ingraph_probe__ in ::core::iter::IntoIterator::into_iter(__ingraph_probes__) {
          #nested
        }
      };
    }
    nested = quote! {
      #(#per_arm)*
      #crossing
      #nested
    };
    if expand_at.is_some() {
      nested = quote! {
        for (__ingraph_arm__, __ingraph_widened__) in ::core::iter::Iterator::enumerate(
          ::core::iter::IntoIterator::into_iter(__ingraph_family__),
        ) {
          #arm_taken
          #nested
        }
      };
    }

    quote! {
      #(#lead)*
      #widening
      let mut __ingraph_grid__ = ::std::vec::Vec::new();
      #nested
      #fold
    }
  }

  /// ② **THE WIDENING** — the family, with the caller's own question at its head.
  ///
  /// The seat is ASCRIBED before it is spent, which is the whole of what pins a widening step's
  /// field to the seat it must hold: a field carrying anything else is `E0308` naming both types, at
  /// the field. The awaited call is [`Expansion::expand`]'s own, and the family's element type is
  /// ascribed too — a widening is an endomorphism, so a step whose `answer = "…"` named some other
  /// type is caught here rather than accepted and dropped.
  ///
  /// [`Expansion::expand`]: https://docs.rs/ingraph
  fn widening(&self, at: usize, step: &StepModel) -> proc_macro2::TokenStream {
    let krate = &self.krate;
    let at_field = step.field.span();
    let held = held(at, at_field);
    let takes = self.takes(at);
    let answers = self.answered(step);
    let taken = if at == 0 {
      quote_spanned!(at_field=> question)
    } else {
      quote_spanned!(at_field=> __ingraph_answered__)
    };
    let seat = respan(quote!(#krate::__private::retrieve::Expansion), at_field);
    let widened = respan(quote!(#krate::__private::retrieve::Expanded), at_field);
    quote_spanned! {at_field=>
      let __ingraph_asked__: #takes = #taken;
      let __ingraph_road__: &#seat<#takes> = #held;
      let __ingraph_family__: ::std::vec::Vec<#widened<#answers>> =
        #seat::expand(__ingraph_road__, __ingraph_asked__).await;
    }
  }

  /// ④ **THE CROSSING** — one dispatch per lane, with every guardrail the fan seat enforces.
  ///
  /// The seat is ASCRIBED for the widening's reason and at the widening's cost. The question crosses
  /// as a BORROW, which is what lets a router spelled for `str` be asked by a chain carrying a
  /// `String`: an argument position is a coercion site, so the step before a crossing owes the
  /// router's own question type nothing but a deref.
  ///
  /// The refusal is MATCHED rather than `?`-ed, on [`hop`](Self::hop)'s own measured reason.
  fn crossing(
    &self,
    at: usize,
    step: &StepModel,
    refusal: &syn::Ident,
  ) -> proc_macro2::TokenStream {
    let krate = &self.krate;
    let at_field = step.field.span();
    let held = held(at, at_field);
    let takes = self.takes(at);
    let variant = Self::variant(step);
    let taken = if at == 0 {
      quote_spanned!(at_field=> question)
    } else {
      quote_spanned!(at_field=> __ingraph_answered__)
    };
    let Some(Fan::Route { router, .. }) = &step.fan else {
      return quote!();
    };
    let router = router.spelled(krate, &takes);
    let seat = respan(quote!(#krate::__private::route::LaneFan), at_field);
    quote_spanned! {at_field=>
      let __ingraph_asked__: #takes = #taken;
      let __ingraph_fan__: &#seat<#router> = #held;
      let __ingraph_probes__ = match #seat::route(__ingraph_fan__, &__ingraph_asked__) {
        ::core::result::Result::Ok(__ingraph_probes__) => __ingraph_probes__,
        ::core::result::Result::Err(__ingraph_refused__) => {
          return ::core::result::Result::Err(#refusal::#variant(__ingraph_refused__));
        }
      };
    }
  }

  /// **ONE GRID CELL** — the tail's stream, filed under its arm and its lane at `arm × lane`.
  ///
  /// The three constructors are the three shapes a fan has, and the axis a tower did not open is
  /// SPELLED rather than filled with a literal: `uncut` names the roster's own default lane and
  /// `unwidened` names the sole arm, so a reader of this expansion is told which segment is missing
  /// instead of being shown a `1.0` to interpret.
  fn cell(&self, widens: bool, crosses: bool) -> proc_macro2::TokenStream {
    let krate = &self.krate;
    let at_field = self
      .steps
      .last()
      .map_or_else(proc_macro2::Span::call_site, |step| step.field.span());
    let stream = respan(quote!(#krate::__private::retrieve::FanStream), at_field);
    let ranked = respan(quote!(#krate::__private::retrieve::RankedStream), at_field);
    let found = quote_spanned!(at_field=> #ranked::into_ranked(__ingraph_answered__));
    let built = match (widens, crosses) {
      (true, true) => quote_spanned!(at_field=> #stream::new(
        __ingraph_lane__,
        __ingraph_arm__,
        __ingraph_arm_weight__,
        __ingraph_lane_weight__,
        #found,
      )),
      (true, false) => {
        quote_spanned!(at_field=> #stream::uncut(__ingraph_arm__, __ingraph_arm_weight__, #found))
      }
      (false, true) => quote_spanned!(at_field=>
        #stream::unwidened(__ingraph_lane__, __ingraph_lane_weight__, #found)
      ),
      (false, false) => return quote!(),
    };
    quote_spanned!(at_field=> ::std::vec::Vec::push(&mut __ingraph_grid__, #built);)
  }

  /// **THE FOLD AT THE MOUTH** — the grid in, the tower's one answer out.
  ///
  /// The join is the HASHED one, and that is a recorded choice rather than an unexamined default:
  /// every root key this framework emits hashes today, which is the same fact
  /// [`HashJoin`](https://docs.rs/ingraph) 's own note states. A tower whose root cannot hash needs
  /// the `eq` mechanism, and the word that would pick it is a DOOR — the search recipe's own
  /// `dedup(…)` at the tower grain — recorded here rather than guessed at now.
  ///
  /// The fold's `k` is likewise the shipped [`Fusion::rrf`](https://docs.rs/ingraph) and not a knob:
  /// the flavour a caller names rides the request road that the recipe already carries, and wiring a
  /// second home for it here is the knobs task's, not this one's.
  fn fold(&self) -> proc_macro2::TokenStream {
    let krate = &self.krate;
    let at_field = self
      .steps
      .last()
      .map_or_else(proc_macro2::Span::call_site, |step| step.field.span());
    let tail = self.tail();
    let stream = respan(quote!(#krate::__private::retrieve::RankedStream), at_field);
    let root = quote_spanned!(at_field=> <#tail as #stream>::Root);
    let evidence = quote_spanned!(at_field=> <#tail as #stream>::Evidence);
    let join = respan(quote!(#krate::__private::retrieve::HashJoin), at_field);
    let fold = respan(quote!(#krate::__private::retrieve::fuse_fanned), at_field);
    let fusion = respan(quote!(#krate::__private::retrieve::Fusion), at_field);
    quote_spanned! {at_field=>
      ::core::result::Result::Ok(#fold::<#root, #evidence, #join<#root>>(
        __ingraph_grid__,
        #fusion::rrf(),
      ))
    }
  }

  /// ONE HOP: what it is handed, what it answers, and the refusal it reports under.
  ///
  /// **BOTH ENDS ARE ASCRIBED, which is the double pin**: the question this hop takes and the
  /// answer it gives are written down beside the call, so the obligation the call raises is the
  /// exact `Serves<Q, A>` the chain arrived at rather than one with a floating parameter — a step
  /// with no impl reports the missing bound instead of *type annotations needed*.
  ///
  /// The call goes through the TRAIT PATH rather than through a method, which is the ask road's own
  /// spelling one layer over and is not a style choice: `step.serve(…)` is `E0599` *no method named
  /// `serve`* when a step wears the other face, and a second refusal standing in front of the one
  /// the walk is about is exactly the shape that hid a real fixture's pin one round ago.
  fn hop(
    &self,
    at: usize,
    step: &StepModel,
    refusal: &syn::Ident,
    reborrowed: bool,
  ) -> proc_macro2::TokenStream {
    // ⟂ THE DISPATCH LIVES HERE, at the one function every position in the walk already calls —
    // before the fan, between the two segments, inside the cell — so an annotation stage is walked
    // wherever a step is walked and no caller learns a third case. The stage law puts a ⟂ step
    // before both fan words, so today it only ever lands in the run before the fan; a hand-built
    // model that put one elsewhere still gets the hop it declared rather than silence.
    if step.annotation.is_some() {
      return self.annotating(at, step, refusal, reborrowed);
    }
    let at_field = step.field.span();
    let held = held(at, at_field);
    // **INSIDE A FAN'S LOOPS THE BORROW IS REBORROWED**, and outside them it is not. A `&mut` handed
    // to a call is moved, so a step under a loop would be gone after the first turn; `&mut *step` is
    // the same borrow, taken again. It is spelled only where it is needed, which is what leaves an
    // unfanned tower's every hop the tokens it already had.
    let held = if reborrowed {
      quote_spanned!(at_field=> &mut *#held)
    } else {
      quote_spanned!(at_field=> #held)
    };
    let takes = self.takes(at);
    let answers = self.answered(step);
    let face = respan(self.face(step), at_field);
    let variant = Self::variant(step);
    // EVERY token of the hop carries the step's span, this one included. An argument left at the
    // emitter's own call site is what a trait-resolution failure gets reported at when the
    // parameters cannot be inferred — the caret lands on the attribute rather than on the field,
    // which is the report a reader cannot act on.
    let taken = if at == 0 {
      quote_spanned!(at_field=> question)
    } else {
      quote_spanned!(at_field=> __ingraph_answered__)
    };
    let landed = step.awaited.then(|| quote_spanned!(at_field=> .await));
    let named = Self::named(step, at_field);
    // MATCHED RATHER THAN `map_err(…)?`, measured on the goldens: the combinator raises its
    // obligation through `Result::map_err`'s own `FnOnce` bound, so a broken hop earned a *required
    // by a bound in `Result::<T, E>::map_err`* note pointing a declaration's author into
    // `core/src/result.rs`. The match raises the same obligation with nothing of the standard
    // library between the step and the report.
    quote_spanned! {at_field=>
      let __ingraph_asked__: #takes = #taken;
      let __ingraph_answered__: #answers = match #face::serve(
        #held,
        __ingraph_asked__,
        #named,
      )
      #landed
      {
        ::core::result::Result::Ok(__ingraph_answered__) => __ingraph_answered__,
        ::core::result::Result::Err(__ingraph_refused__) => {
          return ::core::result::Result::Err(#refusal::#variant(__ingraph_refused__));
        }
      };
    }
  }

  /// ⟂ **THE ANNOTATION STAGE** — the question asked whether it was already told, and the operator
  /// spent only where it was not.
  ///
  /// ```ignore
  /// let __ingraph_asked__: Q = question;
  /// let __ingraph_told__ = Option::is_some(&<Q as AnnotatedQuestion<A>>::carried(&__ingraph_asked__));
  /// let __ingraph_answered__: Q = if __ingraph_told__ { __ingraph_asked__ } else { /* the hop */ };
  /// ```
  ///
  /// # FILL-IF-ABSENT IS A BRANCH AND NOT A MERGE
  ///
  /// The caller's own value is not compared, not merged and not overwritten — the question is
  /// handed on **untouched**, the same value it arrived as. That is the whole of *never override*:
  /// there is no line here that could take a request's own statement and replace it, so the rule is
  /// a property of the emission rather than a discipline a stage's author has to keep.
  ///
  /// **The operator is NOT CONSULTED**, which is a reading rather than an accident. A stage mounted
  /// on a resident is *query-time compute over an exclusive model*, and calling one to discard its
  /// answer would spend a forward pass the request had already made unnecessary. The alternative —
  /// call, then drop — buys exactly one thing, a tap that sees every question, and a stage that
  /// wants that can be given it where taps live.
  ///
  /// # WHY THE TEST IS A `let` AND NOT AN `if` CONDITION
  ///
  /// [`AnnotatedQuestion::carried`](https://docs.rs/ingraph) borrows the question, and the arm that
  /// takes the untouched road MOVES it. Binding the boolean first ends that borrow at the
  /// statement's own semicolon, which is a rule about temporaries this emission does not have to
  /// reason about twice.
  ///
  /// The refusal is MATCHED rather than `?`-ed, on [`hop`](Self::hop)'s own measured reason, and the
  /// step's face is the step's own word: an LID behind a [`Door`](https://docs.rs/ingraph) wears the
  /// awaited one, an in-process detector wears the blocking one, and the stage cares about neither.
  fn annotating(
    &self,
    at: usize,
    step: &StepModel,
    refusal: &syn::Ident,
    reborrowed: bool,
  ) -> proc_macro2::TokenStream {
    let krate = &self.krate;
    let at_field = step.field.span();
    let held = held(at, at_field);
    let held = if reborrowed {
      quote_spanned!(at_field=> &mut *#held)
    } else {
      quote_spanned!(at_field=> #held)
    };
    let takes = self.takes(at);
    let face = respan(self.face(step), at_field);
    let seam = respan(
      quote!(#krate::__private::retrieve::AnnotatedQuestion),
      at_field,
    );
    let variant = Self::variant(step);
    let taken = if at == 0 {
      quote_spanned!(at_field=> question)
    } else {
      quote_spanned!(at_field=> __ingraph_answered__)
    };
    let landed = step.awaited.then(|| quote_spanned!(at_field=> .await));
    let named = Self::named(step, at_field);
    let annotation = step.annotation.as_ref();
    quote_spanned! {at_field=>
      let __ingraph_asked__: #takes = #taken;
      let __ingraph_told__ = ::core::option::Option::is_some(
        &<#takes as #seam<#annotation>>::carried(&__ingraph_asked__),
      );
      let __ingraph_answered__: #takes = if __ingraph_told__ {
        __ingraph_asked__
      } else {
        match #face::serve(
          #held,
          __ingraph_asked__,
          #named,
        )
        #landed
        {
          ::core::result::Result::Ok(__ingraph_answered__) => __ingraph_answered__,
          ::core::result::Result::Err(__ingraph_refused__) => {
            return ::core::result::Result::Err(#refusal::#variant(__ingraph_refused__));
          }
        }
      };
    }
  }

  /// **WHAT THIS CALL NAMED FOR ONE STEP** — the projection out of the tower's own options object.
  ///
  /// The tower's options are per TOWER and a seat is per SERVER, so what a step is handed is ITS OWN
  /// field and nothing else. `and_then` folds the two absences into the one that reaches the step —
  /// no options at all, and options that named nothing for this step, are the same fact from a
  /// step's side: *this call named nothing*.
  ///
  /// The field is read directly rather than through the getter, this expansion and the struct being
  /// one scope; the getter is for everybody else.
  ///
  /// It is a function rather than a line inside the hop because a FAN SEGMENT reads one too: a
  /// widening's row is the arm weight, so the projection is spent at a position that serves no verb.
  fn named(step: &StepModel, at_field: proc_macro2::Span) -> proc_macro2::TokenStream {
    let field = &step.field;
    quote_spanned! {at_field=>
      ::core::option::Option::and_then(options, |__ingraph_options__| {
        ::core::option::Option::as_ref(&__ingraph_options__.#field)
      })
    }
  }

  /// A type as the DOC spells it: the written word, or the canonical line in the short form a
  /// reader would write by hand.
  ///
  /// The emitted projection goes through `__private`, which is a shelf path and not a sentence. A
  /// doc line is read by the author, so what it shows is `<Tokenize as DefaultServe>::Answer` — the
  /// same fact in the spelling the declaration's own crate would use.
  fn written(step: &StepModel, seat: &str) -> String {
    let ty = &step.ty;
    format!("<{} as DefaultServe>::{seat}", spelled(&quote!(#ty)))
  }

  /// The walk's own doc line — the chain an author reads back, and the face the OR law chose.
  fn doc(&self) -> String {
    let chain = self
      .steps
      .iter()
      .map(|step| {
        let ty = &step.ty;
        format!(
          "| `{field}` | `{ty}` | {face} | `{answer}` |",
          field = step.field,
          ty = spelled(&quote!(#ty)),
          face = if step.awaited { "awaited" } else { "blocking" },
          answer = step.answer.as_ref().map_or_else(
            || Self::written(step, "Answer"),
            |answer| spelled(&quote!(#answer)),
          ),
        )
      })
      .collect::<Vec<_>>()
      .join("\n");
    let asked = match (&self.question, self.steps.first()) {
      (Some(question), _) => spelled(&quote!(#question)),
      (None, Some(head)) => Self::written(head, "Question"),
      (None, None) => "()".to_owned(),
    };
    format!(
      "Walk this tower — [`{name}`]'s question pipeline, from `{question}` to `{answer}` in one \
       {face}function.\n\nThe question comes FIRST, then one `&mut` borrow per step in declaration \
       order, then [`{options}`]({options}) — the tower's own options, out of which each hop is \
       handed ITS OWN field. The face is {face}because {why} — the OR law.\n\n| step | server | \
       face | answers |\n|---|---|---|---|\n{chain}\n\nA hop this call named nothing for is served \
       under `None` and runs at its own floor, and `None` for the whole seat names nothing for any \
       of them.\n\n# Errors\n\nThe step that refused, as the arm of [`{error}`]({error}) named \
       after it.",
      name = self.name,
      error = self.error_name(),
      options = self.step_options_name(),
      question = asked,
      answer = self.steps.last().map_or_else(
        || "()".to_owned(),
        |step| step.answer.as_ref().map_or_else(
          || Self::written(step, "Answer"),
          |answer| spelled(&quote!(#answer)),
        ),
      ),
      face = if self.awaited() {
        "awaited "
      } else {
        "blocking "
      },
      why = if self.awaited() {
        "at least one step is awaited"
      } else {
        "every step is blocking"
      },
    )
  }
}

/// A TYPE as a reader writes it, off the tokens it was parsed from.
///
/// `quote!`'s own rendering spaces every token, so `Vec < String >` is what a doc line would carry
/// otherwise. This is a doc-line spelling and never an identity: two types that print the same are
/// still whatever the compiler resolves them to.
fn spelled(tokens: &proc_macro2::TokenStream) -> String {
  tokens
    .to_string()
    .replace(" < ", "<")
    .replace(" >", ">")
    .replace(" :: ", "::")
    .replace(" , ", ", ")
}

/// A step's parameter name in the walk — `__`-pinned so that a field called `question` or `options`
/// cannot shadow the two seats it sits between.
///
/// Positional rather than named after the field, per the tower core's own spelling: what a caller
/// reads is the doc table above, which names every step, and what the compiler reports is a
/// position.
///
/// Minted AT THE STEP'S FIELD, because an argument is where a trait-resolution failure is reported:
/// a parameter left at the emitter's own call site puts the caret on the attribute.
fn held(at: usize, at_field: proc_macro2::Span) -> syn::Ident {
  quote::format_ident!("__ingraph_step{at}__", span = at_field)
}