guibiao 0.9.0

圭表 (Guibiao) — Tianheng's dependency-light static observation core (derived from modou). Declare crate, module, and dependency-source boundaries in Rust — dependencies by name, module imports, and each dependency's declared source kind (git/registry/path) for manifest hygiene — observed from cargo metadata and source use-scans, reacted in CI. No AST: the syn-free gnomon of the family.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
//! The one resolver: what a written path names from the scope it stands in, and what a crate-rooted path names once
//! every module of a compilation unit is read.
//!
//! A lookup walks the occurrence's chain of blocks up to its module; where one scope binds a name more than once —
//! cfg-exclusive imports, which the scanner reads cfg-blind — every binding is a candidate. A glob is an edge to the
//! module it names: every glob's targets are read once for the unit, as a fixed point, and a lookup through a glob the
//! [`Walk`] is already looking the same name up through ends as a cycle. Each segment a
//! module binds rather than declares is replaced by every path that binding names, and every path a resolution passes
//! is a path it names. Every written path's first segment is classified by one dispatch, [`written_root`], and every
//! answer is a typed [`Named`] each reader matches exhaustively.
//!
//! [`MAX_RESOLUTION_CHAIN`] caps two counts, each on its own: the bindings and glob paths one [`Walk`] is nested
//! inside, and the segments one branch of [`CrateScopes::denote`] replaces, each branch counted from where it began. A
//! binding or glob a walk already holds, or a segment a branch already replaced, ends it as a cycle. What a lookup
//! through globs reaches is no walk: [`CrateScopes::through_globs`] reads every scope it reaches once into one graph
//! and settles it, and [`CrateScopes::glob_targets`] reads what the unit's globs name in passes, each bounded by the
//! size of what it reads rather than by the cap. Scopes, modules, blocks
//! and names are held in ordered maps, so every lookup meets them in one order; a fold across several answers —
//! [`joined`], a crate-rooted path's candidates, the glob hazard — takes the least refusal and reads every answer,
//! while a refusal met inside one scope's lookup ends that lookup with it.

use std::cell::RefCell;
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::rc::Rc;

use super::item_head::Visibility;
use super::path_vocab::path_within;
use super::path_vocab::{PathSite, WrittenRoot, written_root};
use super::path_vocab::{Sysroot, sysroot_crate};
use super::path_vocab::{block_segment, is_block_segment, names_a_block_item, readable_module};
pub(super) use super::scope_tree::Namespace;
use super::scope_tree::{Binding, DeclKind, Declaration, ScopeKind, ScopeTable};
use super::token_tree::Edition;

/// The cap on the links of a chain of `type` aliases, imports, globs and re-exports a resolution walks, which bounds
/// how deep a pathological source can walk — set far beyond any real source. A resolution that walks past it answers
/// [`Named::PastCap`] with [`chain_refusal`], which the reader refuses as a scan error. How wide a walk reads is
/// bounded apart from it, by the memo [`CrateScopes::scope_lookup`] keeps: a scope's answer for a name is read once per
/// depth rather than once per path, so a lattice of globs is read in time its size bounds rather than its path count.
const MAX_RESOLUTION_CHAIN: usize = 64;

/// The candidate entries one resolution reading may hold. Depth alone does not bound a branching glob: this limit
/// and [`MAX_RESOLUTION_BYTES`] refuse its width before another pass can multiply it.
const MAX_RESOLUTION_PATHS: usize = 32_768;
/// The bytes of path text one resolution reading may hold, beside [`MAX_RESOLUTION_PATHS`].
const MAX_RESOLUTION_BYTES: usize = 8 * 1024 * 1024;

/// The held answers of a whole glob graph have their own aggregate budget: a long chain repeats its intermediate
/// paths in each scope's answer even though no individual answer is wide.
const MAX_GLOB_GRAPH_PATHS: usize = 1_048_576;
/// The bytes of path text a glob graph's held answers may total, beside [`MAX_GLOB_GRAPH_PATHS`].
const MAX_GLOB_GRAPH_BYTES: usize = 64 * 1024 * 1024;

/// The refusal of a reading holding more than [`MAX_RESOLUTION_PATHS`] paths or [`MAX_RESOLUTION_BYTES`] bytes of
/// path text: the one wording every reading past that per-reading budget uses.
fn width_refusal() -> String {
    format!(
        "cannot judge a resolution holding more than {MAX_RESOLUTION_PATHS} candidate paths or \
         {MAX_RESOLUTION_BYTES} bytes of path text; reduce the branching imports, globs or re-exports"
    )
}

/// What a reading has charged against its width budget: how many candidate paths it holds and how many bytes of
/// path text, checked against the per-reading limits or, for a glob graph's held answers, the graph's.
#[derive(Default)]
pub(super) struct ReadingSize {
    /// How many paths have been charged.
    paths: usize,
    /// How many bytes of path text have been charged.
    bytes: usize,
}

impl ReadingSize {
    /// Charge one path and its text, refused once the reading passes the per-reading budget.
    pub(super) fn add(&mut self, path: &str) -> Result<(), String> {
        self.paths = self.paths.saturating_add(1);
        self.bytes = self.bytes.saturating_add(path.len());
        self.check()
    }

    /// Charge every path `head` holds — bound, declared, passed, the name's own heads and foreign names — refused
    /// once the per-reading budget is passed. An answer holding no paths charges nothing.
    fn head(&mut self, head: &Head) -> Result<(), String> {
        match head {
            Head::Candidates {
                bound,
                declared,
                through,
                heads,
                foreign,
                ..
            } => {
                for path in bound
                    .iter()
                    .map(|(path, _)| path.as_str())
                    .chain(declared.iter().map(Declared::path))
                    .chain(
                        through
                            .iter()
                            .chain(heads)
                            .chain(foreign)
                            .map(String::as_str),
                    )
                {
                    self.add(path)?;
                }
                Ok(())
            }
            Head::Foreign(paths) => paths.iter().try_for_each(|path| self.add(path)),
            _ => Ok(()),
        }
    }

    /// Refuse once what is charged passes [`MAX_GLOB_GRAPH_PATHS`] paths or [`MAX_GLOB_GRAPH_BYTES`] bytes.
    fn check_graph(&self) -> Result<(), String> {
        if self.paths > MAX_GLOB_GRAPH_PATHS || self.bytes > MAX_GLOB_GRAPH_BYTES {
            Err(format!(
                "cannot judge a glob graph holding more than {MAX_GLOB_GRAPH_PATHS} candidate paths or \
                         {MAX_GLOB_GRAPH_BYTES} bytes of path text; reduce the branching imports, globs or re-exports"
            ))
        } else {
            Ok(())
        }
    }

    /// Refuse, with [`width_refusal`], once what is charged passes the per-reading budget.
    fn check(&self) -> Result<(), String> {
        if self.paths > MAX_RESOLUTION_PATHS || self.bytes > MAX_RESOLUTION_BYTES {
            Err(width_refusal())
        } else {
            Ok(())
        }
    }
}

/// The refusal of a chain longer than [`MAX_RESOLUTION_CHAIN`] links, quoting the binding it was measured
/// from and the module that binding is written in: the one wording every walk that meets the cap uses.
fn chain_refusal(quote: &str, module: &str) -> String {
    format!(
        "cannot judge a chain of more than {MAX_RESOLUTION_CHAIN} imports, globs, re-exports and `type` \
         aliases from `{quote};` in {}",
        readable_module(module)
    )
}

/// What a written path names from the scope it stands in: the resolver's typed answer, which each
/// reader matches exhaustively.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum Named {
    /// Every path it names — through the bindings of the nearest scope that binds its head, an item a
    /// module declares, a sysroot crate or a crate-rooted path — each carried through what a
    /// crate-rooted path names.
    Paths(Vec<String>),
    /// A crate the path names by its root (`::dep::…`, and in edition 2015 a root path no crate-root
    /// name claims), without the `::`.
    External(String),
    /// A bare head no scope between the path and its module binds for certain, and that names no sysroot crate:
    /// a crate the head may name, judged by the reader's policy, beside `also`, what scopes binding the head only
    /// where that may not hold named it as — empty where no scope binds it at all.
    Unbound {
        /// The head no scope binds for certain, which may name a crate.
        head: String,
        /// The segments written after the head.
        rest: Vec<String>,
        /// What scopes binding the head where that may not hold named it as; empty where no scope binds it.
        also: Vec<String>,
    },
    /// A block-local item. It is named by no path outside its block, so no prefix reaches it.
    Local,
    /// Nothing a path can start from.
    Invalid,
    /// A refusal of the walk rather than an answer, carrying its message: a chain longer than
    /// [`MAX_RESOLUTION_CHAIN`] links, quoting where it was measured from; the answers of the globs reaching a
    /// head not settling within the graph's readings; or a compilation unit's globs not settling on what they
    /// name within the fixed point's passes.
    PastCap(String),
}

/// A declaration a lookup reached, by what a path through it reads next.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(super) enum Declared {
    /// A module — a declared one, or the crate an `extern crate self` names — whose own scope the rest of a
    /// path is read in.
    Module(String),
    /// An item, or the root of a crate whose contents are not read: the path names it, followed by the rest.
    Item(String),
}

impl Declared {
    /// The path the declaration names, a module's or an item's alike.
    pub(super) fn path(&self) -> &str {
        match self {
            Declared::Module(path) | Declared::Item(path) => path,
        }
    }
}

/// A path a binding names, still to be read, with how that binding is written — what a refusal of a chain through
/// it quotes, recorded where the binding is met rather than looked up again.
type Bound = (String, String);

/// What a name is looked up as in one scope, before the rest of its path is read.
#[derive(Clone, PartialEq, Eq)]
enum Head {
    /// Every candidate the scope binds or declares it as, or else what its globs bring: the paths its
    /// bindings name, still to be read — a name a glob brings is a binding of the scope the glob is written
    /// in — and the items it declares, by crate-rooted path, which name themselves. Neither removes the
    /// other — cfg-exclusive, both can be the live one. `through` holds the paths a name a glob brings passes
    /// on its way — the glob's module followed by the name — which a call reports under and which are not read
    /// again, since what they name is already among the candidates, read where the glob stands.
    ///
    /// `heads` holds what the name alone names where the lookup found it, before anything it names is read further:
    /// the paths its bindings name and the paths it declares, and for a name a glob brings the glob's module followed
    /// by the name. A fold of several answers joins them, so a name bound in one namespace and brought by a glob in
    /// the other keeps both.
    ///
    /// `foreign` holds what a glob of a crate whose contents are not read brings the name as, where a fold joined such
    /// an answer with this one — cfg-exclusive globs or files, or the two namespaces of one lookup — since either can
    /// be the live one; it is read as [`Head::Foreign`] is, by a path through the scope's module alone.
    Candidates {
        /// The paths the scope's bindings name, still to be read, each with how its binding is written.
        bound: Vec<Bound>,
        /// What the scope declares the name as, each by what a path through it reads next.
        declared: Vec<Declared>,
        /// The paths a name a glob brings passes on its way, reported under but not read again.
        through: Vec<String>,
        /// What the name alone names where the lookup found it, before anything it names is read further.
        heads: Vec<String>,
        /// What a glob of a crate whose contents are not read brings the name as, from an answer of that kind
        /// a fold joined with this one.
        foreign: Vec<String>,
        /// Whether the lookup read past every scope on its chain without one ending it, every answer here one that
        /// may not hold on every build, so the head may also name what no scope binds: a sysroot crate or a
        /// dependency.
        open: bool,
    },
    /// The scope declares or imports the name only as a block-local item, which no path outside its block names.
    Local,
    /// Nothing the scope binds or declares, and nothing its globs of this compilation unit bring, but a glob of
    /// a crate whose contents are not read can: that glob's path with the name appended, for each such glob.
    /// A path through the scope's module names what one of them names, since nothing else can; a bare head
    /// written in the scope may instead name a prelude or a local binding, so the lexical lookup reads it as
    /// [`Head::Unbound`] and the glob's own finding is what reacts.
    Foreign(Vec<String>),
    /// Nothing the scope binds or declares under the name, and nothing any of its globs brings.
    Unbound,
    /// A refusal of the walk, as [`Named::PastCap`] carries one.
    PastCap(String),
}

/// One scope a lookup through globs reaches, seen from a module: its table, its scope and that module.
type GlobNode = (usize, u32, String);

/// What [`CrateScopes::through_globs`] read of one scope: its answer, where the scope binds or declares the name for
/// certain or its answer is already kept, or the globs it reads the name through — beside `own`, what the scope binds
/// or declares it as where that may not hold on every build ([`CrateScopes::may_not_hold_here`]), joined with what the
/// globs bring.
enum GlobRead {
    /// The scope's answer, kept or read from what it binds, ends the lookup — a name bound or declared for certain,
    /// or a refusal — or reading its globs refused; its globs are not read.
    Answered(Head),
    /// The scope answers what its globs bring, joined with what it binds or declares itself.
    Globs {
        /// What the scope binds or declares the name as where that may not hold on every build; `None` where it
        /// binds and declares nothing.
        own: Option<Head>,
        /// One edge per target of each glob of the scope that the module it is seen from can see.
        edges: Vec<GlobEdge>,
    },
}

/// One glob of a scope a lookup through globs reads: into the scopes of a module of the unit, by their positions in
/// the graph, or a name of a crate whose contents are not read.
enum GlobEdge {
    /// A glob naming a module of the unit, read through that module's scopes.
    Into {
        /// How the glob is written, which a declaration it brings is bound through.
        quote: String,
        /// The module the glob names; that path followed by the name is the path a name it brings passes.
        target: String,
        /// The graph positions of the module's scopes, one per declaration of the module.
        into: Vec<usize>,
    },
    /// A glob of anything but a module of the unit — a crate whose contents are not read, or an item such as an enum:
    /// its path with the name appended, the one thing it can bring.
    Foreign(String),
}

/// The scopes a lookup through globs reaches, each once, in the order they were met, and what each read.
#[derive(Default)]
struct GlobGraph {
    /// Every scope reached, each with the module it is seen from, in the order met; a node's position here is its
    /// position in `reads` and in a settled answer.
    nodes: Vec<GlobNode>,
    /// Each node's position in `nodes`, so a scope met again from the same module is not added twice.
    index: HashMap<GlobNode, usize>,
    /// What each node read, at the node's own position.
    reads: Vec<GlobRead>,
}

impl GlobGraph {
    /// The position of a scope seen from `from`, added where it is met first.
    fn node(&mut self, t: usize, id: u32, from: &str) -> usize {
        let key = (t, id, from.to_string());
        if let Some(&n) = self.index.get(&key) {
            return n;
        }
        self.nodes.push(key.clone());
        self.index.insert(key, self.nodes.len() - 1);
        self.nodes.len() - 1
    }

    /// Every scope's answer for `head`, read to a fixed point: a scope that reads its globs answers what they bring
    /// joined, starting from none, each read after the scopes its globs reach where no cycle forbids it, and every
    /// such scope is read again until a reading changes nothing. The readings are bounded by the graph's size plus
    /// one; past it every answer is refused, since a graph whose answers do not settle is one the scanner cannot judge.
    fn settle(&self, head: &str) -> Result<Vec<Head>, String> {
        let order = self.children_first();
        let mut total = ReadingSize::default();
        let mut sizes = Vec::new();
        let mut answers = Vec::new();
        for read in &self.reads {
            let answer = match read {
                GlobRead::Answered(answer) => answer.clone(),
                GlobRead::Globs { own, .. } => own.clone().unwrap_or(Head::Unbound),
            };
            let mut size = ReadingSize::default();
            size.head(&answer)?;
            total.paths += size.paths;
            total.bytes += size.bytes;
            total.check_graph()?;
            sizes.push(size);
            answers.push(answer);
        }
        for _ in 0..=self.nodes.len() {
            let mut changed = false;
            for &n in &order {
                let GlobRead::Globs { own, edges } = &self.reads[n] else {
                    continue;
                };
                let globbed = match joined(edges.iter().map(|edge| match edge {
                    GlobEdge::Foreign(path) => Head::Foreign(vec![path.clone()]),
                    GlobEdge::Into {
                        quote,
                        target,
                        into,
                    } => brought_through(
                        joined(into.iter().map(|&m| answers[m].clone())),
                        quote,
                        target,
                        head,
                    ),
                })) {
                    Head::Local => Head::Unbound,
                    other => other,
                };
                let answer = match (own, globbed) {
                    (None, globbed) => globbed,
                    (Some(own), Head::Unbound) => own.clone(),
                    (Some(own), globbed) => joined([own.clone(), globbed]),
                };
                if answer != answers[n] {
                    let mut size = ReadingSize::default();
                    size.head(&answer)?;
                    total.paths = total.paths - sizes[n].paths + size.paths;
                    total.bytes = total.bytes - sizes[n].bytes + size.bytes;
                    total.check_graph()?;
                    sizes[n] = size;
                    answers[n] = answer;
                    changed = true;
                }
            }
            if !changed {
                return Ok(answers);
            }
        }
        Err(format!(
            "cannot judge what the globs reaching `{head}` bring: their answers do not settle within {} readings",
            self.nodes.len() + 1
        ))
    }

    /// Every node, each after the nodes its globs reach where no cycle forbids it: a depth-first walk from each node
    /// not yet met, held on an explicit stack so a long chain of globs is no recursion.
    fn children_first(&self) -> Vec<usize> {
        let children = |n: usize| -> Vec<usize> {
            match &self.reads[n] {
                GlobRead::Globs { edges, .. } => edges
                    .iter()
                    .flat_map(|edge| match edge {
                        GlobEdge::Into { into, .. } => into.clone(),
                        GlobEdge::Foreign(_) => Vec::new(),
                    })
                    .collect(),
                GlobRead::Answered(_) => Vec::new(),
            }
        };
        let mut order = Vec::with_capacity(self.nodes.len());
        let mut seen = vec![false; self.nodes.len()];
        for root in 0..self.nodes.len() {
            if seen[root] {
                continue;
            }
            seen[root] = true;
            let mut stack = vec![(root, children(root), 0usize)];
            while let Some((n, kids, next)) = stack.last_mut() {
                if let Some(&kid) = kids.get(*next) {
                    *next += 1;
                    if !seen[kid] {
                        seen[kid] = true;
                        stack.push((kid, children(kid), 0));
                    }
                } else {
                    order.push(*n);
                    stack.pop();
                }
            }
        }
        order
    }
}

/// What a glob of `target`, written `quote`, brings `head` as from what `target`'s scopes answer: a name `target`
/// binds or declares is bound where the glob stands, through the glob's own quote for a declaration, the path
/// `target::head` is passed on the way, and what the name alone names there is that path.
fn brought_through(found: Head, quote: &str, target: &str, head: &str) -> Head {
    match found {
        Head::Candidates {
            bound,
            declared,
            through,
            foreign,
            ..
        } => Head::Candidates {
            bound: bound
                .into_iter()
                .chain(
                    declared
                        .iter()
                        .map(|d| (d.path().to_string(), quote.to_string())),
                )
                .collect(),
            declared: Vec::new(),
            through: through
                .into_iter()
                .chain([format!("{target}::{head}")])
                .collect(),
            heads: vec![format!("{target}::{head}")],
            foreign,
            open: false,
        },
        other => other,
    }
}

/// Whether a path names something in a namespace, as [`CrateScopes::denote_in`] ends its reading of it: it reaches a
/// declaration or a binding there; its last segment names nothing its module binds or declares in that namespace; or
/// what it reaches is not read — a crate whose contents are not read, a segment that names nothing before the last,
/// a cycle. Ordered from what says least to what says most, so the answer over several readings is their maximum.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
enum Presence {
    /// Its last segment names nothing its module binds or declares in that namespace.
    #[default]
    Absent,
    /// What it reaches is not read: a crate whose contents are not read, a cycle, a segment before the last that
    /// names nothing, or a name a module's macro invocations may generate.
    Unknown,
    /// It reaches a declaration or a binding there.
    Known,
}

/// What [`CrateScopes::denote_in`] reads a path as: every path the reading passes through, and whether the path
/// names something in the namespace its last segment was read in.
#[derive(Clone, Debug, Default)]
struct Denoted {
    /// Every path the reading passed through or named, sorted and deduplicated.
    paths: Vec<String>,
    /// The paths a glob of a crate whose contents are not read brings a segment as, beside what the segment's module
    /// binds or declares, or as the only foreign answer: candidates of what the path names, and never a module a
    /// glob reads names through, since
    /// what such a glob brings is a name and not a module the unit holds.
    beside: Vec<String>,
    /// Whether the path names something in the namespace its last segment was read in: the most any branch said.
    presence: Presence,
    /// Whether a foreign candidate lies within the hazard's prefix or, where ancestors are compared, is one of its
    /// ancestors; false where no hazard is compared.
    terminal_reaches: bool,
}

/// `path` with each segment of `rest` appended after a `::`.
pub(super) fn with_rest(mut path: String, rest: &[String]) -> String {
    for segment in rest {
        path.push_str("::");
        path.push_str(segment);
    }
    path
}

/// What an `extern crate` naming `target` declares: the crate root's module for `crate`, and otherwise the
/// root of a crate whose contents are not read.
pub(super) fn extern_crate_names(target: &str) -> Declared {
    if target == "crate" {
        Declared::Module(target.to_string())
    } else {
        Declared::Item(target.to_string())
    }
}

/// The bindings and globs one resolution is inside, outermost first, each with what it was written
/// as: how a cycle ends a resolution, and how a chain longer than the cap is refused, quoting the
/// binding it was measured from. `cuts` counts every cycle ended while reading, conservatively: a cycle
/// the walk ends makes the answer depend on the walk it was read in, and a cycle a path's own chain ends
/// is counted beside it, so an answer is remembered only where no cycle was cut at all.
#[derive(Default)]
pub(super) struct Walk {
    /// Every binding and glob the walk is inside, outermost first.
    resolving: Vec<Resolving>,
    /// How many cycles the walk has ended; an answer read while it grew is not memoized.
    cuts: usize,
}

/// One binding or glob a [`Walk`] is inside.
struct Resolving {
    /// The binding by its table, scope and name — a glob by `*` and its position — which a cycle is recognised by.
    key: (usize, u32, String),
    /// How the binding is written, which a refusal of a chain measured from it quotes.
    quote: String,
    /// The module the binding is written in, which that refusal names.
    module: String,
}

impl Walk {
    /// Whether the walk is already inside the binding or glob `key` — a cycle, which the walk ends there and
    /// counts.
    fn meets_cycle(&mut self, key: &(usize, u32, String)) -> bool {
        let cycle = self.resolving.iter().any(|entry| &entry.key == key);
        self.cuts += usize::from(cycle);
        cycle
    }

    /// Whether `key` is the binding the walk is reading now: the head of `use md5x::md5x;` looked up in its own scope.
    /// rustc resolves an import's path without that import, so the scope is read without it, which is the scope's
    /// answer for that lookup rather than a cycle the walk cut — and so it is kept, under its own memo key.
    fn reads_itself(&self, key: &(usize, u32, String)) -> bool {
        self.resolving.last().is_some_and(|entry| &entry.key == key)
    }

    /// Enter a binding, unless the chain already holds [`MAX_RESOLUTION_CHAIN`] links.
    fn enter(
        &mut self,
        key: (usize, u32, String),
        quote: String,
        module: &str,
    ) -> Result<(), String> {
        if self.resolving.len() >= MAX_RESOLUTION_CHAIN {
            let first = &self.resolving[0];
            return Err(chain_refusal(&first.quote, &first.module));
        }
        self.resolving.push(Resolving {
            key,
            quote,
            module: module.to_string(),
        });
        Ok(())
    }

    /// Leave the binding or glob entered last.
    fn leave(&mut self) {
        self.resolving.pop();
    }
}

/// What one binding names, read from its own scope: the paths still to be read, and the paths passed on the way
/// that are not.
pub(super) enum BindingNames {
    /// The paths the binding names, still to be read, and beside them the paths the reading passed on the way.
    Paths(Vec<String>, Vec<String>),
    /// The binding names a block-local item, which no path outside its block names.
    Local,
    /// A refusal of the walk, as [`Named::PastCap`] carries one.
    PastCap(String),
}

/// A memo key: a written path, the table and scope it stands in, where it stands, and the namespace its
/// last segment is read in.
type NameKey = (usize, u32, String, PathSite, Namespace);

/// A memo key for an import's presence: its table, scope, name, written path and namespace.
type PresenceKey = (usize, u32, String, String, Namespace);

/// A memo key for [`CrateScopes::denote`]: a path, the namespace its last segment is read in, and whether candidates
/// are requested for findings, or compared with a hazard prefix (and, for glob targets, its ancestors).
type DenoteKey = (String, Namespace, bool, Option<(String, bool)>);

/// Denotations retained by one unit, with keys and answers charged before insertion.
struct DenotationMemo {
    /// Each reading's answer by [`DenoteKey`], a refusal held as the answer so it is not read again.
    answers: HashMap<DenoteKey, Result<Rc<Denoted>, String>>,
    /// The candidate paths charged across every held answer.
    paths: usize,
    /// The bytes of key, path and refusal text charged across every held answer.
    bytes: usize,
    /// The most entries, candidate paths and bytes the memo holds, in that order; an insertion past any one is
    /// refused and holds nothing.
    limits: (usize, usize, usize),
}

impl Default for DenotationMemo {
    fn default() -> Self {
        Self {
            answers: HashMap::new(),
            paths: 0,
            bytes: 0,
            limits: (262_144, 1_048_576, 64 * 1024 * 1024),
        }
    }
}

impl DenotationMemo {
    /// The answer held for `key`, a refusal included.
    fn get(&self, key: &DenoteKey) -> Option<&Result<Rc<Denoted>, String>> {
        self.answers.get(key)
    }

    /// Hold `answer` under `key`, charging the key's text and the answer's paths or refusal; an insertion past the
    /// limits holds nothing and refuses the reading.
    fn insert(
        &mut self,
        key: DenoteKey,
        answer: Result<Rc<Denoted>, String>,
    ) -> Result<(), String> {
        let mut paths = self.paths;
        let mut bytes = self.bytes.saturating_add(key.0.len());
        if let Some((prefix, _)) = &key.3 {
            bytes = bytes.saturating_add(prefix.len());
        }
        match &answer {
            Ok(answer) => {
                for path in answer.paths.iter().chain(&answer.beside) {
                    paths = paths.saturating_add(1);
                    bytes = bytes.saturating_add(path.len());
                }
            }
            Err(message) => bytes = bytes.saturating_add(message.len()),
        }
        let (entries_limit, paths_limit, bytes_limit) = self.limits;
        if self.answers.len() >= entries_limit || paths > paths_limit || bytes > bytes_limit {
            return Err(format!(
                "cannot judge a denotation memo holding more than {entries_limit} readings, {paths_limit} candidate paths or {bytes_limit} bytes of key and answer text; reduce the branching imports, globs or re-exports"
            ));
        }
        self.answers.insert(key, answer);
        self.paths = paths;
        self.bytes = bytes;
        Ok(())
    }

    /// Drop every held answer and its charges, keeping the limits.
    fn clear(&mut self) {
        self.answers.clear();
        self.paths = 0;
        self.bytes = 0;
    }
}

/// A glob, by its table, its scope and its position among that scope's globs.
type GlobKey = (usize, u32, usize);

/// What each glob of the unit names, by [`GlobKey`]: the paths it names, or the refusal met reading it.
type GlobTargets = HashMap<GlobKey, Result<Vec<String>, String>>;

/// A memo key for [`CrateScopes::scope_lookup`]: the table and scope, the name, its namespace, the module it is seen
/// from, how many links deep the walk stands, since whether a lookup meets the chain cap depends on that depth, and
/// whether the lookup is the head of the binding the walk is reading, which reads the scope without that binding.
type LookupKey = (usize, u32, String, Namespace, String, usize, bool);

/// Every table of one compilation unit: what each module binds at module scope, what each declares,
/// and the edition a written path's root is read in. It resolves every binding — a `use` leaf, a
/// `pub use`, a glob and a `type` alias alike — from the scope it is written in when it is looked up,
/// never when it is recorded, and answers what a head names from a scope and what a crate-rooted path
/// names.
pub(super) struct CrateScopes {
    /// The scope table of each file of the unit, by the table position every key and lookup carries.
    pub(super) tables: Vec<ScopeTable>,
    /// The edition a written path's root is read in.
    edition: Edition,
    /// Whether the unit is a proc-macro crate, whose extern prelude holds `proc_macro` beside the sysroot crates.
    proc_macro: bool,
    /// The import names of the package's dependencies and of its own libraries: the crates a build of the unit can
    /// name besides the sysroot's, so the only ones a head no scope binds may be.
    dependencies: BTreeSet<String>,
    /// Every module scope of the unit, `(table, scope)`, by module path — a module declared twice
    /// under exclusive cfgs has one scope per declaration.
    pub(super) modules: BTreeMap<String, Vec<(usize, u32)>>,
    /// Every block, by its module's path followed by its [`block_segment`], so a path through a module
    /// declared in a block is read in the block that declares it.
    blocks: BTreeMap<String, (usize, u32)>,
    /// What each `extern crate` of the crate root binds: in scope in every module of the unit, after
    /// what the module's own scopes bind.
    extern_prelude: BTreeMap<String, Vec<Declared>>,
    /// The names an `extern crate` of the crate root no `cfg` gates binds, which the extern prelude answers for
    /// certain: `extern crate core as std;` leaves no sysroot `std` to read, while a gated one leaves the name open in
    /// every module, whatever else the root declares under it.
    certain_externs: BTreeSet<String>,
    /// What [`CrateScopes::name`] answered, by [`NameKey`].
    named: RefCell<HashMap<NameKey, Named>>,
    /// What [`CrateScopes::denotation`] read each path as, under the memo's own budget.
    denoted: RefCell<DenotationMemo>,
    /// What [`CrateScopes::scope_lookup`] answered, by [`LookupKey`], where no cycle was cut while answering.
    looked: RefCell<HashMap<LookupKey, Head>>,
    /// Whether each import names something in a namespace, by the import's table, scope, name, written path and
    /// namespace — a scope may import one name more than once, under exclusive cfgs — read once, since a chain of
    /// re-exports asks it of every link as each lookup through the chain passes.
    presence: RefCell<HashMap<PresenceKey, Presence>>,
    /// Every glob's targets once [`CrateScopes::glob_targets`] has read them to a fixed point.
    globs: RefCell<Option<GlobTargets>>,
    /// The reading of every glob's targets in progress while that fixed point is iterated, which a glob read during
    /// an iteration answers from.
    reading_globs: RefCell<Option<GlobTargets>>,
    /// The glob whose own path is being read while the fixed point is iterated, which names nothing meanwhile.
    reading_glob: RefCell<Option<GlobKey>>,
    /// Whether the glob being read was asked for while it named nothing.
    read_itself: std::cell::Cell<bool>,
    /// How many scopes have been read for a name, with no memo answering: the work a direction holding a reading's
    /// cost observes, which a clock would confound with every cost beside it.
    #[cfg(test)]
    scope_reads: std::cell::Cell<usize>,
}

impl CrateScopes {
    /// Whether the unit's extern prelude holds the sysroot crate `head` names.
    fn extern_prelude_holds(&self, head: &str) -> bool {
        match sysroot_crate(head) {
            Some(Sysroot::Prelude) => true,
            Some(Sysroot::ProcMacro) => self.proc_macro,
            Some(Sysroot::Test) | None => false,
        }
    }

    /// These scopes, read as a proc-macro crate's, whose extern prelude holds `proc_macro`.
    pub(super) fn in_a_proc_macro_crate(self) -> Self {
        CrateScopes {
            proc_macro: true,
            ..self
        }
    }

    /// The crate `head` followed by `rest`, where no scope binds `head`: a build where no item holds a head reads it from
    /// the extern prelude, which holds the sysroot crates and the package's dependencies alone, so a head that is
    /// neither names no crate in any build that compiles. The one reading of what such a head names, for a binding's
    /// target and a glob's alike.
    fn crate_named(&self, head: String, rest: &[String]) -> Option<String> {
        (self.dependencies.contains(&head) || self.extern_prelude_holds(&head))
            .then(|| with_rest(head, rest))
    }

    /// These scopes, in a package whose dependencies and libraries are imported as `dependencies`.
    pub(super) fn depending_on(self, dependencies: BTreeSet<String>) -> Self {
        CrateScopes {
            dependencies,
            ..self
        }
    }

    /// Hold `tables`, the unit's files, in their edition. Nothing is resolved here: a binding no
    /// resolution walks through is never read.
    pub(super) fn new(tables: Vec<ScopeTable>, edition: Edition) -> Self {
        let mut modules: BTreeMap<String, Vec<(usize, u32)>> = BTreeMap::new();
        let mut blocks: BTreeMap<String, (usize, u32)> = BTreeMap::new();
        let mut extern_prelude: BTreeMap<String, Vec<Declared>> = BTreeMap::new();
        let mut certain_externs = BTreeSet::new();
        for (t, table) in tables.iter().enumerate() {
            for (id, scope) in table.scopes.iter().enumerate() {
                let id = u32::try_from(id).expect("scope table exceeds u32");
                match scope.kind {
                    ScopeKind::Module => modules
                        .entry(scope.module.clone())
                        .or_default()
                        .push((t, id)),
                    ScopeKind::Block => {
                        blocks.insert(
                            format!("{}::{}", scope.module, block_segment(table.table, id)),
                            (t, id),
                        );
                    }
                }
                if scope.kind == ScopeKind::Module && scope.module == "crate" {
                    for (name, all) in &scope.declarations {
                        for declaration in all {
                            if let DeclKind::ExternCrate { target, gated } = &declaration.kind {
                                if !gated {
                                    certain_externs.insert(name.clone());
                                }
                                extern_prelude
                                    .entry(name.clone())
                                    .or_default()
                                    .push(extern_crate_names(target));
                            }
                        }
                    }
                }
            }
        }
        CrateScopes {
            tables,
            edition,
            proc_macro: false,
            dependencies: BTreeSet::new(),
            modules,
            blocks,
            extern_prelude,
            certain_externs,
            named: RefCell::default(),
            denoted: RefCell::default(),
            looked: RefCell::default(),
            presence: RefCell::default(),
            globs: RefCell::default(),
            reading_globs: RefCell::default(),
            reading_glob: RefCell::default(),
            read_itself: std::cell::Cell::default(),
            #[cfg(test)]
            scope_reads: std::cell::Cell::default(),
        }
    }

    /// The scope table of the unit's file at table position `t`.
    pub(super) fn table(&self, t: usize) -> &ScopeTable {
        &self.tables[t]
    }

    /// What `written`, standing in `scope` of table `t`, names through its head alone: the paths its head's bindings
    /// and declarations name, each with the rest of `written` after it, and no path carried further through what
    /// those name. What an import names, where a re-export the rest of its path runs through is not followed. A head a
    /// glob brings is bound as the glob's module followed by the head, whatever that module binds the head as.
    pub(super) fn head_names(
        &self,
        t: usize,
        scope: u32,
        written: &str,
        site: PathSite,
        ns: Namespace,
    ) -> Named {
        self.name_raw(
            t,
            scope,
            written,
            site,
            ns,
            &mut Vec::new(),
            &mut Walk::default(),
            true,
        )
    }

    /// What `written`, standing in `scope` of table `t`, names — its last segment read in `ns` — with
    /// every path carried through what a crate-rooted path names. Memoized by the scope and the path.
    pub(super) fn name(
        &self,
        t: usize,
        scope: u32,
        written: &str,
        site: PathSite,
        ns: Namespace,
    ) -> Named {
        let key = (t, scope, written.to_string(), site, ns);
        if let Some(named) = self.named.borrow().get(&key) {
            return named.clone();
        }
        let mut through = Vec::new();
        let named = match self.name_raw(
            t,
            scope,
            written,
            site,
            ns,
            &mut through,
            &mut Walk::default(),
            false,
        ) {
            Named::Paths(paths) => match self.denote_all(through, &paths, ns) {
                Err(refusal) => Named::PastCap(refusal),
                Ok(None) => Named::Local,
                Ok(Some(denoted)) => Named::Paths(denoted),
            },
            Named::Unbound { head, rest, also } if !also.is_empty() => {
                match self.denote_all(through, &also, ns) {
                    Err(refusal) => Named::PastCap(refusal),
                    Ok(denoted) => Named::Unbound {
                        head,
                        rest,
                        also: denoted.unwrap_or_default(),
                    },
                }
            }
            other => other,
        };
        self.named.borrow_mut().insert(key, named.clone());
        named
    }

    /// Every path `paths` name, each read through [`CrateScopes::denote`], beside `through`, the paths the reading
    /// passed: `None` where every path reached names a block's item, which no path outside its block names, and a
    /// refusal where any path's reading refused.
    fn denote_all(
        &self,
        through: Vec<String>,
        paths: &[String],
        ns: Namespace,
    ) -> Result<Option<Vec<String>>, String> {
        let mut denoted = through;
        let mut size = ReadingSize::default();
        for path in &denoted {
            size.add(path)?;
        }
        let mut past_cap = None;
        for path in paths {
            match self.denote(path, ns) {
                Ok(found) => {
                    for path in found {
                        if let Err(refusal) = size.add(&path) {
                            past_cap = least(past_cap, refusal);
                            break;
                        }
                        denoted.push(path);
                    }
                }
                Err(refusal) => past_cap = least(past_cap, refusal),
            }
        }
        if let Some(refusal) = past_cap {
            return Err(refusal);
        }
        let reached = !denoted.is_empty();
        denoted.retain(|path| !names_a_block_item(path));
        Ok((!reached || !denoted.is_empty()).then(|| sorted_unique(denoted)))
    }

    /// Every path the crate-rooted `path`, its last segment read in `ns`, names: each segment a module binds
    /// rather than declares is replaced by every path its bindings name there, to a fixed point, and a path
    /// through no such segment names itself. A path rooted anywhere else names itself. Memoized by the path
    /// and the namespace.
    pub(super) fn denote(&self, path: &str, ns: Namespace) -> Result<Vec<String>, String> {
        self.denotation(path, ns, true, None)
            .map(|denoted| sorted_unique(denoted.paths.iter().chain(&denoted.beside).cloned()))
    }

    /// The readable-only view used by directions comparing it with the finding and hazard views.
    #[cfg(test)]
    fn readable_paths(&self, path: &str, ns: Namespace) -> Result<Vec<String>, String> {
        self.denotation(path, ns, false, None)
            .map(|denoted| denoted.paths.clone())
    }

    /// What a hazard can traverse, together with whether a terminal foreign candidate reaches its prefix. Terminal
    /// candidates are compared once and never retained as paths or queued for another reading.
    pub(super) fn hazard_paths(
        &self,
        path: &str,
        ns: Namespace,
        prefix: &str,
        ancestors: bool,
    ) -> Result<(Vec<String>, bool), String> {
        self.denotation(path, ns, false, Some((prefix, ancestors)))
            .map(|denoted| (denoted.paths.clone(), denoted.terminal_reaches))
    }

    /// [`CrateScopes::denote_in`] from a fresh walk, memoized by the path, the namespace, whether candidates are
    /// requested and the hazard compared, a refusal included; a memo past its budget refuses the reading.
    fn denotation(
        &self,
        path: &str,
        ns: Namespace,
        candidates: bool,
        hazard: Option<(&str, bool)>,
    ) -> Result<Rc<Denoted>, String> {
        let key = (
            path.to_string(),
            ns,
            candidates,
            hazard.map(|(prefix, ancestors)| (prefix.to_string(), ancestors)),
        );
        if let Some(found) = self.denoted.borrow().get(&key) {
            return found.clone();
        }
        let found = self
            .denote_in(path, ns, &mut Walk::default(), candidates, hazard)
            .map(Rc::new);
        self.denoted.borrow_mut().insert(key, found.clone())?;
        found
    }

    /// What `written` names from `scope`, before a crate-rooted path is carried through what it names:
    /// the one resolution every binding, glob and occurrence goes through.
    #[allow(clippy::too_many_arguments)]
    fn name_raw(
        &self,
        t: usize,
        scope: u32,
        written: &str,
        site: PathSite,
        ns: Namespace,
        through: &mut Vec<String>,
        walk: &mut Walk,
        head_alone: bool,
    ) -> Named {
        let module = &self.tables[t].scopes[scope as usize].module;
        let mut named_by =
            |head: Head, head_name: String, rest: Vec<String>, from_root: bool| match head {
                Head::Candidates {
                    bound,
                    declared,
                    through: passed,
                    heads,
                    foreign,
                    open,
                } => {
                    let named: Vec<String> = if head_alone {
                        heads
                    } else {
                        through.extend(passed.into_iter().map(|p| with_rest(p, &rest)));
                        bound
                            .into_iter()
                            .map(|(path, _)| path)
                            .chain(declared.iter().map(|d| d.path().to_string()))
                            .collect()
                    }
                    .into_iter()
                    .chain(foreign.into_iter().filter(|_| from_root))
                    .map(|p| with_rest(p, &rest))
                    .collect();
                    match open {
                        false => Named::Paths(named),
                        true if self.extern_prelude_holds(&head_name) => Named::Paths(
                            named
                                .into_iter()
                                .chain([with_rest(head_name, &rest)])
                                .collect(),
                        ),
                        true => Named::Unbound {
                            head: head_name,
                            rest,
                            also: named,
                        },
                    }
                }
                Head::Foreign(paths) if from_root => {
                    Named::Paths(paths.into_iter().map(|p| with_rest(p, &rest)).collect())
                }
                Head::Local => Named::Local,
                Head::PastCap(refusal) => Named::PastCap(refusal),
                Head::Unbound | Head::Foreign(_) if self.extern_prelude_holds(&head_name) => {
                    Named::Paths(vec![with_rest(head_name, &rest)])
                }
                Head::Unbound if from_root => Named::External(with_rest(head_name, &rest)),
                Head::Unbound | Head::Foreign(_) => Named::Unbound {
                    head: head_name,
                    rest,
                    also: Vec::new(),
                },
            };
        let last_ns = |rest: &[String]| if rest.is_empty() { ns } else { Namespace::Type };
        match written_root(written, module, site, self.edition) {
            WrittenRoot::Crate(path) => Named::Paths(vec![path]),
            WrittenRoot::Extern { head, rest } => {
                let found = self.in_extern_prelude(&head, last_ns(&rest));
                named_by(found, head, rest, true)
            }
            WrittenRoot::FromCrateRoot { head, rest } => {
                let found = self.lookup_in_module("crate", &head, last_ns(&rest), "crate", walk);
                named_by(found, head, rest, true)
            }
            WrittenRoot::Bare { head, rest } => {
                let found = self.lookup(t, scope, &head, last_ns(&rest), walk);
                named_by(found, head, rest, false)
            }
            WrittenRoot::Invalid => Named::Invalid,
        }
    }

    /// What `head` names from `scope`: the answer of the nearest scope on the chain of blocks up to the
    /// nearest module scope that answers it, each read by [`CrateScopes::scope_lookup`], and else what an
    /// `extern crate` of the crate root binds it as. What only a glob of a crate whose contents are not read
    /// could bring is no answer here — a bare head may name a prelude or a local binding instead — so the
    /// chain walks on past it.
    ///
    /// A block whose only answer is an import of what is not read — `use std::fmt;` — may hold the name in the other
    /// namespace alone, as `std::fmt` names a module and no value, so rustc reads `fmt()` past it from the scope around
    /// the block. Its answer is kept and the chain walks on, the answers joined, so the call reports under what the
    /// outer scope binds it as: `use crate::forbidden::fmt; fn g() { use std::fmt; fmt(); }` calls
    /// `crate::forbidden::fmt`, measured against rustc 1.96.0, edition 2021. A block holding the name only by a
    /// `cfg`-gated item — an import, or an item of the block — walks on the same way, and a module scope of either kind
    /// joins the extern prelude's answer: both are [`CrateScopes::answer_ends_lookup`], the one judgement every lookup
    /// asks of a scope's answer. A name read in both namespaces is looked up in each to the end of its chain before the
    /// two are joined, so a block's `struct now {}`, a type alone, leaves a value `now` to the scope around the block.
    ///
    /// Where a scope the lookup walked past held the name only by a gated item, and the extern prelude does not answer
    /// it for certain, the answer is marked open: on a build that compiles that item out the head may name what no scope
    /// binds — a sysroot crate or a dependency — so `#[cfg(any())] mod std {}` leaves `std::process::id()` to `std`,
    /// while a crate root's ungated `extern crate core as std;` answers `std` as `core`.
    fn lookup(&self, t: usize, scope: u32, head: &str, ns: Namespace, walk: &mut Walk) -> Head {
        if ns == Namespace::Either {
            return joined(
                [Namespace::Type, Namespace::Value].map(|ns| self.lookup(t, scope, head, ns, walk)),
            );
        }
        let mut current = Some(scope);
        let mut unsettled = Vec::new();
        let mut gated = false;
        while let Some(id) = current {
            let entry = &self.tables[t].scopes[id as usize];
            match self.scope_lookup(t, id, head, ns, &entry.module, walk) {
                Head::Unbound | Head::Foreign(_) if entry.kind == ScopeKind::Block => {
                    current = entry.parent;
                }
                Head::Unbound | Head::Foreign(_) => break,
                answer if !self.answer_ends_lookup(&answer, t, id, head, ns, walk) => {
                    gated |= self.held_only_where_gated(t, id, head, ns);
                    unsettled.push(answer);
                    current = match entry.kind {
                        ScopeKind::Block => entry.parent,
                        ScopeKind::Module => None,
                    };
                }
                answer if unsettled.is_empty() => return answer,
                answer => return joined(unsettled.into_iter().chain([answer])),
            }
        }
        let prelude = self.in_extern_prelude(head, ns);
        let open = match prelude {
            Head::Candidates { .. } => !self.certain_externs.contains(head),
            _ => gated,
        };
        let mut answer = joined(unsettled.into_iter().chain([prelude]));
        if open {
            if let Head::Candidates { open, .. } = &mut answer {
                *open = true;
            } else if answer == Head::Local {
                answer = Head::Unbound;
            }
        }
        answer
    }

    /// Whether `answer`, what scope `id` gives for `head` in `ns`, ends a lookup there: every answer does except one
    /// naming what the scope binds or declares — its candidates, or an item of a block — where that may not hold on
    /// every build ([`CrateScopes::may_not_hold_here`]). The one place an answer's kind is asked, so where the lookup
    /// walks out of a block, where it reads the scope's own globs, and where a lookup through globs reaches the scope,
    /// one answer is read one way.
    fn answer_ends_lookup(
        &self,
        answer: &Head,
        t: usize,
        id: u32,
        head: &str,
        ns: Namespace,
        walk: &mut Walk,
    ) -> bool {
        !(matches!(answer, Head::Candidates { .. } | Head::Local)
            && self.may_not_hold_here(t, id, head, ns, walk))
    }

    /// Whether what scope `id` binds or declares `head` as in `ns` may not hold on every build, so the lookup reads on
    /// past it and joins what it finds: the scope holds the name only by items a `cfg` gates
    /// ([`CrateScopes::held_only_where_gated`]), or only through imports of what is not read
    /// ([`CrateScopes::binds_only_what_is_not_read`]). The one answer to whether a scope's answer ends a lookup, read
    /// alike where the lookup walks out of a block, where it reads a scope's own globs, and where a lookup through globs
    /// reaches the scope.
    fn may_not_hold_here(
        &self,
        t: usize,
        id: u32,
        head: &str,
        ns: Namespace,
        walk: &mut Walk,
    ) -> bool {
        self.held_only_where_gated(t, id, head, ns)
            || self.binds_only_what_is_not_read(t, id, head, ns, walk)
    }

    /// Whether scope `id` binds or declares `head` in `ns` only by items a `cfg` gates, so no binding or declaration
    /// of it there is compiled on every build.
    fn held_only_where_gated(&self, t: usize, id: u32, head: &str, ns: Namespace) -> bool {
        let entry = &self.tables[t].scopes[id as usize];
        let held = entry.ungated.get(head);
        (entry.bindings.contains_key(head) || entry.declarations.contains_key(head))
            && !held.is_some_and(|&(type_ns, value_ns)| match ns {
                Namespace::Type => type_ns,
                Namespace::Value => value_ns,
                Namespace::Either => type_ns || value_ns,
            })
    }

    /// Whether block `id` holds `head` in `ns` only through imports whose target is not read in `ns` — neither
    /// declared nor bound there, nor aliased, and every import of it of [`Presence::Unknown`] — so the block may not
    /// hold it in `ns` at all. [`Namespace::Either`] asks each namespace, and one that may not be held is enough.
    fn binds_only_what_is_not_read(
        &self,
        t: usize,
        id: u32,
        head: &str,
        ns: Namespace,
        walk: &mut Walk,
    ) -> bool {
        if ns == Namespace::Either {
            return [Namespace::Type, Namespace::Value]
                .into_iter()
                .any(|ns| self.binds_only_what_is_not_read(t, id, head, ns, walk));
        }
        let entry = &self.tables[t].scopes[id as usize];
        if entry
            .declarations
            .get(head)
            .is_some_and(|all| all.iter().any(|declaration| declaration.in_namespace(ns)))
        {
            return false;
        }
        let bindings = entry.bindings.get(head).map_or(&[][..], Vec::as_slice);
        !bindings.is_empty()
            && bindings.iter().all(|binding| match binding {
                Binding::Import { written, .. } => matches!(
                    self.import_presence(t, id, head, written, ns, walk),
                    Ok(Presence::Unknown)
                ),
                Binding::Alias { .. } => false,
            })
    }

    /// What the crate root's `extern crate` items bind `head` as — the names they add to every module's
    /// scope, a crate's root being a module or type — or [`Head::Unbound`].
    fn in_extern_prelude(&self, head: &str, ns: Namespace) -> Head {
        match self.extern_prelude.get(head) {
            Some(declared) if ns != Namespace::Value => Head::Candidates {
                bound: Vec::new(),
                heads: declared.iter().map(|d| d.path().to_string()).collect(),
                declared: declared.clone(),
                through: Vec::new(),
                foreign: Vec::new(),
                open: false,
            },
            _ => Head::Unbound,
        }
    }

    /// What `head` names in one scope, seen from module `from` — the one module-level lookup a bare head, a `use`
    /// path's first segment, every segment of a crate-rooted path and every glob go through. Every binding of it and
    /// every declaration of it in `ns` that `from` can see are its candidates, each declaration by what it
    /// declares — a module, the crate an `extern crate` names, or an item — and a block's item other than a module
    /// or an `extern crate` is [`Head::Local`], named by no path outside its block. Only where the scope binds and
    /// declares nothing are its globs read, each asking the module it names this same question seen from the
    /// module the glob is written in, so a glob brings each declaration and each binding its own visibility lets
    /// the glob's module see; [`CrateScopes::through_globs`] reads every scope that chain of globs reaches once, so a
    /// lookup that comes back to a scope — two modules globbing each other, neither binding the name — ends there. A
    /// binding holds its name in every namespace, and where there is none a lookup in
    /// [`Namespace::Either`] is the lookup in each namespace, joined. A binding
    /// the walk is already inside is passed over, so a cycle ends; the one the walk is reading now is passed over as
    /// the import resolved without itself, which is no cut, so a `use md5x::md5x;` names the crate and is kept.
    ///
    /// An answer is kept, by [`LookupKey`], only where no cycle was cut while answering, since a cut answer holds what
    /// one walk could read rather than what the scope names, and never past the chain cap, which is a refusal of the
    /// walk rather than an answer; that is what keeps a lattice of globs from being read once per path through it.
    fn scope_lookup(
        &self,
        t: usize,
        id: u32,
        head: &str,
        ns: Namespace,
        from: &str,
        walk: &mut Walk,
    ) -> Head {
        if ns == Namespace::Either {
            return joined(
                [Namespace::Type, Namespace::Value]
                    .map(|ns| self.scope_lookup(t, id, head, ns, from, walk)),
            );
        }
        let memo = (
            t,
            id,
            head.to_string(),
            ns,
            from.to_string(),
            walk.resolving.len(),
            walk.reads_itself(&(t, id, head.to_string())),
        );
        if let Some(head) = self.looked.borrow().get(&memo) {
            return head.clone();
        }
        let cuts = walk.cuts;
        let answer = self.scope_lookup_once(t, id, head, ns, from, walk);
        if walk.cuts == cuts && !matches!(answer, Head::PastCap(_)) {
            self.looked.borrow_mut().insert(memo, answer.clone());
        }
        answer
    }

    /// [`CrateScopes::scope_lookup`] for one namespace, read without the memo: what the scope binds or declares, and
    /// where it binds and declares nothing, what its globs bring, by [`CrateScopes::through_globs`]. A scope binding the
    /// name only through imports of what is not read — `use std::fmt;` — may not hold it in `ns`, as `std::fmt` names a
    /// module and no value, so rustc reads `fmt()` from the scope's globs; its globs are read too and the answers
    /// joined, so `use crate::forbidden::*; use std::fmt;` then `fmt()` calls `crate::forbidden::fmt`, measured against
    /// rustc 1.96.0, edition 2021. Where such an import does hold the name, the glob's answer is an over-reaction,
    /// the declared bound
    /// `inline-symbol-path-confinement/an-import-of-what-is-not-read-beside-a-glob-is-read-with-the-glob-a-stated-bound`.
    /// A scope binding or declaring the name only by what a `cfg` gates has its globs read too and the answers joined,
    /// since on a build that compiles the gated item out the glob names it: `use super::*;` beside
    /// `#[cfg(test)] use crate::mock::Command;` calls the `Command` the glob brings outside tests, measured against
    /// rustc 1.96.0, edition 2021. On a build that compiles it in, the glob's answer is an over-reaction, the declared
    /// bound `inline-symbol-path-confinement/a-cfg-gated-name-beside-a-glob-is-read-with-the-glob-a-stated-bound`.
    fn scope_lookup_once(
        &self,
        t: usize,
        id: u32,
        head: &str,
        ns: Namespace,
        from: &str,
        walk: &mut Walk,
    ) -> Head {
        #[cfg(test)]
        self.scope_reads.set(self.scope_reads.get() + 1);
        match self.bound_here(t, id, head, ns, from, walk) {
            Some(answer)
                if !self.tables[t].scopes[id as usize].globs.is_empty()
                    && !self.answer_ends_lookup(&answer, t, id, head, ns, walk) =>
            {
                match self.through_globs(t, id, head, ns, from, walk) {
                    Head::Unbound => answer,
                    globbed => joined([answer, globbed]),
                }
            }
            Some(answer) => answer,
            None => self.through_globs(t, id, head, ns, from, walk),
        }
    }

    /// What one scope binds or declares `head` as in `ns`, seen from `from`, or `None` where it binds and declares
    /// nothing `from` can see, which leaves the name to the scope's globs.
    ///
    /// The one lookup that reads a scope's own bindings, so it is where a scope of a file holding what the scanner could
    /// not read — a `use` tree, or a block's module it could not name — is refused rather than read: the bindings that
    /// tree makes, or the declaration of that module, are missing from it, and an answer read without them could name
    /// less than rustc does. A lookup that reaches such a scope — directly, or through a glob
    /// into it — refuses, whichever query asked it, while one that never reads it is judged. The glob hazard also walks a
    /// scope's bindings, outside any lookup; it meets the same refusal before it runs, since `UnitScan::findings` refuses
    /// a unit any of whose tables holds one.
    fn bound_here(
        &self,
        t: usize,
        id: u32,
        head: &str,
        ns: Namespace,
        from: &str,
        walk: &mut Walk,
    ) -> Option<Head> {
        let entry = &self.tables[t].scopes[id as usize];
        if let Some(refusal) = self.tables[t].refusal() {
            return Some(Head::PastCap(format!(
                "it reads names through `{}`, whose file holds what the scanner cannot read: {refusal}",
                entry.module
            )));
        }
        let visible = |visibility: &Visibility| visibility.visible_from(&entry.module, from);
        let key = (t, id, head.to_string());
        let mut bindings: Vec<&Binding> = Vec::new();
        if !walk.reads_itself(&key) && !walk.meets_cycle(&key) {
            for binding in entry.bindings.get(head).into_iter().flatten() {
                if !visible(binding.visibility()) {
                    continue;
                }
                match self.binding_holds(t, id, head, binding, ns, walk) {
                    Ok(true) => bindings.push(binding),
                    Ok(false) => {}
                    Err(refusal) => return Some(Head::PastCap(refusal)),
                }
            }
        }
        let declarations: Vec<&Declaration> = entry
            .declarations
            .get(head)
            .into_iter()
            .flatten()
            .filter(|declaration| declaration.in_namespace(ns) && visible(&declaration.visibility))
            .collect();
        if !bindings.is_empty() || !declarations.is_empty() {
            let (mut bound, mut declared, mut through): (Vec<Bound>, Vec<Declared>, Vec<String>) =
                (Vec::new(), Vec::new(), Vec::new());
            let mut names_a_local_item = false;
            for binding in bindings {
                match self.binding_names(t, id, head, binding, ns, walk) {
                    BindingNames::Paths(found, passed) => {
                        let quote = binding_quote(head, binding);
                        bound.extend(found.into_iter().map(|path| (path, quote.clone())));
                        through.extend(passed);
                    }
                    BindingNames::Local => names_a_local_item = true,
                    BindingNames::PastCap(refusal) => return Some(Head::PastCap(refusal)),
                }
            }
            for declaration in declarations {
                match (&declaration.kind, entry.kind) {
                    (DeclKind::Module(path), _) => declared.push(Declared::Module(path.clone())),
                    (DeclKind::ExternCrate { target, .. }, _) => {
                        declared.push(extern_crate_names(target))
                    }
                    (DeclKind::Item(_), ScopeKind::Module) => {
                        declared.push(Declared::Item(format!("{}::{head}", entry.module)));
                    }
                    (DeclKind::Item(_), ScopeKind::Block) => names_a_local_item = true,
                }
            }
            if bound.is_empty() && declared.is_empty() && names_a_local_item {
                return Some(Head::Local);
            }
            declared.sort();
            declared.dedup();
            let heads = bound
                .iter()
                .map(|(path, _)| path.clone())
                .chain(declared.iter().map(|d| d.path().to_string()))
                .collect();
            return Some(Head::Candidates {
                bound,
                declared,
                through,
                heads,
                foreign: Vec::new(),
                open: false,
            });
        }
        None
    }

    /// What the globs of a scope that binds and declares nothing under `head` bring it as, seen from `from`: a glob's
    /// module is read seen from the module the glob is written in, which binds or declares the name or reads its own
    /// globs in turn. Every scope those globs reach, and what each binds, is read once into one graph, and the
    /// answers of the scopes that read their globs are then read to a fixed point, starting from none and in the order
    /// a scope's answer is needed by the one that reaches it, until a reading changes nothing. So two modules globbing
    /// each other end, and a graph of globs is read in time its size bounds rather than once per path through it.
    ///
    /// A glob of an item of this crate rather than a module — `use crate::a::E::*;` bringing an enum's variants — has
    /// no scope to read, so its names are those of a crate whose contents are not read. A scope's answers are kept,
    /// where no cycle was cut while reading what the scopes bind, since each is then the scope's own answer.
    fn through_globs(
        &self,
        t: usize,
        id: u32,
        head: &str,
        ns: Namespace,
        from: &str,
        walk: &mut Walk,
    ) -> Head {
        let cuts = walk.cuts;
        let depth = walk.resolving.len();
        let mut graph = GlobGraph::default();
        let start = graph.node(t, id, from);
        let mut next = 0;
        while next < graph.nodes.len() {
            let (t, id, from) = graph.nodes[next].clone();
            next += 1;
            let reading = if next - 1 == start {
                self.glob_edges(&mut graph, t, id, head, &from)
            } else {
                let itself = walk.reads_itself(&(t, id, head.to_string()));
                let memo = (t, id, head.to_string(), ns, from.clone(), depth, itself);
                let held = self.looked.borrow().get(&memo).cloned();
                match held.or_else(|| self.bound_here(t, id, head, ns, &from, walk)) {
                    Some(answer) if !self.answer_ends_lookup(&answer, t, id, head, ns, walk) => {
                        match self.glob_edges(&mut graph, t, id, head, &from) {
                            GlobRead::Globs { edges, .. } => GlobRead::Globs {
                                own: Some(answer),
                                edges,
                            },
                            refused => refused,
                        }
                    }
                    Some(answer) => GlobRead::Answered(answer),
                    None => self.glob_edges(&mut graph, t, id, head, &from),
                }
            };
            graph.reads.push(reading);
        }
        let answers = match graph.settle(head) {
            Ok(answers) => answers,
            Err(refusal) => return Head::PastCap(refusal),
        };
        if walk.cuts == cuts {
            let mut looked = self.looked.borrow_mut();
            for (n, (t, id, from)) in graph.nodes.iter().enumerate() {
                if n != start
                    && matches!(graph.reads[n], GlobRead::Globs { .. })
                    && !matches!(answers[n], Head::PastCap(_))
                {
                    let itself = walk.reads_itself(&(*t, *id, head.to_string()));
                    looked.insert(
                        (*t, *id, head.to_string(), ns, from.clone(), depth, itself),
                        answers[n].clone(),
                    );
                }
            }
        }
        answers[start].clone()
    }

    /// The globs of one scope that binds and declares nothing under `head`, seen from `from`, as edges of `graph`: a
    /// glob of a module of the unit is an edge to each of that module's scopes, seen from this scope's module, and any
    /// other glob names what a crate whose contents are not read brings.
    fn glob_edges(
        &self,
        graph: &mut GlobGraph,
        t: usize,
        id: u32,
        head: &str,
        from: &str,
    ) -> GlobRead {
        let entry = &self.tables[t].scopes[id as usize];
        let mut edges = Vec::new();
        let mut size = ReadingSize::default();
        for (i, glob) in entry.globs.iter().enumerate() {
            if !glob.visibility.visible_from(&entry.module, from) {
                continue;
            }
            let targets = match self.glob_targets(t, id, i) {
                Ok(targets) => targets,
                Err(refusal) => return GlobRead::Answered(Head::PastCap(refusal)),
            };
            for target in targets {
                if let Err(refusal) = size.add(&target) {
                    return GlobRead::Answered(Head::PastCap(refusal));
                }
                let scopes = path_within(&target, "crate")
                    .then(|| self.modules.get(&target))
                    .flatten();
                if let Some(scopes) = scopes {
                    let into = scopes
                        .iter()
                        .map(|&(t, s)| graph.node(t, s, &entry.module))
                        .collect();
                    edges.push(GlobEdge::Into {
                        quote: format!("use {}::*", glob.written),
                        target,
                        into,
                    });
                } else {
                    edges.push(GlobEdge::Foreign(format!("{target}::{head}")));
                }
            }
        }
        GlobRead::Globs { own: None, edges }
    }

    /// [`CrateScopes::scope_lookup`] in every scope of `module`, seen from `from`, their answers joined.
    fn lookup_in_module(
        &self,
        module: &str,
        head: &str,
        ns: Namespace,
        from: &str,
        walk: &mut Walk,
    ) -> Head {
        let scopes = match self.blocks.get(module) {
            Some(block) => std::slice::from_ref(block),
            None => self.modules.get(module).map_or(&[][..], Vec::as_slice),
        };
        joined(
            scopes
                .iter()
                .map(|&(t, s)| self.scope_lookup(t, s, head, ns, from, walk))
                .collect::<Vec<_>>(),
        )
    }

    /// Whether `binding` holds `name` in `ns`: a `type` alias names a type, and so does a `{self}` leaf, which imports
    /// its group's module alone; any other import holds each namespace its target
    /// names something in, and every namespace where its target names nothing in either — an item a macro generates,
    /// whose namespaces are not read — so only a target known in the other namespace and absent in this one leaves
    /// this one to the scope's globs. The one namespace filter a declaration also answers, [`Namespace`], read for a
    /// binding from what its target is.
    fn binding_holds(
        &self,
        t: usize,
        scope: u32,
        name: &str,
        binding: &Binding,
        ns: Namespace,
        walk: &mut Walk,
    ) -> Result<bool, String> {
        let Binding::Import {
            written,
            module_only,
            ..
        } = binding
        else {
            return Ok(ns != Namespace::Value);
        };
        if *module_only {
            return Ok(ns != Namespace::Value);
        }
        if self.import_presence(t, scope, name, written, ns, walk)? != Presence::Absent {
            return Ok(true);
        }
        Ok(self.import_presence(t, scope, name, written, ns.other(), walk)? == Presence::Absent)
    }

    /// Whether the import `written`, binding `name` in `scope`, names something in `ns`, read inside the walk so a
    /// cycle of imports ends as the resolution it is part of does. It is remembered only where no cycle was ended while
    /// it was read, since what a read past a cut cycle finds depends on the walk it was read in.
    fn import_presence(
        &self,
        t: usize,
        scope: u32,
        name: &str,
        written: &str,
        ns: Namespace,
        walk: &mut Walk,
    ) -> Result<Presence, String> {
        let key = (t, scope, name.to_string(), written.to_string(), ns);
        if let Some(presence) = self.presence.borrow().get(&key) {
            return Ok(*presence);
        }
        let module = &self.tables[t].scopes[scope as usize].module;
        let cuts = walk.cuts;
        walk.enter(
            (t, scope, name.to_string()),
            format!("use {written}"),
            module,
        )?;
        let presence = match self.name_raw(
            t,
            scope,
            written,
            PathSite::Use,
            ns,
            &mut Vec::new(),
            walk,
            false,
        ) {
            Named::Paths(paths) => paths.iter().try_fold(Presence::Absent, |most, path| {
                let presence = if path_within(path, "crate") {
                    self.denote_in(path, ns, walk, false, None)
                        .map(|denoted| denoted.presence)
                } else {
                    Ok(Presence::Unknown)
                };
                presence.map(|presence| most.max(presence))
            }),
            Named::External(_) | Named::Unbound { .. } => Ok(Presence::Unknown),
            Named::Local => Ok(Presence::Known),
            Named::Invalid => Ok(Presence::Absent),
            Named::PastCap(refusal) => Err(refusal),
        };
        walk.leave();
        if let (Ok(presence), true) = (&presence, walk.cuts == cuts) {
            self.presence.borrow_mut().insert(key, *presence);
        }
        presence
    }

    /// The paths one binding names in `ns`, read from its own scope as a `use` path or as a `type` alias's
    /// target. A head no scope binds names the extern-prelude crate of that name, for either.
    pub(super) fn binding_names(
        &self,
        t: usize,
        scope: u32,
        name: &str,
        binding: &Binding,
        ns: Namespace,
        walk: &mut Walk,
    ) -> BindingNames {
        let (written, site, ns, quote) = match binding {
            Binding::Import { written, .. } => {
                (written, PathSite::Use, ns, format!("use {written}"))
            }
            Binding::Alias { written, .. } => (
                written,
                PathSite::Expr,
                Namespace::Type,
                format!("type {name} = {written}"),
            ),
        };
        let module = &self.tables[t].scopes[scope as usize].module;
        if let Err(refusal) = walk.enter((t, scope, name.to_string()), quote, module) {
            return BindingNames::PastCap(refusal);
        }
        let mut through = Vec::new();
        let named = self.name_raw(t, scope, written, site, ns, &mut through, walk, false);
        walk.leave();
        match named {
            Named::Paths(paths) => BindingNames::Paths(paths, through),
            Named::External(path) => BindingNames::Paths(vec![path], through),
            Named::Unbound { head, rest, also } => BindingNames::Paths(
                self.crate_named(head, &rest)
                    .into_iter()
                    .chain(also)
                    .collect(),
                through,
            ),
            Named::Local => BindingNames::Local,
            Named::Invalid => BindingNames::Paths(Vec::new(), through),
            Named::PastCap(refusal) => BindingNames::PastCap(refusal),
        }
    }

    /// Every path glob `i` of `scope` names, read from that scope as a `use` path, each crate-rooted one carried
    /// through what it names.
    ///
    /// A glob's own path may be read through another glob of the unit, and that one through the first, so every glob
    /// of the unit is read together, to a fixed point, in passes starting from none. A glob's own path is never read
    /// through the glob itself, which names nothing while it is read, as rustc never resolves a glob through what it
    /// imports. Each glob is read with every remembered answer forgotten first, so it is read from the current readings of
    /// the others — those the globs before it in the same pass have just been read as — and never through itself; the
    /// passes read the unit's globs in turn forwards and backwards, so a chain of globs each read through one written
    /// before or after it settles within a few passes. A pass that changes nothing ends the reading, and every answer
    /// it read is from the settled readings.
    /// Passes are bounded by [`MAX_RESOLUTION_CHAIN`] or twice the unit's globs plus two, whichever is more, past which
    /// every glob is refused, since a source whose globs name each other's names without settling is one the scanner
    /// cannot judge.
    pub(super) fn glob_targets(
        &self,
        t: usize,
        scope: u32,
        i: usize,
    ) -> Result<Vec<String>, String> {
        let key = (t, scope, i);
        if let Some(all) = self.globs.borrow().as_ref() {
            return all.get(&key).cloned().unwrap_or_else(|| Ok(Vec::new()));
        }
        if self.reading_globs.borrow().is_some() {
            if *self.reading_glob.borrow() == Some(key) {
                self.read_itself.set(true);
                return Ok(Vec::new());
            }
            return self.last_read(key);
        }
        let every: Vec<GlobKey> = self
            .tables
            .iter()
            .enumerate()
            .flat_map(|(t, table)| {
                table
                    .scopes
                    .iter()
                    .enumerate()
                    .flat_map(move |(id, entry)| {
                        let id = u32::try_from(id).expect("scope table exceeds u32");
                        (0..entry.globs.len()).map(move |i| (t, id, i))
                    })
            })
            .collect();
        *self.reading_globs.borrow_mut() = Some(GlobTargets::new());
        let passes = MAX_RESOLUTION_CHAIN.max(2 * (every.len() + 1));
        let mut settled = false;
        for pass in 0..passes {
            let mut changed = false;
            let order: Box<dyn Iterator<Item = &GlobKey>> = if pass % 2 == 0 {
                Box::new(every.iter())
            } else {
                Box::new(every.iter().rev())
            };
            for &glob in order {
                changed |= self.read_in_pass(glob);
            }
            if !changed {
                settled = true;
                break;
            }
        }
        let read = self
            .reading_globs
            .borrow_mut()
            .take()
            .expect("the glob readings are set before the passes");
        let all: GlobTargets = if settled {
            read
        } else {
            let refusal = format!(
                "cannot judge a compilation unit whose globs do not settle on what they name within {passes} passes"
            );
            every
                .iter()
                .map(|&key| (key, Err(refusal.clone())))
                .collect()
        };
        self.forget_readings();
        let found = all.get(&key).cloned().unwrap_or_else(|| Ok(Vec::new()));
        *self.globs.borrow_mut() = Some(all);
        found
    }

    /// What glob `key` was last read as while the fixed point is iterated: nothing before its first reading.
    fn last_read(&self, key: GlobKey) -> Result<Vec<String>, String> {
        self.reading_globs
            .borrow()
            .as_ref()
            .and_then(|all| all.get(&key).cloned())
            .unwrap_or_else(|| Ok(Vec::new()))
    }

    /// Read glob `key` once in the current pass, with the glob itself naming nothing while its own path is read, and
    /// keep what it is read as; whether that changed. Every answer remembered before the read is forgotten first, since
    /// one remembered while this glob still answered its last reading would read the glob through itself; and answers
    /// read while the glob named nothing are forgotten after it, since they hold less than the glob brings to any
    /// other reader.
    fn read_in_pass(&self, key: GlobKey) -> bool {
        self.forget_readings();
        *self.reading_glob.borrow_mut() = Some(key);
        self.read_itself.set(false);
        let reading = self.read_glob(key.0, key.1, key.2).and_then(|paths| {
            let mut size = ReadingSize::default();
            for path in &paths {
                size.add(path)?;
            }
            Ok(paths)
        });
        *self.reading_glob.borrow_mut() = None;
        if self.read_itself.get() {
            self.forget_readings();
        }
        if reading == self.last_read(key) {
            return false;
        }
        if let Some(all) = self.reading_globs.borrow_mut().as_mut() {
            all.insert(key, reading);
        }
        true
    }

    /// Drop every answer read while the globs' targets were still being read, since each may hold a reading of them
    /// the fixed point has since changed.
    fn forget_readings(&self) {
        self.named.borrow_mut().clear();
        self.denoted.borrow_mut().clear();
        self.looked.borrow_mut().clear();
        self.presence.borrow_mut().clear();
    }

    /// One reading of glob `i` of `scope`, each glob its path passes answered from the reading in progress. A path whose
    /// head no scope binds names a crate only as [`CrateScopes::crate_named`] reads it, so
    /// `#[cfg(unix)] mod m1; pub use m1::*;` names `m1` and no crate, and two such globs each read through the other's
    /// settle rather than naming `m1::m2::m1…` without end.
    fn read_glob(&self, t: usize, scope: u32, i: usize) -> Result<Vec<String>, String> {
        let entry = &self.tables[t].scopes[scope as usize];
        let written = &entry.globs[i].written;
        let mut walk = Walk::default();
        walk.enter(
            (t, scope, format!("*{i}")),
            format!("use {written}::*"),
            &entry.module,
        )?;
        let named = self.name_raw(
            t,
            scope,
            written,
            PathSite::Use,
            Namespace::Type,
            &mut Vec::new(),
            &mut walk,
            false,
        );
        match named {
            Named::Paths(paths) => self.read_glob_paths(&paths, Vec::new(), &mut walk),
            Named::External(path) => Ok(vec![path]),
            Named::Unbound { head, rest, also } => self.read_glob_paths(
                &also,
                self.crate_named(head, &rest).into_iter().collect(),
                &mut walk,
            ),
            Named::Local | Named::Invalid => Ok(Vec::new()),
            Named::PastCap(refusal) => Err(refusal),
        }
    }

    /// `found` followed by every readable path each of `paths` names in the type namespace inside `walk`, all charged
    /// against one width budget; what a foreign glob brings is not among them.
    fn read_glob_paths(
        &self,
        paths: &[String],
        mut found: Vec<String>,
        walk: &mut Walk,
    ) -> Result<Vec<String>, String> {
        let mut size = ReadingSize::default();
        for path in &found {
            size.add(path)?;
        }
        for path in paths {
            for path in self
                .denote_in(path, Namespace::Type, walk, false, None)?
                .paths
            {
                size.add(&path)?;
                found.push(path);
            }
        }
        Ok(found)
    }

    /// [`CrateScopes::denote`] inside a walk. The path is read segment by segment from the crate root, each
    /// segment looked up — in the type namespace, the last in `ns` — in the module the segments before it
    /// reached, by [`CrateScopes::lookup_in_module`], the lookup a head written in that module gets. A declared
    /// module, or the crate an `extern crate self` names, is walked into; a declared item, or the root of a crate
    /// whose contents are not read, names itself with the rest of the path after it; a segment the module binds —
    /// through an import, a `type` alias or a glob — is replaced by every path the binding names and read again
    /// from the root; and a segment only a glob of a crate whose contents are not read can bring names that
    /// glob's path. A segment the module neither binds nor declares names itself. A branch that replaces more
    /// than [`MAX_RESOLUTION_CHAIN`] segments is refused, quoting the binding it started from.
    ///
    /// A file-form module a block declares is its own file's module, named through the block's readable form rather
    /// than a block scope, so a readable block segment is read together with the module name after it.
    fn denote_in(
        &self,
        path: &str,
        ns: Namespace,
        walk: &mut Walk,
        candidates: bool,
        hazard: Option<(&str, bool)>,
    ) -> Result<Denoted, String> {
        ReadingSize::default().add(path)?;
        let Some(rest) = crate_rooted(path) else {
            return Ok(Denoted {
                paths: vec![path.to_string()],
                beside: Vec::new(),
                presence: Presence::Unknown,
                terminal_reaches: false,
            });
        };
        let mut reading = Reading::new(rest, candidates, hazard);
        while let Some((module, rest, chain)) = reading.next()? {
            self.read_branch(&mut reading, module, &rest, chain, ns, walk)?;
        }
        Ok(reading.denoted())
    }

    /// One branch of a [`CrateScopes::denote_in`] reading: `rest` read from `module`, which `chain` reached. No
    /// segment left names the module; a block segment steps into the block, or into the file-form module it
    /// declares; and any other segment is looked up in `module` and its answer read by one arm each.
    fn read_branch(
        &self,
        reading: &mut Reading,
        module: String,
        rest: &[String],
        chain: Vec<Link>,
        ns: Namespace,
        walk: &mut Walk,
    ) -> Result<(), String> {
        let Some((segment, after)) = rest.split_first() else {
            reading.find(module)?;
            reading.raise(Presence::Known);
            return Ok(());
        };
        let here = format!("{module}::{segment}");
        if is_block_segment(segment) {
            if let Some((name, beyond)) = after.split_first() {
                let file_module = format!("{here}::{name}");
                if !self.blocks.contains_key(&here) && self.modules.contains_key(&file_module) {
                    reading.step(file_module, beyond.to_vec(), chain);
                    return Ok(());
                }
            }
            reading.step(here, after.to_vec(), chain);
            return Ok(());
        }
        let segment_ns = if after.is_empty() {
            ns
        } else {
            Namespace::Type
        };
        match self.lookup_in_module(&module, segment, segment_ns, &module, walk) {
            Head::Candidates {
                bound,
                declared,
                through,
                foreign,
                ..
            } => {
                for path in through {
                    reading.find(with_rest(path, after))?;
                }
                if !foreign.is_empty() {
                    reading.terminal(foreign, after)?;
                    reading.raise(Presence::Unknown);
                }
                for declaration in declared {
                    match declaration {
                        Declared::Module(inner) if !after.is_empty() => {
                            reading.branch(inner, after.to_vec(), chain.clone())?;
                        }
                        Declared::Module(path) | Declared::Item(path) => {
                            reading.find(with_rest(path, after))?;
                            reading.raise(Presence::Known);
                        }
                    }
                }
                if !bound.is_empty() {
                    reading.follow_bound(&module, segment, after, chain, bound, walk)?;
                }
            }
            Head::Foreign(paths) => {
                reading.find(with_rest(here, after))?;
                reading.terminal(paths, after)?;
                reading.raise(Presence::Unknown);
            }
            Head::PastCap(refusal) => return Err(refusal),
            Head::Local => {
                reading.find(with_rest(here, after))?;
                reading.raise(Presence::Known);
            }
            Head::Unbound => {
                reading.find(with_rest(here, after))?;
                if !after.is_empty() || self.may_generate_items(&module) {
                    reading.raise(Presence::Unknown);
                }
            }
        }
        Ok(())
    }

    /// Whether a scope of `module` holds a macro invocation where an item can stand, which may generate an item the
    /// scanner does not read: a name its module declares in neither namespace is then unknown there, not absent.
    fn may_generate_items(&self, module: &str) -> bool {
        self.modules
            .get(module)
            .into_iter()
            .flatten()
            .any(|&(t, s)| self.tables[t].scopes[s as usize].macro_items)
    }
}

/// The segments after `crate` of a crate-rooted path, or `None` for a path rooted anywhere else.
fn crate_rooted(path: &str) -> Option<Vec<String>> {
    if path == "crate" {
        return Some(Vec::new());
    }
    path.strip_prefix("crate::")
        .map(|rest| rest.split("::").map(str::to_string).collect())
}

/// A branch of a [`CrateScopes::denote_in`] reading still to read: the module reached, the segments after it, and
/// the chain of bindings followed to reach it.
type Branch = (String, Vec<String>, Vec<Link>);

/// What a [`CrateScopes::denote_in`] reading holds while it reads, and the one place its width budget is charged:
/// a branch as it is taken up, a path as it is found, a branch as it is pushed, and a foreign candidate as it is
/// projected. A step of the reading names what it found or what to read next, and never charges the budget itself.
struct Reading<'h> {
    /// The branches still to read, the one pushed last taken up first.
    work: Vec<Branch>,
    /// Every module and remaining segments already taken up, so a branch reached twice is read once.
    seen: BTreeSet<(String, Vec<String>)>,
    /// Every path the reading named, sorted and deduplicated only when the reading ends.
    found: Vec<String>,
    /// What foreign globs bring a segment as, held only where candidates are requested.
    beside: Vec<String>,
    /// The most any branch has said about whether the path names something in its namespace.
    presence: Presence,
    /// Whether a foreign candidate lies within the hazard's prefix or, where ancestors are compared, is one of its
    /// ancestors.
    terminal_reaches: bool,
    /// Everything the reading has charged against the width budget: what it holds and what it took up.
    size: ReadingSize,
    /// Whether foreign candidates are kept in `beside` as candidates of what the path names.
    candidates: bool,
    /// The prefix a hazard compares foreign candidates with, and whether its ancestors are compared too; `None`
    /// outside a hazard reading.
    hazard: Option<(&'h str, bool)>,
}

impl<'h> Reading<'h> {
    /// A reading of the crate-rooted path whose segments after `crate` are `rest`.
    fn new(rest: Vec<String>, candidates: bool, hazard: Option<(&'h str, bool)>) -> Self {
        Reading {
            work: vec![("crate".to_string(), rest, Vec::new())],
            seen: BTreeSet::new(),
            found: Vec::new(),
            beside: Vec::new(),
            presence: Presence::Absent,
            terminal_reaches: false,
            size: ReadingSize::default(),
            candidates,
            hazard,
        }
    }

    /// The next branch not read before. Every branch taken up is charged, one already read too, and the reading is
    /// refused once what it holds and what it has still to read pass the width budget together.
    fn next(&mut self) -> Result<Option<Branch>, String> {
        while let Some((module, rest, chain)) = self.work.pop() {
            self.size.add(&module)?;
            self.size.bytes = self
                .size
                .bytes
                .saturating_add(rest.iter().map(String::len).sum::<usize>());
            self.size.check()?;
            if self.size.paths.saturating_add(self.work.len()) > MAX_RESOLUTION_PATHS {
                return Err(width_refusal());
            }
            if self.seen.insert((module.clone(), rest.clone())) {
                return Ok(Some((module, rest, chain)));
            }
        }
        Ok(None)
    }

    /// A path the reading names.
    fn find(&mut self, path: String) -> Result<(), String> {
        self.size.add(&path)?;
        self.found.push(path);
        Ok(())
    }

    /// A branch to read, charged as the path it denotes.
    fn branch(
        &mut self,
        module: String,
        rest: Vec<String>,
        chain: Vec<Link>,
    ) -> Result<(), String> {
        self.size.add(&with_rest(module.clone(), &rest))?;
        self.work.push((module, rest, chain));
        Ok(())
    }

    /// A branch spelling the same path through a block, which holds no text the branch it came from did not.
    fn step(&mut self, module: String, rest: Vec<String>, chain: Vec<Link>) {
        self.work.push((module, rest, chain));
    }

    /// Raise the presence reported to `presence` where it says more; it never falls, so the answer over every
    /// branch is their maximum.
    fn raise(&mut self, presence: Presence) {
        self.presence = self.presence.max(presence);
    }

    /// Project foreign names to the requested consumer: findings keep them; a hazard compares them without reading
    /// through them; a presence reading needs only the caller's Unknown contribution.
    fn terminal(&mut self, paths: Vec<String>, after: &[String]) -> Result<(), String> {
        if !self.candidates && self.hazard.is_none() {
            return Ok(());
        }
        for path in paths {
            let path = with_rest(path, after);
            self.size.add(&path)?;
            if let Some((prefix, ancestors)) = self.hazard {
                self.terminal_reaches |=
                    path_within(&path, prefix) || (ancestors && path_within(prefix, &path));
            }
            if self.candidates {
                self.beside.push(path);
            }
        }
        Ok(())
    }

    /// The segment `segment` of `module`, which the module binds to each of `bound`: the segment's own path is
    /// found, and each binding's target with `after` is read again from the root, the chain extended by the
    /// binding — or, rooted outside the crate, found. A binding the chain already followed is a cycle and ends the
    /// branch, unknown; a chain of [`MAX_RESOLUTION_CHAIN`] links is refused, quoting the binding it started from.
    /// A target rooted outside the crate is charged as the target it was read as and again as the path found.
    fn follow_bound(
        &mut self,
        module: &str,
        segment: &str,
        after: &[String],
        chain: Vec<Link>,
        bound: Vec<Bound>,
        walk: &mut Walk,
    ) -> Result<(), String> {
        self.find(with_rest(format!("{module}::{segment}"), after))?;
        if chain
            .iter()
            .any(|(m, name, _)| m == module && name == segment)
        {
            walk.cuts += 1;
            self.raise(Presence::Unknown);
            return Ok(());
        }
        if chain.len() >= MAX_RESOLUTION_CHAIN {
            return Err(chain_refusal(&chain[0].2, &chain[0].0));
        }
        for (target, quote) in bound {
            let target = with_rest(target, after);
            match crate_rooted(&target) {
                Some(rest) => {
                    let mut chain = chain.clone();
                    chain.push((module.to_string(), segment.to_string(), quote));
                    self.branch("crate".to_string(), rest, chain)?;
                }
                None => {
                    self.size.add(&target)?;
                    self.find(target)?;
                    self.raise(Presence::Unknown);
                }
            }
        }
        Ok(())
    }

    /// The reading's answer: what it found and what foreign globs brought, each sorted and deduplicated, with the
    /// most any branch said about presence.
    fn denoted(self) -> Denoted {
        Denoted {
            paths: sorted_unique(self.found),
            beside: sorted_unique(self.beside),
            presence: self.presence,
            terminal_reaches: self.terminal_reaches,
        }
    }
}

/// How `binding`, binding `name`, is written, for a refusal of a chain through it to quote.
fn binding_quote(name: &str, binding: &Binding) -> String {
    match binding {
        Binding::Import { written, .. } => format!("use {written}"),
        Binding::Alias { written, .. } => format!("type {name} = {written}"),
    }
}

/// One link of a chain [`CrateScopes::denote`] follows: a module, the name in it whose binding replaced a segment,
/// and how that binding is written. A branch that meets the same module and name twice is a cycle.
type Link = (String, String, String);

/// Several answers to one lookup, joined: the least refusal if any refuses, whatever order the answers come in; else
/// every candidate any gives; else a block-local item if any names one; else every path a foreign glob could bring;
/// else unbound.
fn joined(heads: impl IntoIterator<Item = Head>) -> Head {
    let (mut bound, mut declared, mut through, mut alone, mut foreign, mut local) = (
        Vec::new(),
        Vec::new(),
        Vec::new(),
        Vec::new(),
        Vec::new(),
        false,
    );
    let mut refused: Option<String> = None;
    let mut open = false;
    let mut size = ReadingSize::default();
    for head in heads {
        if let Err(refusal) = size.head(&head) {
            return Head::PastCap(refusal);
        }
        match head {
            Head::PastCap(refusal) => refused = least(refused, refusal),
            Head::Candidates {
                bound: b,
                declared: d,
                through: p,
                heads: g,
                foreign: f,
                open: o,
            } => {
                bound.extend(b);
                declared.extend(d);
                through.extend(p);
                alone.extend(g);
                foreign.extend(f);
                open |= o;
            }
            Head::Foreign(paths) => foreign.extend(paths),
            Head::Local => local = true,
            Head::Unbound => {}
        }
    }
    if let Some(refusal) = refused {
        Head::PastCap(refusal)
    } else if !bound.is_empty() || !declared.is_empty() {
        declared.sort();
        declared.dedup();
        Head::Candidates {
            bound: sorted_unique(bound),
            declared,
            through: sorted_unique(through),
            heads: sorted_unique(alone),
            foreign: sorted_unique(foreign),
            open,
        }
    } else if local {
        Head::Local
    } else if !foreign.is_empty() {
        Head::Foreign(sorted_unique(foreign))
    } else {
        Head::Unbound
    }
}

/// The lesser of a refusal already held and another: the one refusal a fold over several reports, independent of the
/// order they were met in.
pub(super) fn least(held: Option<String>, refusal: String) -> Option<String> {
    Some(match held {
        Some(held) if held <= refusal => held,
        _ => refusal,
    })
}

/// `paths` sorted with duplicates removed, so answers built in different orders compare equal.
fn sorted_unique<T: Ord>(paths: impl IntoIterator<Item = T>) -> Vec<T> {
    let mut paths: Vec<T> = paths.into_iter().collect();
    paths.sort();
    paths.dedup();
    paths
}

#[cfg(test)]
mod tests {
    use super::super::token_tree::{Edition, TokenTree};
    use super::*;

    #[test]
    fn mutually_globbed_gated_modules_have_bounded_reading_work() {
        for (count, dense) in [(8, true), (16, true), (32, false)] {
            let mut source = String::new();
            for i in 0..count {
                source.push_str(&format!("#[cfg(unix)] pub mod m{i} {{\n"));
                for j in 0..count {
                    if i != j && (dense || j == (i + 1) % count || j == (i + count - 1) % count) {
                        source.push_str(&format!("pub use crate::m{j}::*;\n"));
                    }
                }
                if i == 0 {
                    source.push_str("pub fn f() {}\n");
                }
                source.push_str("}\n");
            }
            source.push_str("pub use m0::*;\npub fn g() { f(); }\n");
            let tree = TokenTree::lex(&source, Edition::Rust2021);
            let token = (0..tree.len())
                .find(|&i| tree.start(i) >= source.find("f();").unwrap())
                .unwrap();
            let scopes = CrateScopes::new(
                vec![ScopeTable::build(&tree, "crate", 0)],
                Edition::Rust2021,
            );
            let answer = scopes.name(
                0,
                scopes.table(0).scope_at(token),
                "f",
                PathSite::Expr,
                Namespace::Value,
            );
            assert!(
                matches!(&answer, Named::Paths(paths) if paths.iter().any(|p| p == "crate::m0::f")),
                "{answer:?}"
            );
            let reads = scopes.scope_reads.get();
            assert!(
                reads <= 32 * count * count * count,
                "{count} modules read {reads} scopes"
            );
        }
    }

    #[test]
    fn foreign_candidates_beside_local_ones_are_terminal_for_every_reader() {
        let source = "pub mod a { pub struct V; } pub mod s { #[cfg(any())] pub use crate::a::*; #[cfg(not(any()))] pub use std::process::*; }";
        let tree = TokenTree::lex(source, Edition::Rust2021);
        let scopes = CrateScopes::new(
            vec![ScopeTable::build(&tree, "crate", 0)],
            Edition::Rust2021,
        );
        assert!(
            scopes
                .denote("crate::s::V", Namespace::Type)
                .unwrap()
                .contains(&"std::process::V".to_string())
        );
        assert!(
            !scopes
                .readable_paths("crate::s::V", Namespace::Type)
                .unwrap()
                .contains(&"std::process::V".to_string())
        );
        for ancestors in [false, true] {
            let (paths, reaches) = scopes
                .hazard_paths("crate::s::V", Namespace::Type, "std::process", ancestors)
                .unwrap();
            assert!(!paths.contains(&"std::process::V".to_string()));
            assert!(reaches);
        }
        assert_eq!(
            scopes
                .denote_in(
                    "crate::s::V",
                    Namespace::Type,
                    &mut Walk::default(),
                    false,
                    None
                )
                .unwrap()
                .presence,
            Presence::Known
        );
    }

    #[test]
    fn distinct_denotations_share_a_retention_budget() {
        for limits in [
            (2, usize::MAX, usize::MAX),
            (usize::MAX, 2, usize::MAX),
            (usize::MAX, usize::MAX, 24),
        ] {
            let scopes = CrateScopes::new(Vec::new(), Edition::Rust2021);
            scopes.denoted.borrow_mut().limits = limits;
            for path in ["std::a", "std::b"] {
                assert_eq!(scopes.denote(path, Namespace::Type).unwrap(), vec![path]);
                assert_eq!(scopes.denote(path, Namespace::Type).unwrap(), vec![path]);
            }
            let error = scopes.denote("std::c", Namespace::Type).unwrap_err();
            assert!(error.contains("cannot judge a denotation memo"), "{error}");
            assert_eq!(scopes.denoted.borrow().answers.len(), 2);
            scopes.forget_readings();
            assert_eq!(
                scopes.denote("std::c", Namespace::Type).unwrap(),
                vec!["std::c"]
            );
        }
    }

    #[test]
    fn denotation_retention_charges_terminal_candidates_and_hazard_keys() {
        let source = "pub mod a { pub struct V; } pub mod s { #[cfg(any())] pub use crate::a::*; #[cfg(not(any()))] pub use std::process::*; }";
        let tree = TokenTree::lex(source, Edition::Rust2021);
        let scopes = CrateScopes::new(
            vec![ScopeTable::build(&tree, "crate", 0)],
            Edition::Rust2021,
        );
        scopes.denoted.borrow_mut().limits = (usize::MAX, 1, usize::MAX);
        assert!(
            scopes
                .denote("crate::s::V", Namespace::Type)
                .unwrap_err()
                .contains("denotation memo")
        );
        assert!(scopes.denoted.borrow().answers.is_empty());

        let scopes = CrateScopes::new(Vec::new(), Edition::Rust2021);
        scopes.denoted.borrow_mut().limits = (usize::MAX, usize::MAX, 12);
        assert!(
            scopes
                .hazard_paths("std::a", Namespace::Type, "std", false)
                .unwrap_err()
                .contains("denotation memo")
        );
        assert!(scopes.denoted.borrow().answers.is_empty());

        let mut memo = DenotationMemo {
            limits: (usize::MAX, usize::MAX, 6),
            ..Default::default()
        };
        assert!(
            memo.insert(
                ("std::a".to_string(), Namespace::Type, false, None),
                Err("refusal".to_string())
            )
            .is_err()
        );
        assert!(memo.answers.is_empty());
    }

    #[test]
    fn resolution_width_and_path_bytes_refuse_before_growth() {
        let paths = (0..=MAX_RESOLUTION_PATHS).map(|i| Head::Foreign(vec![format!("dep::p{i}")]));
        assert!(matches!(joined(paths), Head::PastCap(message) if message == width_refusal()));
        let tree = TokenTree::lex("", Edition::Rust2021);
        let scopes = CrateScopes::new(
            vec![ScopeTable::build(&tree, "crate", 0)],
            Edition::Rust2021,
        );
        assert_eq!(
            scopes.denote(&"x".repeat(MAX_RESOLUTION_BYTES + 1), Namespace::Type),
            Err(width_refusal())
        );
        let paths = vec!["std::process".to_string(); MAX_RESOLUTION_PATHS + 1];
        assert_eq!(
            scopes.denote_all(Vec::new(), &paths, Namespace::Type),
            Err(width_refusal())
        );
        assert_eq!(
            scopes.read_glob_paths(&paths, Vec::new(), &mut Walk::default()),
            Err(width_refusal())
        );
        let paths: Vec<String> = (0..MAX_RESOLUTION_PATHS)
            .map(|i| format!("dep::p{i}"))
            .collect();
        let count = MAX_GLOB_GRAPH_PATHS / MAX_RESOLUTION_PATHS + 1;
        let graph = GlobGraph {
            nodes: (0..count).map(|i| (i, 0, "crate".to_string())).collect(),
            index: HashMap::new(),
            reads: (0..count)
                .map(|_| GlobRead::Answered(Head::Foreign(paths.clone())))
                .collect(),
        };
        assert!(
            matches!(graph.settle("f"), Err(message) if message.contains("glob graph holding more than"))
        );
        let mut size = ReadingSize::default();
        assert!(size.add(&"x".repeat(MAX_RESOLUTION_BYTES)).is_ok());
        assert_eq!(size.add("x"), Err(width_refusal()));
    }

    /// The scopes a cfg-closed re-export ring of `links` links reads to answer `m0::f()`, and whether that answer names
    /// `crate::forbidden::f`.
    fn ring_reading(links: usize) -> (usize, bool) {
        let mut source = String::from("pub mod forbidden { pub fn f() {} }\n");
        for i in 0..links {
            source.push_str(&format!(
                "pub mod m{i} {{ #[cfg(unix)] pub use crate::m{}::f; #[cfg(not(unix))] pub use crate::forbidden::f; }}\n",
                i + 1
            ));
        }
        source.push_str(&format!(
            "pub mod m{links} {{ #[cfg(unix)] pub use crate::forbidden::f; #[cfg(not(unix))] pub use crate::m0::f; }}\n\
             pub fn g() {{ m0::f(); }}\n"
        ));
        let tree = TokenTree::lex(&source, Edition::Rust2021);
        let offset = source.find("m0::f()").unwrap();
        let token = (0..tree.len()).find(|&i| tree.start(i) >= offset).unwrap();
        let scopes = CrateScopes::new(
            vec![ScopeTable::build(&tree, "crate", 0)],
            Edition::Rust2021,
        );
        let named = scopes.name(
            0,
            scopes.table(0).scope_at(token),
            "m0::f",
            PathSite::Expr,
            Namespace::Value,
        );
        let reaches = matches!(&named, Named::Paths(paths) if paths.iter().any(|p| p == "crate::forbidden::f"));
        (scopes.scope_reads.get(), reaches)
    }

    /// The declared bound `a-cfg-closed-re-export-ring-is-read-in-time-exponential-in-its-length`, held by the work
    /// it names rather than by a clock: an answer read past a cut cycle is not remembered, so each link is re-read once
    /// per path to it and eleven links read at least four times the scopes eight do, where doubling per link makes it
    /// about eight. Both answers reach `crate::forbidden::f`. A repair that bounds the reading fails here, naming the
    /// bound to retire; no mutation record pins it, since the bound states a cost no single perturbation turns without
    /// repairing the defect.
    #[test]
    fn a_cfg_closed_re_export_ring_is_read_in_time_exponential_in_its_length() {
        let (short, short_reaches) = ring_reading(8);
        let (long, long_reaches) = ring_reading(11);
        assert!(
            short_reaches && long_reaches,
            "both rings name crate::forbidden::f"
        );
        assert!(
            long >= short * 4,
            "eleven links read {long} scopes and eight {short}: the ring no longer doubles per link, so the declared \
             bound a-cfg-closed-re-export-ring-is-read-in-time-exponential-in-its-length no longer holds and should be \
             retired"
        );
    }

    /// What `head` at `at` in `source`, read as `crate::core` beneath a crate root declaring it, names.
    fn resolved(source: &str, at: &str, head: &str, ns: Namespace) -> Option<String> {
        let tree = TokenTree::lex(source, Edition::Rust2018);
        let offset = source.find(at).unwrap();
        let token = (0..tree.len()).find(|&i| tree.start(i) >= offset).unwrap();
        let table = ScopeTable::build(&tree, "crate::core", 0);
        let root = TokenTree::lex("pub mod core;\n", Edition::Rust2018);
        let root = ScopeTable::build(&root, "crate", 1);
        let scopes = CrateScopes::new(vec![table, root], Edition::Rust2018);
        match scopes.name(0, scopes.table(0).scope_at(token), head, PathSite::Expr, ns) {
            Named::Paths(paths) => Some(paths.join(" | ")),
            Named::Unbound { also, .. } if !also.is_empty() => Some(also.join(" | ")),
            Named::Local => Some("<local>".to_string()),
            _ => None,
        }
    }

    #[test]
    fn written_root_classifies_each_root_once() {
        let bare = |head: &str, rest: &[&str]| WrittenRoot::Bare {
            head: head.to_string(),
            rest: rest.iter().map(|s| s.to_string()).collect(),
        };
        let from_root = |head: &str, rest: &[&str]| WrittenRoot::FromCrateRoot {
            head: head.to_string(),
            rest: rest.iter().map(|s| s.to_string()).collect(),
        };
        let extern_ = |head: &str, rest: &[&str]| WrittenRoot::Extern {
            head: head.to_string(),
            rest: rest.iter().map(|s| s.to_string()).collect(),
        };
        let crate_ = |path: &str| WrittenRoot::Crate(path.to_string());
        for (written, module, site, edition, expected) in [
            (
                "std::time",
                "crate::core",
                PathSite::Expr,
                Edition::Rust2018,
                bare("std", &["time"]),
            ),
            (
                "::core::time",
                "crate::core",
                PathSite::Expr,
                Edition::Rust2018,
                extern_("core", &["time"]),
            ),
            (
                "::alloc::vec",
                "crate::core",
                PathSite::Use,
                Edition::Rust2015,
                from_root("alloc", &["vec"]),
            ),
            (
                "crate::a::X",
                "crate::core",
                PathSite::Expr,
                Edition::Rust2018,
                crate_("crate::a::X"),
            ),
            (
                "super::X",
                "crate::core::t",
                PathSite::Use,
                Edition::Rust2018,
                crate_("crate::core::X"),
            ),
            (
                "self::X",
                "crate::core",
                PathSite::Expr,
                Edition::Rust2018,
                crate_("crate::core::X"),
            ),
            (
                "super::super::X",
                "crate",
                PathSite::Expr,
                Edition::Rust2018,
                WrittenRoot::Invalid,
            ),
            (
                "::self::X",
                "crate::core",
                PathSite::Expr,
                Edition::Rust2018,
                WrittenRoot::Invalid,
            ),
            (
                "::super::X",
                "crate::core",
                PathSite::Use,
                Edition::Rust2015,
                WrittenRoot::Invalid,
            ),
            (
                "::md5x::f",
                "crate::core",
                PathSite::Expr,
                Edition::Rust2018,
                extern_("md5x", &["f"]),
            ),
            (
                "::md5x::f",
                "crate::core",
                PathSite::Expr,
                Edition::Rust2015,
                from_root("md5x", &["f"]),
            ),
            (
                "clock::now",
                "crate::core",
                PathSite::Use,
                Edition::Rust2015,
                from_root("clock", &["now"]),
            ),
            (
                "clock::now",
                "crate::core",
                PathSite::Expr,
                Edition::Rust2015,
                bare("clock", &["now"]),
            ),
            (
                "clock::now",
                "crate::core",
                PathSite::Use,
                Edition::Rust2018,
                bare("clock", &["now"]),
            ),
            (
                "r#try::f",
                "crate::core",
                PathSite::Expr,
                Edition::Rust2018,
                bare("try", &["f"]),
            ),
            (
                "",
                "crate::core",
                PathSite::Expr,
                Edition::Rust2018,
                WrittenRoot::Invalid,
            ),
        ] {
            assert_eq!(
                written_root(written, module, site, edition),
                expected,
                "`{written}` at {module}, {edition:?}"
            );
        }
    }

    #[test]
    fn a_block_use_binds_its_whole_block_and_nothing_outside() {
        let source = "mod a { pub struct X; }\nmod b { pub struct X; }\nuse crate::core::a::X;\nfn h() { X::fa(); }\nfn g() { X::early(); use crate::core::b::X; X::fb(); }\nfn k() { X::late(); }\n";
        for (at, expected) in [
            ("X::fa", "crate::core::a::X"),
            ("X::early", "crate::core::b::X"),
            ("X::fb", "crate::core::b::X"),
            ("X::late", "crate::core::a::X"),
        ] {
            assert_eq!(
                resolved(source, at, "X", Namespace::Type).as_deref(),
                Some(expected),
                "{at}"
            );
        }
    }

    #[test]
    fn a_block_item_shadows_in_its_namespace_only() {
        let source = "use std::process::Command;\nfn g() { struct Command {} let _ = Command::new(); let _ = Command(); }\n";
        assert_eq!(
            resolved(source, "Command::new", "Command", Namespace::Type).as_deref(),
            Some("<local>")
        );
        assert_eq!(
            resolved(source, "Command()", "Command", Namespace::Value).as_deref(),
            Some("std::process::Command"),
            "a braced struct names no value"
        );
    }

    #[test]
    fn member_bodies_bind_nothing_and_pass_through_bodies_bind_outward() {
        let source = "use std::process::Command;\nimpl S { const Command: u8 = 0; fn f() { Command::a(); } }\nenum E { Command }\nfn g() { extern \"C\" { fn Command(); } Command(); }\ncfg_if! { if #[cfg(unix)] { use crate::u::Y; } else { use crate::w::Y; } }\nfn y() { Y::b(); }\n";
        assert_eq!(
            resolved(source, "Command::a", "Command", Namespace::Type).as_deref(),
            Some("std::process::Command")
        );
        assert_eq!(
            resolved(source, "Command();", "Command", Namespace::Value).as_deref(),
            Some("<local>"),
            "an extern block's item belongs to the enclosing block"
        );
        assert_eq!(
            resolved(source, "Y::b", "Y", Namespace::Type).as_deref(),
            Some("crate::u::Y | crate::w::Y"),
            "each cfg_if arm's use binds at module scope, and both are candidates"
        );
    }

    #[test]
    fn a_keyword_in_a_type_heads_no_item() {
        let source = "use std::process::Command;\nfn g() -> impl Sized { let _: &'static str = \"\"; Command::new() }\n";
        assert_eq!(
            resolved(source, "Command::new", "Command", Namespace::Type).as_deref(),
            Some("std::process::Command")
        );
    }
}