echoes 0.10.2

Find duplicated Rust doctests, functions and contexts
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
//! Source-only metadata extraction for indexed context records.

use crate::cfg::{path_claims, render_conjunction};
use crate::reuse::ContextAccess;
use crate::{ContextSite, TargetScan};
use alloc::collections::{BTreeMap, BTreeSet, VecDeque};
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use proc_macro2::Span;
use quote::ToTokens;
use syn::ext::IdentExt;
use syn::visit::Visit;

/// One indexed lexical context, recorded without a token floor.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct IndexedContext {
    /// The canonical form text of the context.
    pub form: String,
    /// The canonical weighted-token count.
    pub tokens: usize,
    /// The original source range.
    pub site: ContextSite,
    /// The exact lexical module path of the context.
    pub module: String,
    /// The owning compilation target name.
    pub crate_name: String,
    /// The owning target root source path, workspace-relative.
    pub crate_root: String,
    /// Source-established accessibility of the context.
    pub access: ContextAccess,
    /// The established external route, for accessible whole functions and methods.
    #[serde(default)]
    pub api_path: Option<String>,
    /// Conditional-compilation requirements retained from source.
    pub conditions: Vec<String>,
    /// Source-established extraction constraints and unresolved facts.
    pub extraction_notes: Vec<String>,
}

/// The indexed contexts of the files of `target` that `scanned` keeps, one record per context
/// and module membership.
#[must_use]
pub fn extract(
    target: &TargetScan,
    root: &str,
    scanned: &dyn Fn(&crate::SourceFile) -> bool,
) -> Vec<IndexedContext> {
    let layout = crate_layout(target);
    let model = CrateModel::new(target, &layout);
    let crate_root = workspace_relative(target.files.first().map_or("", |f| f.path.as_str()), root);
    let mut out = Vec::new();
    for file in target.files.iter().filter(|file| scanned(file)) {
        let path = workspace_relative(&file.path, root);
        let memberships = layout
            .memberships
            .get(&workspace_relative(&file.path, ""))
            .expect("a layout file");
        let meta = context_meta(&file.parsed);
        let mut extractor = Extractor {
            model: &model,
            library: target.library,
            name: &target.name,
            path: &path,
            crate_root: &crate_root,
            ascii: file.text.is_ascii(),
            offset: SourceOffset::new(&file.parsed, &file.text),
            text: &file.text,
            meta: &meta,
            seen: BTreeSet::new(),
            out: &mut out,
        };
        syn_canon::contexts(&file.parsed, &mut |context, canonical| {
            extractor.context(&context, canonical, memberships);
        });
    }
    out
}

/// The text `parse_file` dropped before tokenizing, for `byte_range` offsets.
struct SourceOffset {
    /// Bytes removed by shebang preprocessing.
    shebang: usize,
    /// Bytes removed by the leading BOM, 0 or 3.
    bom: usize,
}

impl SourceOffset {
    fn new(parsed: &syn::File, text: &str) -> Self {
        let shebang = parsed.shebang.as_ref().map_or(0, String::len);
        let bom = usize::from(text.starts_with('\u{feff}')) * '\u{feff}'.len_utf8();
        SourceOffset { shebang, bom }
    }

    /// The original-text index of a `byte_range` offset.
    fn origin(&self, offset: usize) -> usize {
        offset + self.shebang + self.bom
    }
}

/// The 1-based byte column of an original-text index, exclusive for ends.
fn byte_column(text: &str, offset: usize) -> usize {
    offset - text[..offset].rfind('\n').map_or(0, |newline| newline + 1) + 1
}

/// One file's extraction state, the callback closure's capture set.
struct Extractor<'a> {
    model: &'a CrateModel,
    library: bool,
    name: &'a str,
    path: &'a str,
    crate_root: &'a str,
    ascii: bool,
    offset: SourceOffset,
    text: &'a str,
    meta: &'a BTreeMap<SpanKey, Meta>,
    seen: BTreeSet<(usize, u32, usize, u32, usize)>,
    out: &'a mut Vec<IndexedContext>,
}

impl Extractor<'_> {
    fn context(
        &mut self,
        context: &syn_canon::Context,
        canonical: syn_canon::CanonicalForm,
        memberships: &[Membership],
    ) {
        let tokens = canonical.body_units();
        let form = canonical.into_key();
        let (start, end) = (context.span.start(), context.span.end());
        let (column, end_column) = if self.ascii {
            (start.column + 1, end.column + 1)
        } else {
            let bytes = context.span.byte_range();
            (
                byte_column(self.text, self.offset.origin(bytes.start)),
                byte_column(self.text, self.offset.origin(bytes.end)),
            )
        };
        let line = u32::try_from(start.line).unwrap_or(u32::MAX);
        let end_line = u32::try_from(end.line).unwrap_or(u32::MAX);
        let key_span = span_key(context.span);
        let chain = self
            .meta
            .get(&key_span)
            .map_or(Vec::new(), |m| m.chain.clone());
        let clf = Classifier {
            model: self.model,
            name: self.name,
            library: self.library,
        };
        for (membership_index, membership) in memberships.iter().enumerate() {
            let key = (membership_index, line, column, end_line, end_column);
            if !self.seen.insert(key) {
                continue;
            }
            let branch = render_alternatives(&membership.alternatives);
            let shadowed = !membership.alternatives.is_empty()
                && membership
                    .alternatives
                    .iter()
                    .all(|alternative| alternative.iter().any(|condition| condition == "false"));
            let (access, api_path, conditions, notes) = classify(
                &clf,
                &membership.module,
                branch.as_deref(),
                shadowed,
                self.meta
                    .get(&key_span)
                    .expect("the source walk records every emitted context"),
                context.item,
            );
            let prefix = join_path(
                core::iter::once(self.name).chain(membership.module.iter().map(String::as_str)),
            );
            let item = join_path([prefix.as_str(), context.item]);
            let module = join_path(
                [prefix.as_str()]
                    .into_iter()
                    .chain(chain.iter().map(String::as_str)),
            );
            self.out.push(IndexedContext {
                form: form.clone(),
                tokens,
                site: ContextSite {
                    file: self.path.to_string(),
                    line,
                    column,
                    end: end_line,
                    end_column,
                    item,
                    kind: context.kind,
                },
                module,
                crate_name: self.name.to_string(),
                crate_root: self.crate_root.to_string(),
                access,
                api_path,
                conditions,
                extraction_notes: notes,
            });
        }
    }
}

/// The crate and target inputs shared by the whole-body route classifiers.
struct Classifier<'a> {
    model: &'a CrateModel,
    name: &'a str,
    library: bool,
}

/// The accessibility and external route of a whole function or method.
fn classify(
    clf: &Classifier,
    membership: &[String],
    branch: Option<&str>,
    shadowed: bool,
    meta: &Meta,
    item: &str,
) -> (ContextAccess, Option<String>, Vec<String>, Vec<String>) {
    let mut conditions: Vec<String> = meta.cfg.clone();
    if let Some(branch) = branch {
        conditions.push(branch.to_string());
    }
    conditions.sort_unstable();
    conditions.dedup();
    if shadowed {
        return (
            ContextAccess::Unresolved,
            None,
            conditions,
            alloc::vec![
                "the source is shadowed by an earlier path provider and never linked".to_string()
            ],
        );
    }
    let module_rel = join_path(membership.iter().chain(meta.chain.iter()));
    let fn_name = item.rsplit("::").next().unwrap_or(item).to_string();
    let notes = Vec::new();
    match &meta.flavor {
        Flavor::Embedded => (ContextAccess::Embedded, None, conditions, notes),
        Flavor::Free { visible, nested } => {
            let path = join_path([module_rel.as_str(), fn_name.as_str()]);
            classify_item(clf, *nested, &path, *visible, conditions)
        }
        Flavor::Method {
            self_type,
            visible,
            nested,
        } => classify_method(
            clf,
            &module_rel,
            self_type,
            *visible,
            *nested,
            &fn_name,
            conditions,
        ),
        Flavor::TraitDefault {
            trait_name,
            trait_visible,
            nested,
        } => {
            let path = join_path([module_rel.as_str(), trait_name.as_str()]);
            classify_trait_default(clf, *nested, &path, *trait_visible, &fn_name, conditions)
        }
    }
}

/// The route of a whole free function body.
fn classify_item(
    clf: &Classifier,
    nested: bool,
    path: &str,
    visible: Vis,
    conditions: Vec<String>,
) -> (ContextAccess, Option<String>, Vec<String>, Vec<String>) {
    let mut notes = Vec::new();
    if !clf.library {
        notes.push(not_established());
        return (ContextAccess::Unresolved, None, conditions, notes);
    }
    if nested {
        notes.push(nested_note());
        return (ContextAccess::InternalFunction, None, conditions, notes);
    }
    match item_route(clf.model, path, visible == Vis::Public) {
        Established::Public {
            route,
            conditions: carried,
        } => {
            let conditions = merge_conditions(clf.model, conditions, carried, &route);
            (
                ContextAccess::PublicFunction,
                Some(qualify(clf.name, route)),
                conditions,
                notes,
            )
        }
        Established::Internal => (ContextAccess::InternalFunction, None, conditions, notes),
        Established::Unknown(reason) => {
            notes.push(reason);
            (ContextAccess::Unresolved, None, conditions, notes)
        }
    }
}

/// The route of a whole method body, decided by the receiver.
fn classify_method(
    clf: &Classifier,
    module_rel: &str,
    self_type: &str,
    visible: Vis,
    nested: bool,
    fn_name: &str,
    conditions: Vec<String>,
) -> (ContextAccess, Option<String>, Vec<String>, Vec<String>) {
    let mut notes = Vec::new();
    if !clf.library {
        notes.push(not_established());
        return (ContextAccess::Unresolved, None, conditions, notes);
    }
    if nested {
        notes.push(nested_note());
        return (ContextAccess::InternalMethod, None, conditions, notes);
    }
    if visible != Vis::Public {
        return (ContextAccess::InternalMethod, None, conditions, notes);
    }
    match receiver_route(clf.model, module_rel, self_type) {
        Established::Public {
            route,
            conditions: carried,
        } => (
            ContextAccess::PublicMethod,
            Some(qualify(clf.name, join_path([route.as_str(), fn_name]))),
            merge_conditions(clf.model, conditions, carried, &route),
            notes,
        ),
        Established::Internal => {
            notes.push(format!("the receiver {self_type} is internal to the crate"));
            (ContextAccess::InternalMethod, None, conditions, notes)
        }
        Established::Unknown(reason) => {
            notes.push(reason);
            (ContextAccess::Unresolved, None, conditions, notes)
        }
    }
}

/// The route of a whole trait default body, following the trait.
fn classify_trait_default(
    clf: &Classifier,
    nested: bool,
    path: &str,
    trait_visible: Vis,
    fn_name: &str,
    conditions: Vec<String>,
) -> (ContextAccess, Option<String>, Vec<String>, Vec<String>) {
    let mut notes = Vec::new();
    if !clf.library {
        notes.push(not_established());
        return (ContextAccess::Unresolved, None, conditions, notes);
    }
    if nested {
        notes.push(nested_note());
        return (ContextAccess::InternalMethod, None, conditions, notes);
    }
    match item_route(clf.model, path, trait_visible == Vis::Public) {
        Established::Public {
            route,
            conditions: carried,
        } => (
            ContextAccess::PublicMethod,
            Some(qualify(clf.name, join_path([route.as_str(), fn_name]))),
            merge_conditions(clf.model, conditions, carried, &route),
            notes,
        ),
        Established::Internal => (ContextAccess::InternalMethod, None, conditions, notes),
        Established::Unknown(reason) => {
            notes.push(reason);
            (ContextAccess::Unresolved, None, conditions, notes)
        }
    }
}

fn not_established() -> String {
    "the target is not a library, so external accessibility is not established".to_string()
}

fn nested_note() -> String {
    "a nested function body is never externally reachable".to_string()
}

/// The established route of an item as public, internal, or unestablished.
enum Established {
    /// The known external route, target-relative, with the conditions its resolution carried.
    Public {
        route: String,
        conditions: Vec<String>,
    },
    /// The source establishes that no external route exists.
    Internal,
    /// Source evidence does not settle the route, with the reason.
    Unknown(String),
}

fn item_route(model: &CrateModel, path: &str, visible: bool) -> Established {
    if model.chain_visible(path) && visible {
        return Established::Public {
            route: path.to_string(),
            conditions: Vec::new(),
        };
    }
    if visible && let Some((route, conditions)) = reexport_route(model, path) {
        return Established::Public { route, conditions };
    }
    if model.resolved && model.chain_known(path) {
        return Established::Internal;
    }
    if let Some(module) = first_unknown_module(model, path) {
        return Established::Unknown(format!(
            "module {module} is not found in the scanned source"
        ));
    }
    let module = model
        .first_unresolved_module()
        .expect("an unresolved target records an unresolved module");
    Established::Unknown(format!(
        "module {module} is not found in the scanned source"
    ))
}

/// The first module of `path` missing from the model.
fn first_unknown_module(model: &CrateModel, path: &str) -> Option<String> {
    module_segments(path)
        .into_iter()
        .find(|module| !model.modules.contains_key(module))
}

/// The base conditions plus every condition on the chosen route.
fn merge_conditions(
    model: &CrateModel,
    base: Vec<String>,
    carried: Vec<String>,
    route: &str,
) -> Vec<String> {
    let mut out = base;
    out.extend(carried);
    out.extend(route_path_conditions(model, route));
    out.sort_unstable();
    out.dedup();
    out
}

/// The cfg conditions of the modules and terminal type on `route`, plus the
/// branch conditions of any module whose claims do not cover every case.
fn route_path_conditions(model: &CrateModel, route: &str) -> Vec<String> {
    let mut out = Vec::new();
    for module in module_segments(route) {
        if let Some(info) = model.modules.get(&module) {
            out.extend(info.cfg.iter().cloned());
            if let Some(claim) = render_alternatives(&info.claims) {
                out.push(claim);
            }
        }
    }
    if let Some(def) = model.types.get(route) {
        out.extend(def.cfg.iter().cloned());
    }
    out
}

/// The text of a disjunction of claim alternatives, `None` when no condition
/// applies or an alternative is unconditional.
fn render_alternatives(alternatives: &[Vec<String>]) -> Option<String> {
    let mut rendered = Vec::new();
    for alternative in alternatives {
        let text = render_conjunction(alternative);
        if text.is_empty() {
            return None;
        }
        if !rendered.iter().any(|existing| existing == &text) {
            rendered.push(text);
        }
    }
    for text in &rendered {
        if rendered
            .iter()
            .any(|other| other == &format!("not({text})"))
        {
            return None;
        }
    }
    match rendered.len() {
        0 => None,
        1 => rendered.into_iter().next(),
        _ => Some(format!("any({})", rendered.join(", "))),
    }
}

/// The re-exported route of an item, through a bare `pub use` on a visible chain of the item
/// itself or of a module above it.
fn reexport_route(model: &CrateModel, path: &str) -> Option<(String, Vec<String>)> {
    for (module, bindings) in &model.bindings {
        if !model.module_chain_visible(module) {
            continue;
        }
        for binding in bindings.iter().filter(|b| b.visible) {
            let Some(target) = resolve_use_target(model, module, &binding.segments, binding.rooted)
            else {
                continue;
            };
            let route = match binding.alias.as_deref() {
                Some(alias) if target == path => qualified(module, alias),
                Some(alias) => match reexported_rest(model, &target, path) {
                    Some(rest) => qualified(module, &qualified(alias, rest)),
                    None => continue,
                },
                None => match reexported_rest(model, &target, path) {
                    Some(rest) => qualified(module, rest),
                    None => continue,
                },
            };
            return Some(reexport_with_conditions(model, binding, path, route));
        }
    }
    None
}

/// The part of `path` below the module `target`, when every module in it is visible.
fn reexported_rest<'a>(model: &CrateModel, target: &str, path: &'a str) -> Option<&'a str> {
    let rest = path.strip_prefix(target)?.strip_prefix("::")?;
    if !model.modules.contains_key(target) {
        return None;
    }
    module_segments(rest)
        .iter()
        .all(|below| {
            model
                .modules
                .get(&qualified(target, below))
                .is_some_and(|info| info.visible && info.resolved)
        })
        .then_some(rest)
}

/// A re-export route with the cfg conditions of its declaration and the
/// conditions of the item's actual location.
fn reexport_with_conditions(
    model: &CrateModel,
    binding: &Binding,
    location: &str,
    route: String,
) -> (String, Vec<String>) {
    let mut conditions = binding.cfg.clone();
    conditions.extend(route_path_conditions(model, &route));
    conditions.extend(route_path_conditions(model, location));
    (route, conditions)
}

/// The receiver's established route for a written self type.
fn receiver_route(model: &CrateModel, module: &str, self_type: &str) -> Established {
    let Some(base) = bare_receiver(self_type) else {
        return Established::Unknown(format!(
            "the receiver {self_type} is not established from the scanned source"
        ));
    };
    if is_primitive(base) {
        return Established::Public {
            route: base.to_string(),
            conditions: Vec::new(),
        };
    }
    type_route(model, module, base)
}

/// The bare type name of a written self type, generics ignored.
fn bare_receiver(self_type: &str) -> Option<&str> {
    let base = self_type.split('<').next()?.trim();
    let first = base.chars().next()?;
    if (first.is_ascii_alphabetic() || first == '_')
        && base.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
    {
        Some(base)
    } else {
        None
    }
}

const PRIMITIVES: &[&str] = &[
    "bool", "char", "str", "i8", "i16", "i32", "i64", "i128", "isize", "u8", "u16", "u32", "u64",
    "u128", "usize", "f32", "f64", "()",
];

fn is_primitive(name: &str) -> bool {
    PRIMITIVES.contains(&name)
}

/// The established route of a type name resolvable in `module`.
fn type_route(model: &CrateModel, module: &str, name: &str) -> Established {
    let mut glob_before = false;
    let mut m = Some(module.to_string());
    while let Some(path) = m {
        let def_path = qualified(&path, name);
        if glob_before
            && (model.types.contains_key(&def_path) || model.binding_in(&path, name).is_some())
        {
            return Established::Unknown(format!(
                "the receiver {name} may be shadowed by a glob import"
            ));
        }
        if let Some(def) = model.types.get(&def_path) {
            return item_route(model, &def_path, def.visible);
        }
        if let Some(binding) = model.binding_in(&path, name) {
            match resolve_use_target(model, &path, &binding.segments, binding.rooted) {
                Some(target) if model.types.contains_key(&target) => {
                    let def = model
                        .types
                        .get(&target)
                        .expect("a just-checked type definition");
                    let mut established = item_route(model, &target, def.visible);
                    if let Established::Public { conditions, .. } = &mut established {
                        conditions.extend(binding.cfg.iter().cloned());
                        conditions.extend(route_path_conditions(model, &target));
                    }
                    return established;
                }
                Some(_) => {
                    return Established::Unknown(format!(
                        "the receiver {name} binds to a type outside the scanned source"
                    ));
                }
                None => {
                    return Established::Unknown(format!(
                        "the receiver {name} binds to an unresolvable path"
                    ));
                }
            }
        }
        if model.glob_in(&path) {
            glob_before = true;
        }
        m = parent_of(&path);
    }
    Established::Unknown(format!(
        "the receiver {name} is not defined in the scanned source"
    ))
}

/// The resolved target of a written use path, `None` when unresolvable.
fn resolve_use_target(
    model: &CrateModel,
    from: &str,
    written: &[String],
    rooted: bool,
) -> Option<String> {
    resolve_use_target_inner(model, from, written, rooted, 0)
}

fn resolve_use_target_inner(
    model: &CrateModel,
    from: &str,
    written: &[String],
    rooted: bool,
    hops: usize,
) -> Option<String> {
    let mut queue: VecDeque<String> = written.iter().cloned().collect();
    let mut rooted = rooted;
    if !rooted && queue.front().is_some_and(|first| first == "crate") {
        queue.pop_front();
        rooted = true;
    }
    let mut base: Vec<String> = if rooted {
        Vec::new()
    } else {
        segments_of(from).into_iter().map(String::from).collect()
    };
    let mut redirects = hops;
    while let Some(segment) = queue.pop_front() {
        match segment.as_str() {
            "self" => {}
            "super" => {
                if base.is_empty() {
                    return None;
                }
                base.pop();
            }
            name => {
                let base_path = join_path(base.iter().map(String::as_str));
                let mut candidate = base.clone();
                candidate.push(name.to_string());
                if model
                    .modules
                    .contains_key(&join_path(candidate.iter().map(String::as_str)))
                {
                    base = candidate;
                    continue;
                }
                let binding = model.binding_in(&base_path, name).or_else(|| {
                    (base_path == from)
                        .then(|| model.binding_ancestor(&base_path, name))
                        .flatten()
                });
                let Some(binding) = binding else {
                    if queue.is_empty() {
                        base = candidate;
                        return Some(join_path(base.iter().map(String::as_str)));
                    }
                    return None;
                };
                redirects += 1;
                if redirects > 8 {
                    return None;
                }
                let target = resolve_use_target_inner(
                    model,
                    &base_path,
                    &binding.segments,
                    binding.rooted,
                    redirects,
                )?;
                if model.modules.contains_key(&target) {
                    base = segments_of(&target).into_iter().map(String::from).collect();
                } else if queue.is_empty() {
                    return Some(target);
                } else {
                    return None;
                }
            }
        }
    }
    Some(join_path(base.iter().map(String::as_str)))
}

/// The cumulative module paths below `path`, the item name excluded.
fn module_segments(path: &str) -> Vec<String> {
    let segments = segments_of(path);
    let modules = segments.len().saturating_sub(1);
    (1..=modules)
        .map(|end| segments[..end].join("::"))
        .collect()
}

/// `path` split on `::`, empty segments dropped.
fn segments_of(path: &str) -> Vec<&str> {
    path.split("::").filter(|s| !s.is_empty()).collect()
}

/// The parent of `path`, `None` for a top module.
fn parent_of(path: &str) -> Option<String> {
    let segments = segments_of(path);
    let last = segments.len().checked_sub(1)?;
    Some(segments[..last].join("::"))
}

/// `tail` appended to `module`, the bare name at the crate root.
fn qualified(module: &str, tail: &str) -> String {
    if module.is_empty() {
        tail.to_string()
    } else {
        format!("{module}::{tail}")
    }
}

/// The last `::` segment of `path`.
fn last_segment(path: &str) -> &str {
    path.rsplit("::").next().unwrap_or(path)
}

/// `segments` joined on `::`, empty entries dropped.
fn join_path<I>(segments: I) -> String
where
    I: IntoIterator,
    I::Item: AsRef<str>,
{
    let mut out = String::new();
    for segment in segments {
        let segment = segment.as_ref();
        if segment.is_empty() {
            continue;
        }
        if !out.is_empty() {
            out.push_str("::");
        }
        out.push_str(segment);
    }
    out
}

/// `route` qualified with the target name.
fn qualify(name: &str, route: String) -> String {
    join_path([name.to_string(), route])
}

/// `path` as a workspace-relative site path with forward slashes and no leading `./` or `/`.
fn workspace_relative(path: &str, root: &str) -> String {
    let stripped = path.strip_prefix(root).unwrap_or(path);
    let mut out = stripped.replace('\\', "/");
    while let Some(rest) = out.strip_prefix("./") {
        out = rest.to_string();
    }
    while let Some(rest) = out.strip_prefix('/') {
        out = rest.to_string();
    }
    out
}

/// The directory of `path`, `""` at the top.
fn dir_of(path: &str) -> String {
    match path.rfind('/') {
        Some(index) => path[..index].to_string(),
        None => String::new(),
    }
}

/// The file stem of `path`, its last extension dropped.
fn stem_of(path: &str) -> &str {
    let file = last_segment(path);
    match file.rfind('.') {
        Some(index) if index > 0 => &file[..index],
        _ => file,
    }
}

/// `dir` and `name` joined, `.` dropped and `..` taking off the previous component.
fn lexical_join(dir: &str, name: &str) -> String {
    let name = name.replace('\\', "/");
    if name.starts_with('/') {
        return name;
    }
    let mut out: Vec<&str> = dir
        .split('/')
        .filter(|c| !c.is_empty() && *c != ".")
        .collect();
    for component in name.split('/').filter(|c| !c.is_empty()) {
        match component {
            "." => {}
            ".." => {
                out.pop();
            }
            other => out.push(other),
        }
    }
    out.join("/")
}

/// `dir/name` joined on one separator.
fn join_dir(dir: &str, name: &str) -> String {
    if dir.is_empty() {
        name.to_string()
    } else {
        format!("{dir}/{name}")
    }
}

/// The callback span's positions.
type SpanKey = (u32, u32, u32, u32);

fn span_key(span: Span) -> SpanKey {
    let start = span.start();
    let end = span.end();
    (
        u32::try_from(start.line).unwrap_or(u32::MAX),
        u32::try_from(start.column).unwrap_or(u32::MAX),
        u32::try_from(end.line).unwrap_or(u32::MAX),
        u32::try_from(end.column).unwrap_or(u32::MAX),
    )
}

/// The first-to-last token span of `node`, the way the context emitter measures it.
fn node_span(node: &impl ToTokens) -> SpanKey {
    let mut first = None;
    let mut last = None;
    for tree in node.to_token_stream() {
        if first.is_none() {
            first = Some(tree.span());
        }
        last = Some(tree.span());
    }
    let last = last.expect("a recorded node carries tokens");
    let first = first.unwrap_or(last);
    span_key(first.join(last).unwrap_or_else(Span::call_site))
}

/// The inline module chain, enclosing cfgs and function flavour of each emitted context.
struct Meta {
    chain: Vec<String>,
    cfg: Vec<String>,
    flavor: Flavor,
}

/// What the context is, from the source walk.
enum Flavor {
    /// A context embedded in an item, requiring extraction.
    Embedded,
    /// A whole free function body.
    Free { visible: Vis, nested: bool },
    /// A whole method body, `self_type` as written on the impl.
    Method {
        self_type: String,
        visible: Vis,
        nested: bool,
    },
    /// A whole trait default body.
    TraitDefault {
        trait_name: String,
        trait_visible: Vis,
        nested: bool,
    },
}

/// The declared visibility of an item.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Vis {
    /// No `pub`.
    Inherited,
    /// A bare `pub`.
    Public,
    /// A restricted `pub(crate)`, `pub(super)` or `pub(path)`.
    Restricted,
}

fn vis_class(vis: &syn::Visibility) -> Vis {
    match vis {
        syn::Visibility::Inherited => Vis::Inherited,
        syn::Visibility::Public(_) => Vis::Public,
        syn::Visibility::Restricted(_) => Vis::Restricted,
    }
}

/// The walk that records one meta per emitted context node.
struct MetaWalk {
    chain: Vec<String>,
    cfg: Vec<String>,
    fns: usize,
    owner: Option<Owner>,
    out: BTreeMap<SpanKey, Meta>,
}

/// The enclosing impl self type or trait, for method and trait-default flavours.
#[derive(Clone)]
struct Owner {
    /// The impl self type as written.
    self_type: String,
    /// The enclosing trait name.
    trait_name: Option<String>,
    /// The enclosing trait's declared visibility.
    trait_vis: Vis,
}

impl MetaWalk {
    fn record(&mut self, key: SpanKey, flavor: Flavor) {
        self.out.insert(
            key,
            Meta {
                chain: self.chain.clone(),
                cfg: self.cfg.clone(),
                flavor,
            },
        );
    }
}

impl Visit<'_> for MetaWalk {
    fn visit_item_mod(&mut self, item: &syn::ItemMod) {
        let depth = self.cfg.len();
        self.cfg.extend(cfgs(&item.attrs));
        self.chain.push(item.ident.to_string());
        syn::visit::visit_item_mod(self, item);
        self.chain.pop();
        self.cfg.truncate(depth);
    }

    fn visit_item_fn(&mut self, item: &syn::ItemFn) {
        let depth = self.cfg.len();
        self.cfg.extend(cfgs(&item.attrs));
        self.record(
            node_span(item.block.as_ref()),
            Flavor::Free {
                visible: vis_class(&item.vis),
                nested: self.fns > 0,
            },
        );
        self.fns += 1;
        syn::visit::visit_item_fn(self, item);
        self.fns -= 1;
        self.cfg.truncate(depth);
    }

    fn visit_item_impl(&mut self, item: &syn::ItemImpl) {
        let depth = self.cfg.len();
        self.cfg.extend(cfgs(&item.attrs));
        let owner = Owner {
            self_type: type_text(&item.self_ty),
            trait_name: None,
            trait_vis: Vis::Inherited,
        };
        let previous = self.owner.replace(owner);
        syn::visit::visit_item_impl(self, item);
        self.owner = previous;
        self.cfg.truncate(depth);
    }

    fn visit_item_trait(&mut self, item: &syn::ItemTrait) {
        let depth = self.cfg.len();
        self.cfg.extend(cfgs(&item.attrs));
        let owner = Owner {
            self_type: String::new(),
            trait_name: Some(item.ident.to_string()),
            trait_vis: vis_class(&item.vis),
        };
        let previous = self.owner.replace(owner);
        syn::visit::visit_item_trait(self, item);
        self.owner = previous;
        self.cfg.truncate(depth);
    }

    fn visit_item_const(&mut self, item: &syn::ItemConst) {
        let depth = self.cfg.len();
        self.cfg.extend(cfgs(&item.attrs));
        syn::visit::visit_item_const(self, item);
        self.cfg.truncate(depth);
    }

    fn visit_item_static(&mut self, item: &syn::ItemStatic) {
        let depth = self.cfg.len();
        self.cfg.extend(cfgs(&item.attrs));
        syn::visit::visit_item_static(self, item);
        self.cfg.truncate(depth);
    }

    fn visit_impl_item(&mut self, item: &syn::ImplItem) {
        let syn::ImplItem::Fn(f) = item else {
            syn::visit::visit_impl_item(self, item);
            return;
        };
        let depth = self.cfg.len();
        self.cfg.extend(cfgs(&f.attrs));
        let owner = self.owner.clone().expect("an enclosing impl or trait");
        self.record(
            node_span(&f.block),
            Flavor::Method {
                self_type: owner.self_type,
                visible: vis_class(&f.vis),
                nested: self.fns > 0,
            },
        );
        self.fns += 1;
        syn::visit::visit_impl_item(self, item);
        self.fns -= 1;
        self.cfg.truncate(depth);
    }

    fn visit_trait_item(&mut self, item: &syn::TraitItem) {
        let syn::TraitItem::Fn(f) = item else {
            syn::visit::visit_trait_item(self, item);
            return;
        };
        let Some(block) = f.default.as_ref() else {
            syn::visit::visit_trait_item(self, item);
            return;
        };
        let depth = self.cfg.len();
        self.cfg.extend(cfgs(&f.attrs));
        let owner = self.owner.clone().expect("an enclosing impl or trait");
        self.record(
            node_span(block),
            Flavor::TraitDefault {
                trait_name: owner.trait_name.unwrap_or_default(),
                trait_visible: owner.trait_vis,
                nested: self.fns > 0,
            },
        );
        self.fns += 1;
        syn::visit::visit_trait_item(self, item);
        self.fns -= 1;
        self.cfg.truncate(depth);
    }

    fn visit_expr_if(&mut self, expr: &syn::ExprIf) {
        self.record(node_span(&expr.then_branch), Flavor::Embedded);
        syn::visit::visit_expr_if(self, expr);
    }

    fn visit_expr_for_loop(&mut self, expr: &syn::ExprForLoop) {
        self.record(node_span(&expr.body), Flavor::Embedded);
        syn::visit::visit_expr_for_loop(self, expr);
    }

    fn visit_expr_while(&mut self, expr: &syn::ExprWhile) {
        self.record(node_span(&expr.body), Flavor::Embedded);
        syn::visit::visit_expr_while(self, expr);
    }

    fn visit_expr_loop(&mut self, expr: &syn::ExprLoop) {
        self.record(node_span(&expr.body), Flavor::Embedded);
        syn::visit::visit_expr_loop(self, expr);
    }

    fn visit_expr_block(&mut self, expr: &syn::ExprBlock) {
        self.record(node_span(expr), Flavor::Embedded);
        syn::visit::visit_expr_block(self, expr);
    }

    fn visit_expr_unsafe(&mut self, expr: &syn::ExprUnsafe) {
        self.record(node_span(expr), Flavor::Embedded);
        syn::visit::visit_expr_unsafe(self, expr);
    }

    fn visit_expr_async(&mut self, expr: &syn::ExprAsync) {
        self.record(node_span(expr), Flavor::Embedded);
        syn::visit::visit_expr_async(self, expr);
    }

    fn visit_expr_try_block(&mut self, expr: &syn::ExprTryBlock) {
        self.record(node_span(expr), Flavor::Embedded);
        syn::visit::visit_expr_try_block(self, expr);
    }

    fn visit_expr_const(&mut self, expr: &syn::ExprConst) {
        self.record(node_span(expr), Flavor::Embedded);
        syn::visit::visit_expr_const(self, expr);
    }

    fn visit_arm(&mut self, arm: &syn::Arm) {
        self.record(node_span(arm), Flavor::Embedded);
        syn::visit::visit_arm(self, arm);
    }

    fn visit_expr_closure(&mut self, closure: &syn::ExprClosure) {
        self.record(node_span(closure), Flavor::Embedded);
        syn::visit::visit_expr_closure(self, closure);
    }
}

fn context_meta(parsed: &syn::File) -> BTreeMap<SpanKey, Meta> {
    let mut walk = MetaWalk {
        chain: Vec::new(),
        cfg: Vec::new(),
        fns: 0,
        owner: None,
        out: BTreeMap::new(),
    };
    walk.visit_file(parsed);
    walk.out
}

/// The printed `cfg` attributes among `attrs`.
fn cfgs(attrs: &[syn::Attribute]) -> impl Iterator<Item = String> + '_ {
    attrs
        .iter()
        .filter(|a| a.path().is_ident("cfg"))
        .map(|a| a.to_token_stream().to_string())
}

/// The type as written, `Foo<u8>` and `a::Foo` kept whole.
fn type_text(ty: &syn::Type) -> String {
    let printed = ty.to_token_stream().to_string();
    let word = |c: Option<char>| c.is_some_and(|c| c.is_alphanumeric() || c == '_');
    let mut out = String::with_capacity(printed.len());
    let mut chars = printed.chars().peekable();
    while let Some(c) = chars.next() {
        if c != ' ' || (word(out.chars().last()) && word(chars.peek().copied())) {
            out.push(c);
        }
    }
    out
}

/// The crate model with modules, type definitions and import bindings by module path.
struct CrateModel {
    /// Modules by target-relative path.
    modules: BTreeMap<String, ModuleInfo>,
    /// Type definitions by target-relative path.
    types: BTreeMap<String, TypeDef>,
    /// Import bindings by module path, source order per module.
    bindings: BTreeMap<String, Vec<Binding>>,
    /// Whether every externally declared module resolved to a scanned file.
    resolved: bool,
}

struct ModuleInfo {
    /// The module's declared `pub`.
    visible: bool,
    /// An external declaration whose file the target carries.
    resolved: bool,
    /// The declaration's cfg attributes.
    cfg: Vec<String>,
    /// The alternatives of the module's available claims, none while unconditional.
    claims: Vec<Vec<String>>,
}

struct TypeDef {
    /// The type's declared `pub`.
    visible: bool,
    /// The definition's cfg attributes.
    cfg: Vec<String>,
}

#[derive(Clone)]
struct Binding {
    /// The alias name, `None` for a glob.
    alias: Option<String>,
    /// The written target segments.
    segments: Vec<String>,
    /// A leading `::` or `crate::`.
    rooted: bool,
    /// A bare `pub use`.
    visible: bool,
    /// The use declaration's cfg attributes.
    cfg: Vec<String>,
}

impl CrateModel {
    fn new(target: &TargetScan, layout: &CrateLayout) -> Self {
        let mut modules = BTreeMap::new();
        let file_set: BTreeSet<String> = target
            .files
            .iter()
            .map(|f| workspace_relative(&f.path, ""))
            .collect();
        let mut types = BTreeMap::new();
        let mut bindings: BTreeMap<String, Vec<Binding>> = BTreeMap::new();
        let mut resolved = true;
        for file in &target.files {
            let path = workspace_relative(&file.path, "");
            let file_decls = layout.decls.get(&path).expect("a drained file");
            let memberships = layout.memberships.get(&path).expect("a layout file");
            let items = item_defs(&file.parsed);
            for membership in memberships {
                for decl in file_decls {
                    let module = join_path(membership.module.iter().chain(decl.module.iter()));
                    match modules.entry(module) {
                        alloc::collections::btree_map::Entry::Occupied(mut entry) => {
                            let info: &mut ModuleInfo = entry.get_mut();
                            info.visible &= decl.visible;
                            info.resolved &= decl.resolved;
                        }
                        alloc::collections::btree_map::Entry::Vacant(entry) => {
                            entry.insert(ModuleInfo {
                                visible: decl.visible,
                                resolved: decl.resolved,
                                cfg: decl.cfg.clone(),
                                claims: claim_alternatives(decl, &file_set),
                            });
                        }
                    }
                    if !decl.inline && !decl.resolved {
                        resolved = false;
                    }
                }
                for (chain, def) in &items.defs {
                    let path = join_path(
                        membership
                            .module
                            .iter()
                            .chain(chain.iter())
                            .chain(core::iter::once(&def.name)),
                    );
                    types.entry(path).or_insert_with(|| TypeDef {
                        visible: def.visible,
                        cfg: def.cfg.clone(),
                    });
                }
                for (chain, binding) in &items.bindings {
                    let module = join_path(membership.module.iter().chain(chain.iter()));
                    bindings.entry(module).or_default().push(binding.clone());
                }
            }
        }
        CrateModel {
            modules,
            types,
            bindings,
            resolved,
        }
    }

    fn binding_in(&self, module: &str, name: &str) -> Option<&Binding> {
        self.bindings
            .get(module)
            .and_then(|list| list.iter().find(|b| b.alias.as_deref() == Some(name)))
    }

    /// The first declared module whose file the target does not carry.
    fn first_unresolved_module(&self) -> Option<String> {
        self.modules
            .iter()
            .find(|(_, info)| !info.resolved)
            .map(|(module, _)| module.clone())
    }

    fn binding_ancestor(&self, module: &str, name: &str) -> Option<&Binding> {
        let mut m = parent_of(module);
        while let Some(path) = m {
            if let Some(binding) = self.binding_in(&path, name) {
                return Some(binding);
            }
            m = parent_of(&path);
        }
        None
    }

    fn glob_in(&self, module: &str) -> bool {
        self.bindings
            .get(module)
            .is_some_and(|list| list.iter().any(|b| b.alias.is_none()))
    }

    /// All modules of `path` exist and are visible.
    fn chain_visible(&self, path: &str) -> bool {
        module_segments(path).iter().all(|module| {
            self.modules
                .get(module)
                .is_some_and(|i| i.visible && i.resolved)
        })
    }

    /// All modules of `path` exist, visibility unknowns included.
    fn chain_known(&self, path: &str) -> bool {
        module_segments(path)
            .iter()
            .all(|module| self.modules.contains_key(module))
    }

    /// All modules of `module` exist and are visible, the module itself included.
    fn module_chain_visible(&self, module: &str) -> bool {
        let segments = segments_of(module);
        (1..=segments.len()).all(|end| {
            self.modules
                .get(&segments[..end].join("::"))
                .is_some_and(|info| info.visible && info.resolved)
        })
    }
}

/// The alternatives of a declaration's available claim units, none while every
/// unit resolves or an available unit is unconditional.
fn claim_alternatives(decl: &Decl, file_set: &BTreeSet<String>) -> Vec<Vec<String>> {
    let mut units: Vec<Vec<String>> = Vec::new();
    for (pred, _, _) in &decl.paths {
        if !units.iter().any(|unit| unit == pred) {
            units.push(pred.clone());
        }
    }
    let available: Vec<Vec<String>> = units
        .iter()
        .filter(|unit| {
            decl.paths
                .iter()
                .any(|(pred, path, _)| pred == *unit && file_set.contains(path))
        })
        .cloned()
        .collect();
    if available.len() == units.len() || available.iter().any(alloc::vec::Vec::is_empty) {
        return Vec::new();
    }
    available
}

/// An externally declared module and where it resolves.
struct Decl {
    /// The inline chain below the file, plus the module name.
    module: Vec<String>,
    /// A declared bare `pub`.
    visible: bool,
    /// An inline module.
    inline: bool,
    /// The declaration resolves to a file the target carries.
    resolved: bool,
    /// The declaration's cfg attributes.
    cfg: Vec<String>,
    /// The claim file paths, their branch conditions and mod-rs flags.
    paths: Vec<(Vec<String>, String, bool)>,
}

/// The module path of one file membership and the alternatives of its claim conditions.
struct Membership {
    /// The module path segments.
    module: Vec<String>,
    /// The claim alternatives under which the file is linked.
    alternatives: Vec<Vec<String>>,
}

/// The file layout with declarations, module memberships and claim contexts.
struct CrateLayout {
    /// The module declarations of every file, keyed by file path.
    decls: BTreeMap<String, Vec<Decl>>,
    /// The module memberships and branch conditions of each file, the discovered segments first.
    memberships: BTreeMap<String, Vec<Membership>>,
}

/// The directory context a file's module declarations resolve against.
#[derive(Clone)]
struct FileClaim {
    /// The directory of implicit child files.
    base: String,
    /// The directory of `#[path]` child files.
    dir: String,
}

fn crate_layout(target: &TargetScan) -> CrateLayout {
    let file_set: BTreeSet<String> = target
        .files
        .iter()
        .map(|f| workspace_relative(&f.path, ""))
        .collect();
    let file_index: BTreeMap<String, usize> = target
        .files
        .iter()
        .enumerate()
        .map(|(index, f)| (workspace_relative(&f.path, ""), index))
        .collect();
    let mut decls = BTreeMap::new();
    let mut memberships: BTreeMap<String, Vec<Membership>> = BTreeMap::new();
    let mut contexts: BTreeMap<String, FileClaim> = BTreeMap::new();
    let mut queue: VecDeque<String> = VecDeque::new();
    for file in &target.files {
        let path = workspace_relative(&file.path, "");
        if !memberships.contains_key(&path) {
            memberships.insert(
                path.clone(),
                alloc::vec![Membership {
                    module: file.segments.clone(),
                    alternatives: Vec::new(),
                }],
            );
        }
        if file.segments.is_empty() {
            let dir = dir_of(&path);
            if contexts
                .insert(
                    path.clone(),
                    FileClaim {
                        base: dir.clone(),
                        dir,
                    },
                )
                .is_none()
            {
                queue.push_back(path);
            }
        }
    }
    drain_queue(
        target,
        &file_set,
        &file_index,
        &mut decls,
        &mut memberships,
        &mut contexts,
        &mut queue,
    );
    let unclaimed: Vec<String> = memberships
        .keys()
        .filter(|path| !decls.contains_key(*path))
        .cloned()
        .collect();
    for path in unclaimed {
        let index = *file_index.get(&path).expect("a layout file");
        let file = &target.files[index];
        let dir = dir_of(&path);
        let claim = if file.segments.is_empty() || path.ends_with("/mod.rs") {
            FileClaim {
                base: dir.clone(),
                dir: dir.clone(),
            }
        } else {
            FileClaim {
                base: join_dir(&dir, stem_of(&path)),
                dir: dir.clone(),
            }
        };
        if contexts.insert(path.clone(), claim).is_none() {
            queue.push_back(path);
        }
    }
    drain_queue(
        target,
        &file_set,
        &file_index,
        &mut decls,
        &mut memberships,
        &mut contexts,
        &mut queue,
    );
    CrateLayout { decls, memberships }
}

/// Process queued files by collecting their declarations and following their claims.
fn drain_queue(
    target: &TargetScan,
    file_set: &BTreeSet<String>,
    file_index: &BTreeMap<String, usize>,
    decls: &mut BTreeMap<String, Vec<Decl>>,
    memberships: &mut BTreeMap<String, Vec<Membership>>,
    contexts: &mut BTreeMap<String, FileClaim>,
    queue: &mut VecDeque<String>,
) {
    while let Some(path) = queue.pop_front() {
        let index = *file_index.get(&path).expect("an enqueued file");
        let file = &target.files[index];
        let claim = contexts.get(&path).expect("an enqueued context").clone();
        let mut walk = DeclWalk {
            chain: Vec::new(),
            base: alloc::vec![claim.base.clone()],
            dir: alloc::vec![claim.dir.clone()],
            pred: alloc::vec![Vec::new()],
            file_set,
            out: Vec::new(),
        };
        walk.visit_file(&file.parsed);
        let own = walk.out;
        for decl in &own {
            if decl.inline {
                continue;
            }
            for (branch, claim_path, mod_rs) in &decl.paths {
                if !file_set.contains(claim_path) {
                    continue;
                }
                let entry = memberships.entry(claim_path.clone()).or_default();
                match entry.iter_mut().find(|m| m.module == decl.module) {
                    Some(existing) => {
                        if !existing.alternatives.contains(branch) {
                            existing.alternatives.push(branch.clone());
                        }
                    }
                    None => entry.push(Membership {
                        module: decl.module.clone(),
                        alternatives: alloc::vec![branch.clone()],
                    }),
                }
                if contexts.contains_key(claim_path) {
                    continue;
                }
                let dir = dir_of(claim_path);
                contexts.insert(
                    claim_path.clone(),
                    FileClaim {
                        base: if *mod_rs {
                            dir.clone()
                        } else {
                            join_dir(&dir, stem_of(claim_path))
                        },
                        dir,
                    },
                );
                queue.push_back(claim_path.clone());
            }
        }
        decls.insert(path, own);
    }
}

/// The `mod` declarations of one parsed file, with their claim paths.
struct DeclWalk<'a> {
    chain: Vec<String>,
    base: Vec<String>,
    dir: Vec<String>,
    /// The accumulated condition of each context, parallel to `base` and `dir`.
    pred: Vec<Vec<String>>,
    file_set: &'a BTreeSet<String>,
    out: Vec<Decl>,
}

impl<'a> Visit<'a> for DeclWalk<'a> {
    fn visit_item_mod(&mut self, item: &'a syn::ItemMod) {
        let name = item.ident.unraw().to_string();
        let depth = self.chain.len();
        self.chain.push(item.ident.to_string());
        if let Some((_, items)) = &item.content {
            self.inline_mod(item, &name, items, depth);
        } else {
            self.file_mod(item, &name, depth);
        }
    }
}

impl<'a> DeclWalk<'a> {
    fn inline_mod(
        &mut self,
        item: &'a syn::ItemMod,
        name: &str,
        items: &'a [syn::Item],
        depth: usize,
    ) {
        self.out.push(Decl {
            module: self.chain.clone(),
            visible: matches!(item.vis, syn::Visibility::Public(_)),
            inline: true,
            resolved: true,
            cfg: cfgs(&item.attrs).collect(),
            paths: Vec::new(),
        });
        let claimed = path_claims(&item.attrs, &claim_atom);
        let mut inner_base: Vec<String> = Vec::new();
        let mut inner_dir: Vec<String> = Vec::new();
        let mut inner_pred: Vec<Vec<String>> = Vec::new();
        let mut push_context = |context: String, pred: Vec<String>| {
            if !inner_dir.contains(&context) {
                inner_base.push(context.clone());
                inner_dir.push(context);
                inner_pred.push(pred);
            }
        };
        for ((base, dir), outer) in self.base.iter().zip(&self.dir).zip(&self.pred) {
            let context = if let Some(path) = &claimed.direct {
                lexical_join(dir, path)
            } else {
                join_dir(base, name)
            };
            let dir_pred = if claimed.direct.is_some() {
                &claimed.direct_pred
            } else {
                &claimed.fallback
            };
            push_context(
                context,
                outer
                    .iter()
                    .cloned()
                    .chain(dir_pred.iter().cloned())
                    .collect(),
            );
            for (branch, path) in &claimed.branches {
                push_context(
                    lexical_join(dir, path),
                    outer
                        .iter()
                        .cloned()
                        .chain(branch.iter().cloned())
                        .collect(),
                );
            }
        }
        let (previous_base, previous_dir, previous_pred) =
            (self.base.clone(), self.dir.clone(), self.pred.clone());
        self.base = inner_base;
        self.dir = inner_dir;
        self.pred = inner_pred;
        for child in items {
            syn::visit::visit_item(self, child);
        }
        self.base = previous_base;
        self.dir = previous_dir;
        self.pred = previous_pred;
        self.chain.truncate(depth);
    }

    fn file_mod(&mut self, item: &'a syn::ItemMod, name: &str, depth: usize) {
        let cfg: Vec<String> = cfgs(&item.attrs).collect();
        let claimed = path_claims(&item.attrs, &claim_atom);
        let mut claims: Vec<(Vec<String>, String, bool)> = Vec::new();
        let mut seen: BTreeSet<(Vec<String>, String, bool)> = BTreeSet::new();
        let add = |claims: &mut Vec<(Vec<String>, String, bool)>,
                   seen: &mut BTreeSet<(Vec<String>, String, bool)>,
                   pred: Vec<String>,
                   claim: String,
                   mod_rs: bool| {
            if seen.insert((pred.clone(), claim.clone(), mod_rs)) {
                claims.push((pred, claim, mod_rs));
            }
        };
        for ((base, dir), outer) in self.base.iter().zip(&self.dir).zip(&self.pred) {
            let join =
                |pred: &[String]| outer.iter().cloned().chain(pred.iter().cloned()).collect();
            if let Some(path) = &claimed.direct {
                add(
                    &mut claims,
                    &mut seen,
                    join(&claimed.direct_pred),
                    lexical_join(dir, path),
                    true,
                );
            } else {
                add(
                    &mut claims,
                    &mut seen,
                    join(&claimed.fallback),
                    join_dir(base, &format!("{name}.rs")),
                    false,
                );
                add(
                    &mut claims,
                    &mut seen,
                    join(&claimed.fallback),
                    join_dir(base, &format!("{name}/mod.rs")),
                    true,
                );
            }
            for (pred, path) in &claimed.branches {
                add(
                    &mut claims,
                    &mut seen,
                    join(pred),
                    lexical_join(dir, path),
                    true,
                );
            }
        }
        self.out.push(Decl {
            module: self.chain.clone(),
            visible: matches!(item.vis, syn::Visibility::Public(_)),
            inline: false,
            resolved: claims
                .iter()
                .any(|(_, path, _)| self.file_set.contains(path)),
            cfg,
            paths: claims,
        });
        self.chain.truncate(depth);
    }
}

/// One `cfg_attr` predicate as a context condition.
fn claim_atom(pred: &syn::Meta) -> String {
    format!("cfg({})", pred.to_token_stream())
}

/// Type definitions and import bindings at every module depth of one file.
struct ItemDefs {
    defs: Vec<(Vec<String>, ItemDef)>,
    bindings: Vec<(Vec<String>, Binding)>,
}

struct ItemDef {
    name: String,
    visible: bool,
    cfg: Vec<String>,
}

/// The walk that records type definitions and import bindings.
struct DefWalk {
    chain: Vec<String>,
    out: ItemDefs,
}

impl DefWalk {
    fn def_item(&mut self, name: &syn::Ident, visible: bool, attrs: &[syn::Attribute]) {
        self.out.defs.push((
            self.chain.clone(),
            ItemDef {
                name: name.to_string(),
                visible,
                cfg: cfgs(attrs).collect(),
            },
        ));
    }
}

impl Visit<'_> for DefWalk {
    fn visit_item_mod(&mut self, item: &syn::ItemMod) {
        let depth = self.chain.len();
        self.chain.push(item.ident.to_string());
        syn::visit::visit_item_mod(self, item);
        self.chain.truncate(depth);
    }

    /// Nothing inside a block is recorded, so the walk stops here.
    fn visit_block(&mut self, _: &syn::Block) {}

    fn visit_item_struct(&mut self, item: &syn::ItemStruct) {
        self.def_item(
            &item.ident,
            matches!(item.vis, syn::Visibility::Public(_)),
            &item.attrs,
        );
        syn::visit::visit_item_struct(self, item);
    }

    fn visit_item_enum(&mut self, item: &syn::ItemEnum) {
        self.def_item(
            &item.ident,
            matches!(item.vis, syn::Visibility::Public(_)),
            &item.attrs,
        );
        syn::visit::visit_item_enum(self, item);
    }

    fn visit_item_union(&mut self, item: &syn::ItemUnion) {
        self.def_item(
            &item.ident,
            matches!(item.vis, syn::Visibility::Public(_)),
            &item.attrs,
        );
        syn::visit::visit_item_union(self, item);
    }

    fn visit_item_type(&mut self, item: &syn::ItemType) {
        self.def_item(
            &item.ident,
            matches!(item.vis, syn::Visibility::Public(_)),
            &item.attrs,
        );
        syn::visit::visit_item_type(self, item);
    }

    fn visit_item_use(&mut self, item: &syn::ItemUse) {
        let visible = matches!(item.vis, syn::Visibility::Public(_));
        let cfg: Vec<String> = cfgs(&item.attrs).collect();
        for binding in use_bindings(item) {
            self.out.bindings.push((
                self.chain.clone(),
                Binding {
                    visible,
                    cfg: cfg.clone(),
                    ..binding
                },
            ));
        }
        // Imports are bound by their enclosing scope and the walk stops here.
    }
}

fn item_defs(parsed: &syn::File) -> ItemDefs {
    let mut walk = DefWalk {
        chain: Vec::new(),
        out: ItemDefs {
            defs: Vec::new(),
            bindings: Vec::new(),
        },
    };
    walk.visit_file(parsed);
    walk.out
}

/// The leaf bindings of one `use` tree.
fn use_bindings(item: &syn::ItemUse) -> Vec<Binding> {
    let mut out = Vec::new();
    use_leaf(item.leading_colon.is_some(), &[], &item.tree, &mut out);
    out
}

fn use_leaf(rooted: bool, prefix: &[String], tree: &syn::UseTree, out: &mut Vec<Binding>) {
    match tree {
        syn::UseTree::Path(path) => {
            let mut prefix = prefix.to_vec();
            prefix.push(path.ident.to_string());
            use_leaf(rooted, &prefix, &path.tree, out);
        }
        syn::UseTree::Name(name) => {
            let mut segments = prefix.to_vec();
            segments.push(name.ident.to_string());
            out.push(Binding {
                alias: Some(name.ident.to_string()),
                segments,
                rooted,
                visible: false,
                cfg: Vec::new(),
            });
        }
        syn::UseTree::Rename(rename) => {
            let mut segments = prefix.to_vec();
            segments.push(rename.ident.to_string());
            out.push(Binding {
                alias: Some(rename.rename.to_string()),
                segments,
                rooted,
                visible: false,
                cfg: Vec::new(),
            });
        }
        syn::UseTree::Glob(_) => {
            out.push(Binding {
                alias: None,
                segments: prefix.to_vec(),
                rooted,
                visible: false,
                cfg: Vec::new(),
            });
        }
        syn::UseTree::Group(group) => {
            for tree in &group.items {
                use_leaf(rooted, prefix, tree, out);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::context_scope::ContextScope;
    use crate::{ContextKind, SourceFile, TargetScan};
    use alloc::vec;

    fn file(path: &str, segments: &[&str], code: &str) -> SourceFile {
        SourceFile {
            path: path.to_string(),
            segments: segments.iter().map(ToString::to_string).collect(),
            cfg: Vec::new(),
            parsed: syn::parse_file(code).unwrap(),
            text: code.to_string(),
            rustdoc: true,
        }
    }

    fn target(files: &[SourceFile], library: bool) -> TargetScan {
        TargetScan {
            name: "app".into(),
            library,
            files: files.to_vec(),
        }
    }

    fn records(code: &str) -> Vec<IndexedContext> {
        let file = file("src/lib.rs", &[], code);
        extract(&target(&[file], true), "", &|_| true)
    }

    fn one<'a>(record: &'a [IndexedContext], module: &str) -> &'a IndexedContext {
        record
            .iter()
            .find(|r| r.module == module)
            .unwrap_or_else(|| {
                panic!(
                    "no record for {module}: {:?}",
                    record.iter().map(|r| r.module.as_str()).collect::<Vec<_>>()
                )
            })
    }

    #[test]
    fn records_carry_form_tokens_module_and_site() {
        let out = records("pub fn helper(x: u32) -> u32 { x + 1u32 }");
        assert_eq!(out.len(), 1);
        let record = &out[0];
        assert_eq!(record.site.file, "src/lib.rs");
        assert_eq!(record.site.item, "app::helper");
        assert_eq!(record.module, "app");
        assert_eq!(record.crate_name, "app");
        assert_eq!(record.crate_root, "src/lib.rs");
        assert_eq!(record.access, ContextAccess::PublicFunction);
        assert_eq!(record.api_path.as_deref(), Some("app::helper"));
        assert_eq!(record.conditions, Vec::<String>::new());
        assert_eq!(record.extraction_notes, Vec::<String>::new());
    }

    #[test]
    fn private_module_function_is_internal() {
        let out = records("mod inner { pub fn helper(x: u32) -> u32 { x + 1u32 } }");
        let record = one(&out, "app::inner");
        assert_eq!(record.access, ContextAccess::InternalFunction);
        assert_eq!(record.api_path, None);
    }

    #[test]
    fn pub_reexport_restores_a_public_route() {
        let out = records(
            "mod inner { pub fn helper(x: u32) -> u32 { x + 1u32 } }\npub use inner::helper;",
        );
        let record = one(&out, "app::inner");
        assert_eq!(record.access, ContextAccess::PublicFunction);
        assert_eq!(record.api_path.as_deref(), Some("app::helper"));
        // The original site item keeps the private-module path as evidence.
        assert_eq!(record.site.item, "app::inner::helper");
    }

    #[test]
    fn reexport_on_a_private_chain_stays_internal() {
        let out = records(
            "mod inner { pub fn helper(x: u32) -> u32 { x + 1u32 } }\nmod api { use super::inner::helper; }",
        );
        let record = one(&out, "app::inner");
        assert_eq!(record.access, ContextAccess::InternalFunction);
    }

    #[test]
    fn pub_reexport_in_a_private_module_stays_internal() {
        let out = records(
            "mod inner { pub fn helper(x: u32) -> u32 { x + 1u32 } }\nmod api { pub use super::inner::helper; }",
        );
        let record = one(&out, "app::inner");
        assert_eq!(record.access, ContextAccess::InternalFunction);
        assert_eq!(record.api_path, None);
        assert_eq!(record.conditions, Vec::<String>::new());
    }

    #[test]
    fn reexport_through_a_public_module_restores_the_route() {
        let out = records(
            "mod inner { pub fn helper(x: u32) -> u32 { x + 1u32 } }\npub mod api { pub use super::inner::helper; }",
        );
        let record = one(&out, "app::inner");
        assert_eq!(record.access, ContextAccess::PublicFunction);
        assert_eq!(record.api_path.as_deref(), Some("app::api::helper"));
    }

    #[test]
    fn module_reexports_route_the_items_inside() {
        let inner = "mod inner { pub mod deep { pub mod sub { pub fn helper(x: u32) -> u32 { x + 1u32 } } } mod hidden { pub fn secret(x: u32) -> u32 { x + 2u32 } } }";
        for (uses, module, route) in [
            (
                "pub use inner::deep;",
                "app::inner::deep::sub",
                Some("app::deep::sub::helper"),
            ),
            (
                "pub use inner::deep as alias;",
                "app::inner::deep::sub",
                Some("app::alias::sub::helper"),
            ),
            (
                "pub use inner::deep::sub;",
                "app::inner::deep::sub",
                Some("app::sub::helper"),
            ),
            (
                "pub use inner::*;",
                "app::inner::deep::sub",
                Some("app::deep::sub::helper"),
            ),
            (
                "pub use inner::deep::*;",
                "app::inner::deep::sub",
                Some("app::sub::helper"),
            ),
            ("pub use inner::*;", "app::inner::hidden", None),
            ("pub use inner::deep;", "app::inner::hidden", None),
        ] {
            let out = records(&format!("{inner}\n{uses}"));
            let record = one(&out, module);
            assert_eq!(record.api_path.as_deref(), route, "{uses} {module}");
            let access = if route.is_some() {
                ContextAccess::PublicFunction
            } else {
                ContextAccess::InternalFunction
            };
            assert_eq!(record.access, access, "{uses} {module}");
        }
    }

    #[test]
    fn a_method_on_a_type_in_a_reexported_module_is_public() {
        let out = records(
            "mod inner { pub mod deep { pub struct Pack; impl Pack { pub fn size(&self) -> u32 { 1u32 } } } }\npub use inner::deep;",
        );
        let record = one(&out, "app::inner::deep");
        assert_eq!(record.access, ContextAccess::PublicMethod);
        assert_eq!(record.api_path.as_deref(), Some("app::deep::Pack::size"));
    }

    #[test]
    fn a_module_public_under_one_cfg_only_is_not_public() {
        let out = records(
            "#[cfg(unix)]\npub mod m { pub fn helper(x: u32) -> u32 { x + 1u32 } }\n#[cfg(not(unix))]\nmod m { pub fn helper(x: u32) -> u32 { x + 2u32 } }",
        );
        for record in out.iter().filter(|record| record.module == "app::m") {
            assert_ne!(record.access, ContextAccess::PublicFunction, "{record:?}");
            assert_eq!(record.api_path, None, "{record:?}");
        }
    }

    #[test]
    fn restricted_pub_is_not_an_external_route() {
        let out = records("pub(crate) fn helper(x: u32) -> u32 { x + 1u32 }");
        let record = &out[0];
        assert_eq!(record.access, ContextAccess::InternalFunction);
        assert_eq!(record.api_path, None);
    }

    #[test]
    fn method_on_a_public_type_is_public() {
        let out = records("pub struct Box;\nimpl Box { pub fn pack(&self) -> u32 { 1u32 } }");
        let record = &out[0];
        assert_eq!(record.access, ContextAccess::PublicMethod);
        assert_eq!(record.api_path.as_deref(), Some("app::Box::pack"));
    }

    #[test]
    fn method_on_an_internal_type_is_internal() {
        let out = records("struct Box;\nimpl Box { pub fn pack(&self) -> u32 { 1u32 } }");
        let record = &out[0];
        assert_eq!(record.access, ContextAccess::InternalMethod);
        assert!(
            record
                .extraction_notes
                .iter()
                .any(|note| note.contains("internal to the crate"))
        );
    }

    #[test]
    fn method_on_a_foreign_type_is_unresolved() {
        let out = records("impl External { pub fn pack(&self) -> u32 { 1u32 } }");
        let record = &out[0];
        assert_eq!(record.access, ContextAccess::Unresolved);
        assert!(
            record
                .extraction_notes
                .iter()
                .any(|note| note.contains("External"))
        );
    }

    #[test]
    fn method_receiver_resolves_across_files_through_an_import() {
        let files = vec![
            file("src/lib.rs", &[], "pub struct Box;\npub mod store;"),
            file(
                "src/store.rs",
                &["store"],
                "use crate::Box;\nimpl Box { pub fn pack(&self) -> u32 { 1u32 } }",
            ),
        ];
        let out = extract(&target(&files, true), "", &|_| true);
        let record = one(&out, "app::store");
        assert_eq!(record.access, ContextAccess::PublicMethod);
        assert_eq!(record.api_path.as_deref(), Some("app::Box::pack"));
    }

    #[test]
    fn trait_defaults_follow_the_trait_visibility() {
        let pub_trait = records("pub trait Seal { fn stamp(&self) -> u32 { 1u32 } }");
        assert_eq!(one(&pub_trait, "app").access, ContextAccess::PublicMethod);
        assert_eq!(
            one(&pub_trait, "app").api_path.as_deref(),
            Some("app::Seal::stamp")
        );
        let private_trait = records("trait Seal { fn stamp(&self) -> u32 { 1u32 } }");
        assert_eq!(
            one(&private_trait, "app").access,
            ContextAccess::InternalMethod
        );
        let reexported = records(
            "mod inner { pub trait Seal { fn stamp(&self) -> u32 { 1u32 } } }\npub use inner::Seal;",
        );
        let record = one(&reexported, "app::inner");
        assert_eq!(record.access, ContextAccess::PublicMethod);
        assert_eq!(record.api_path.as_deref(), Some("app::Seal::stamp"));
    }

    #[test]
    fn nested_functions_are_internal() {
        let out = records(
            "pub fn outer(x: u32) -> u32 { fn inner(y: u32) -> u32 { y + 1u32 } inner(x) }",
        );
        let inner = out
            .iter()
            .find(|r| r.site.item == "app::outer::inner")
            .unwrap();
        let outer = out.iter().find(|r| r.site.item == "app::outer").unwrap();
        assert_eq!(outer.access, ContextAccess::PublicFunction);
        assert_eq!(inner.access, ContextAccess::InternalFunction);
        assert!(
            inner
                .extraction_notes
                .iter()
                .any(|note| note.contains("nested"))
        );
    }

    #[test]
    fn bin_targets_are_unresolved() {
        let file = file(
            "src/main.rs",
            &[],
            "pub fn helper(x: u32) -> u32 { x + 1u32 }",
        );
        let out = extract(&target(&[file], false), "", &|_| true);
        assert_eq!(out[0].access, ContextAccess::Unresolved);
        assert!(
            out[0]
                .extraction_notes
                .iter()
                .any(|note| note.contains("not a library"))
        );
    }

    #[test]
    fn unresolvable_module_keeps_access_unresolved() {
        let files = vec![
            file("src/lib.rs", &[], "pub mod leaf;\npub mod missing;"),
            file(
                "src/leaf.rs",
                &["leaf"],
                "fn helper(x: u32) -> u32 { x + 1u32 }",
            ),
        ];
        let out = extract(&target(&files, true), "", &|_| true);
        let record = one(&out, "app::leaf");
        assert_eq!(record.access, ContextAccess::Unresolved);
        assert!(
            record
                .extraction_notes
                .iter()
                .any(|note| note.contains("missing"))
        );
    }

    #[test]
    fn resolved_private_function_ignores_unrelated_missing_modules() {
        let files = vec![
            file(
                "src/lib.rs",
                &[],
                "pub mod leaf;\npub mod missing;\npub fn helper(x: u32) -> u32 { x + 1u32 }",
            ),
            file("src/leaf.rs", &["leaf"], ""),
        ];
        let out = extract(&target(&files, true), "", &|_| true);
        let helper = out.iter().find(|r| r.site.item == "app::helper").unwrap();
        assert_eq!(helper.access, ContextAccess::PublicFunction);
    }

    #[test]
    fn cfg_conditions_retain_the_enclosing_branches() {
        let out = records(
            "#[cfg(unix)]\nmod inner {\n    #[cfg(feature = \"extra\")]\n    pub fn helper(x: u32) -> u32 { x + 1u32 }\n}",
        );
        let record = one(&out, "app::inner");
        assert_eq!(record.conditions.len(), 2);
        assert!(record.conditions.iter().any(|c| c.contains("unix")));
        assert!(record.conditions.iter().any(|c| c.contains("feature")));
    }

    #[test]
    fn cfg_attr_branches_condition_the_public_routes() {
        let files = vec![
            file(
                "src/lib.rs",
                &[],
                "#[cfg_attr(feature = \"alternate\", path = \"alternate.rs\")]\npub mod m;\npub fn helper(x: u32) -> u32 { x + 1u32 }\n",
            ),
            file(
                "src/m.rs",
                &["m"],
                "pub fn helper(x: u32) -> u32 { x + 1u32 }\n",
            ),
            file(
                "src/alternate.rs",
                &["m"],
                "pub fn helper(x: u32) -> u32 { x + 1u32 }\n",
            ),
        ];
        let out = extract(&target(&files, true), "", &|_| true);
        let default = out
            .iter()
            .find(|r| r.site.file == "src/m.rs" && r.module == "app::m")
            .unwrap();
        let branch = out
            .iter()
            .find(|r| r.site.file == "src/alternate.rs" && r.module == "app::m")
            .unwrap();
        assert_eq!(default.access, ContextAccess::PublicFunction);
        assert_eq!(branch.access, ContextAccess::PublicFunction);
        assert_eq!(default.api_path.as_deref(), Some("app::m::helper"));
        assert_eq!(branch.api_path.as_deref(), Some("app::m::helper"));
        assert_eq!(default.conditions, ["not(cfg(feature = \"alternate\"))"]);
        assert_eq!(branch.conditions, ["cfg(feature = \"alternate\")"]);
    }

    #[test]
    fn a_direct_path_before_a_branch_wins_every_configuration() {
        let files = vec![
            file(
                "src/lib.rs",
                &[],
                "#[path = \"base.rs\"]\n#[cfg_attr(feature = \"alternate\", path = \"alternate.rs\")]\npub mod m;\n",
            ),
            file(
                "src/base.rs",
                &["m"],
                "pub fn helper(x: u32) -> u32 { x + 1u32 }\n",
            ),
            file(
                "src/alternate.rs",
                &["m"],
                "pub fn helper(x: u32) -> u32 { x + 1u32 }\n",
            ),
        ];
        let out = extract(&target(&files, true), "", &|_| true);
        let base = out
            .iter()
            .find(|r| r.site.file == "src/base.rs" && r.module == "app::m")
            .unwrap();
        let branch = out
            .iter()
            .find(|r| r.site.file == "src/alternate.rs" && r.module == "app::m")
            .unwrap();
        assert_eq!(base.access, ContextAccess::PublicFunction);
        assert_eq!(branch.access, ContextAccess::Unresolved);
        assert_eq!(base.api_path.as_deref(), Some("app::m::helper"));
        assert_eq!(branch.api_path, None);
        assert_eq!(base.conditions, Vec::<String>::new());
        assert_eq!(
            branch.conditions,
            ["all(cfg(feature = \"alternate\"), false)"]
        );
        assert!(
            branch
                .extraction_notes
                .iter()
                .any(|note| note.contains("shadowed"))
        );
    }

    #[test]
    fn earlier_branches_exclude_later_ones_selecting_the_same_file() {
        let files = vec![
            file(
                "src/lib.rs",
                &[],
                "#[cfg_attr(feature = \"a\", path = \"x.rs\")]\n#[cfg_attr(feature = \"b\", path = \"x.rs\")]\npub mod m;\n",
            ),
            file(
                "src/m.rs",
                &["m"],
                "pub fn helper(x: u32) -> u32 { x + 1u32 }\n",
            ),
            file(
                "src/x.rs",
                &["m"],
                "pub fn helper(x: u32) -> u32 { x + 1u32 }\n",
            ),
        ];
        let out = extract(&target(&files, true), "", &|_| true);
        let default = out
            .iter()
            .find(|r| r.site.file == "src/m.rs" && r.module == "app::m")
            .unwrap();
        let branch = out
            .iter()
            .find(|r| r.site.file == "src/x.rs" && r.module == "app::m")
            .unwrap();
        assert_eq!(
            default.conditions,
            ["all(not(cfg(feature = \"a\")), not(cfg(feature = \"b\")))"]
        );
        assert_eq!(
            branch.conditions,
            ["any(cfg(feature = \"a\"), all(cfg(feature = \"b\"), not(cfg(feature = \"a\"))))"]
        );
    }

    #[test]
    fn inline_module_children_claim_every_branch_directory() {
        let files = vec![
            file(
                "src/lib.rs",
                &[],
                "#[cfg_attr(feature = \"alt\", path = \"alt/m.rs\")]\npub mod m {\n    pub mod child;\n}\n",
            ),
            file(
                "src/m/child.rs",
                &["m", "child"],
                "pub fn helper(x: u32) -> u32 { x + 1u32 }\n",
            ),
            file(
                "src/alt/child.rs",
                &["m", "child"],
                "pub fn helper(x: u32) -> u32 { x + 1u32 }\n",
            ),
        ];
        let out = extract(&target(&files, true), "", &|_| true);
        let site_files: Vec<&str> = out.iter().map(|r| r.site.file.as_str()).collect();
        assert!(site_files.contains(&"src/m/child.rs"));
        assert!(site_files.contains(&"src/alt/child.rs"));
        assert_eq!(
            out.iter().filter(|r| r.module == "app::m::child").count(),
            2
        );
    }

    #[test]
    fn a_reexport_route_carries_the_branch_conditions_of_its_module() {
        let files = vec![
            file(
                "src/lib.rs",
                &[],
                "#[cfg_attr(feature = \"alt\", path = \"alt_api.rs\")]\nmod api;\npub use api::helper;\n",
            ),
            file(
                "src/api.rs",
                &["api"],
                "pub fn helper(x: u32) -> u32 { x + 1u32 }\n",
            ),
        ];
        let out = extract(&target(&files, true), "", &|_| true);
        let record = one(&out, "app::api");
        assert_eq!(record.access, ContextAccess::PublicFunction);
        assert_eq!(record.api_path.as_deref(), Some("app::helper"));
        assert_eq!(record.conditions, ["not(cfg(feature = \"alt\"))"]);
    }

    #[test]
    fn embedded_contexts_are_classified_embedded() {
        let out = records(
            "pub fn outer(x: u32) -> u32 {\n    let body = { x + 1u32 };\n    let pick = |y: u32| y + 1u32;\n    let arm = match x { _ => { x + 1u32 } };\n    arm + pick(body) + body\n}",
        );
        let outer = out.iter().find(|r| r.site.item == "app::outer").unwrap();
        assert_eq!(outer.access, ContextAccess::PublicFunction);
        assert_eq!(outer.api_path.as_deref(), Some("app::outer"));
        let embedded = out
            .iter()
            .filter(|r| r.access == ContextAccess::Embedded)
            .count();
        assert_eq!(embedded, 4);
        assert!(out.iter().all(|r| r.module == "app"));
        assert!(
            out.iter()
                .filter(|r| r.site.kind != ContextKind::FunctionBody)
                .all(|r| r.access == ContextAccess::Embedded)
        );
    }

    #[test]
    fn module_level_const_block_is_embedded() {
        let out = records("const SUM: u32 = { 1u32 + 1u32 };");
        assert_eq!(out.len(), 1);
        assert_eq!(out[0].access, ContextAccess::Embedded);
        assert_eq!(out[0].site.item, "app::SUM");
    }

    #[test]
    fn extract_keeps_sub_floor_records() {
        let out = records("fn tiny() -> u32 { 1u32 }");
        assert_eq!(out.len(), 1);
        assert!(out[0].tokens < 30);
    }

    #[test]
    fn aliased_module_memberships_select_and_route() {
        let files = vec![
            file(
                "src/lib.rs",
                &[],
                "mod a;\n#[path = \"a.rs\"]\npub mod b;\npub use b::helper;",
            ),
            file(
                "src/a.rs",
                &["a"],
                "pub fn helper(x: u32) -> u32 { x + 1u32 }",
            ),
        ];
        let out = extract(&target(&files, true), "", &|_| true);
        assert_eq!(out.len(), 2);
        let by_a = one(&out, "app::a");
        let by_b = one(&out, "app::b");
        assert_eq!(by_a.access, ContextAccess::InternalFunction);
        assert_eq!(by_b.access, ContextAccess::PublicFunction);
        assert_eq!(by_b.api_path.as_deref(), Some("app::b::helper"));
        assert_eq!(by_a.site.file, by_b.site.file);
        assert_eq!(by_a.site.line, by_b.site.line);
        let exact_a = ContextScope::ModuleExact("app::a".to_string());
        let exact_b = ContextScope::ModuleExact("app::b".to_string());
        assert!(out.iter().any(|r| exact_a.matches(r)));
        assert!(
            !out.iter()
                .any(|r| ContextScope::ModuleExact("app::c".to_string()).matches(r))
        );
        assert!(out.iter().any(|r| exact_b.matches(r)));
    }

    #[test]
    fn shared_file_records_keep_their_crate() {
        let file = file(
            "src/shared.rs",
            &[],
            "pub fn helper(x: u32) -> u32 { x + 1u32 }",
        );
        let first_target = TargetScan {
            name: "one".into(),
            library: true,
            files: vec![file.clone()],
        };
        let two = TargetScan {
            name: "two".into(),
            library: true,
            files: vec![file],
        };
        let first = extract(&first_target, "", &|_| true);
        let second = extract(&two, "", &|_| true);
        assert_eq!(first[0].crate_name, "one");
        assert_eq!(second[0].crate_name, "two");
        assert_eq!(first[0].site.file, second[0].site.file);
        assert_eq!(first[0].site.line, second[0].site.line);
        assert_eq!(first[0].site.column, second[0].site.column);
        assert_eq!(first[0].site.end, second[0].site.end);
        assert_eq!(first[0].site.end_column, second[0].site.end_column);
        assert_eq!(first[0].site.kind, second[0].site.kind);
        assert_eq!(first[0].site.item, "one::helper");
        assert_eq!(second[0].site.item, "two::helper");
    }
    #[test]
    fn nested_cfg_attr_module_paths_resolve_and_report_their_condition_chain() {
        let files = vec![
            file(
                "src/lib.rs",
                &[],
                "#[cfg_attr(unix, cfg_attr(feature = \"alt\", path = \"alt_leaf.rs\"))] pub mod leaf;\npub fn root_fn(x: u32) -> u32 { x * 2u32 }",
            ),
            file(
                "src/alt_leaf.rs",
                &["leaf"],
                "pub fn helper(x: u32) -> u32 { x + 1u32 }",
            ),
        ];
        let out = extract(&target(&files, true), "", &|_| true);
        let record = one(&out, "app::leaf");
        assert_eq!(record.site.file, "src/alt_leaf.rs");
        assert_eq!(record.access, ContextAccess::PublicFunction);
        assert_eq!(record.api_path.as_deref(), Some("app::leaf::helper"));
        assert_eq!(
            record.conditions,
            vec!["all(cfg(unix), cfg(feature = \"alt\"))"]
        );
    }

    #[test]
    fn nested_cfg_attr_inline_directories_resolve_and_report_their_condition_chain() {
        let files = vec![
            file(
                "src/lib.rs",
                &[],
                "#[cfg_attr(unix, cfg_attr(feature = \"alt\", path = \"altbox\"))] pub mod boxy { pub mod child; }",
            ),
            file(
                "src/altbox/child.rs",
                &["boxy", "child"],
                "pub fn helper(x: u32) -> u32 { x + 1u32 }",
            ),
        ];
        let out = extract(&target(&files, true), "", &|_| true);
        let record = one(&out, "app::boxy::child");
        assert_eq!(record.site.file, "src/altbox/child.rs");
        assert_eq!(record.access, ContextAccess::PublicFunction);
        assert_eq!(record.api_path.as_deref(), Some("app::boxy::child::helper"));
        assert_eq!(
            record.conditions,
            vec!["all(cfg(unix), cfg(feature = \"alt\"))"]
        );
    }
    #[test]
    fn a_branch_after_a_direct_path_is_never_linked() {
        let files = vec![
            file(
                "src/lib.rs",
                &[],
                "#[path = \"main_leaf.rs\"]\n#[cfg_attr(unix, path = \"alt_leaf.rs\")]\npub mod leaf;\npub fn root_fn(x: u32) -> u32 { x * 2u32 }",
            ),
            file(
                "src/main_leaf.rs",
                &["leaf"],
                "pub fn helper(x: u32) -> u32 { x + 1u32 }",
            ),
            file(
                "src/alt_leaf.rs",
                &["leaf"],
                "pub fn helper(x: u32) -> u32 { x + 7u32 }",
            ),
        ];
        let out = extract(&target(&files, true), "", &|_| true);
        let main = out
            .iter()
            .find(|r| r.site.file == "src/main_leaf.rs")
            .unwrap();
        let alt = out
            .iter()
            .find(|r| r.site.file == "src/alt_leaf.rs")
            .unwrap();
        assert_eq!(main.access, ContextAccess::PublicFunction);
        assert_eq!(main.api_path.as_deref(), Some("app::leaf::helper"));
        assert_eq!(main.conditions, Vec::<String>::new());
        assert_eq!(alt.access, ContextAccess::Unresolved);
        assert_eq!(alt.api_path, None);
        assert_eq!(alt.conditions, vec!["all(cfg(unix), false)"]);
        assert!(
            alt.extraction_notes
                .iter()
                .any(|note| note.contains("shadowed"))
        );
    }

    #[test]
    fn a_branch_before_a_direct_path_shadows_it_only_when_active() {
        let files = vec![
            file(
                "src/lib.rs",
                &[],
                "#[cfg_attr(unix, path = \"alt_leaf.rs\")]\n#[path = \"main_leaf.rs\"]\npub mod leaf;\npub fn root_fn(x: u32) -> u32 { x * 2u32 }",
            ),
            file(
                "src/main_leaf.rs",
                &["leaf"],
                "pub fn helper(x: u32) -> u32 { x + 1u32 }",
            ),
            file(
                "src/alt_leaf.rs",
                &["leaf"],
                "pub fn helper(x: u32) -> u32 { x + 7u32 }",
            ),
        ];
        let out = extract(&target(&files, true), "", &|_| true);
        let main = out
            .iter()
            .find(|r| r.site.file == "src/main_leaf.rs")
            .unwrap();
        let alt = out
            .iter()
            .find(|r| r.site.file == "src/alt_leaf.rs")
            .unwrap();
        assert_eq!(main.conditions, vec!["not(cfg(unix))"]);
        assert_eq!(alt.conditions, vec!["cfg(unix)"]);
    }
    #[test]
    fn a_bin_method_and_trait_default_are_not_established() {
        let out = extract(
            &target(
                &[file(
                    "src/main.rs",
                    &[],
                    "struct A; impl A { pub fn m(&self) -> u32 { 1u32 } } trait T { fn d(&self) -> u32 { 1u32 } }",
                )],
                false,
            ),
            "",
            &|_| true,
        );
        let method = out.iter().find(|r| r.site.item == "app::A::m").unwrap();
        let default = out.iter().find(|r| r.site.item == "app::T::d").unwrap();
        for record in [method, default] {
            assert_eq!(
                record.access,
                ContextAccess::Unresolved,
                "{}",
                record.site.item
            );
            assert!(
                record
                    .extraction_notes
                    .iter()
                    .any(|note| note.contains("not a library"))
            );
        }
    }

    #[test]
    fn a_root_qualified_self_type_keeps_its_leading_colons_in_the_item() {
        let out = extract(
            &target(
                &[file(
                    "src/lib.rs",
                    &[],
                    "pub trait T { fn m(&self) -> u32; } impl T for ::core::cell::Cell<u32> { fn m(&self) -> u32 { 1u32 } }",
                )],
                true,
            ),
            "",
            &|_| true,
        );
        let items: Vec<&str> = out.iter().map(|r| r.site.item.as_str()).collect();
        assert!(
            items.contains(&"app:::: core :: cell :: Cell < u32 >::m"),
            "{items:?}"
        );
    }

    #[test]
    fn items_inside_a_function_body_are_nested() {
        let out = records(
            "struct A;\npub fn outer() -> u32 { impl A { pub fn m(&self) -> u32 { 1u32 } } 1u32 }",
        );
        let nested = out
            .iter()
            .find(|r| r.site.item == "app::outer::A::m")
            .unwrap();
        assert_eq!(nested.access, ContextAccess::InternalMethod);
        assert!(
            nested
                .extraction_notes
                .iter()
                .any(|note| note.contains("nested"))
        );
    }

    #[test]
    fn a_trait_inside_a_function_body_is_nested() {
        let out = records("pub fn outer() -> u32 { trait T { fn d(&self) -> u32 { 1u32 } } 1u32 }");
        let nested = out
            .iter()
            .find(|r| r.site.item == "app::outer::T::d")
            .unwrap();
        assert_eq!(nested.access, ContextAccess::InternalMethod);
        assert!(
            nested
                .extraction_notes
                .iter()
                .any(|note| note.contains("nested"))
        );
    }

    #[test]
    fn a_private_method_stays_internal() {
        let out = records("pub struct A;\nimpl A { fn m(&self) -> u32 { 1u32 } }");
        let record = one(&out, "app");
        assert_eq!(record.access, ContextAccess::InternalMethod);
        assert_eq!(record.api_path, None);
    }

    #[test]
    fn a_trait_default_on_an_undeclared_chain_is_unresolved() {
        let out = extract(
            &target(
                &[file(
                    "src/b.rs",
                    &["a", "b"],
                    "pub trait T { fn d(&self) -> u32 { 1u32 } }",
                )],
                true,
            ),
            "",
            &|_| true,
        );
        let record = one(&out, "app::a::b");
        assert_eq!(record.access, ContextAccess::Unresolved);
        assert!(
            record
                .extraction_notes
                .iter()
                .any(|note| note.contains("module a is not found"))
        );
    }

    #[test]
    fn a_reference_receiver_is_not_established() {
        let out = records("struct A;\nimpl &A { pub fn m(&self) -> u32 { 1u32 } }");
        let record = one(&out, "app");
        assert_eq!(record.access, ContextAccess::Unresolved);
        assert!(
            record
                .extraction_notes
                .iter()
                .any(|note| note.contains("&A"))
        );
    }

    #[test]
    fn a_primitive_receiver_is_public() {
        let out = records("impl u32 { pub fn inc(&self) -> u32 { *self + 1u32 } }");
        let record = one(&out, "app");
        assert_eq!(record.access, ContextAccess::PublicMethod);
        assert_eq!(record.api_path.as_deref(), Some("app::u32::inc"));
    }

    #[test]
    fn a_type_shadowed_by_a_glob_import_is_unresolved() {
        let out = records(
            "pub struct Pack;\nmod inner { use super::*; impl Pack { pub fn m(&self) -> u32 { 1u32 } } }",
        );
        let record = one(&out, "app::inner");
        assert_eq!(record.access, ContextAccess::Unresolved);
        assert!(
            record
                .extraction_notes
                .iter()
                .any(|note| note.contains("shadowed by a glob import"))
        );
    }

    #[test]
    fn a_receiver_aliased_to_a_module_is_unresolved() {
        let out = records(
            "mod inner { pub struct Pack; }\nmod m { use crate::inner as Pack; impl Pack { pub fn m(&self) -> u32 { 1u32 } } }",
        );
        let record = one(&out, "app::m");
        assert_eq!(record.access, ContextAccess::Unresolved);
        assert!(
            record
                .extraction_notes
                .iter()
                .any(|note| note.contains("outside the scanned source"))
        );
    }

    #[test]
    fn a_receiver_bound_to_an_unresolvable_path_is_unresolved() {
        let out =
            records("mod m { use nope::Pack; impl Pack { pub fn m(&self) -> u32 { 1u32 } } }");
        let record = one(&out, "app::m");
        assert_eq!(record.access, ContextAccess::Unresolved);
        assert!(
            record
                .extraction_notes
                .iter()
                .any(|note| note.contains("unresolvable path"))
        );
    }

    #[test]
    fn an_undeclared_receiver_is_not_defined() {
        let out = records("mod m { impl Ghost { pub fn m(&self) -> u32 { 1u32 } } }");
        let record = one(&out, "app::m");
        assert_eq!(record.access, ContextAccess::Unresolved);
        assert!(
            record
                .extraction_notes
                .iter()
                .any(|note| note.contains("not defined in the scanned source"))
        );
    }

    #[test]
    fn a_terminating_redirect_cycle_yields_no_reexport() {
        let out = records(
            "mod x { pub struct T; }\nmod deep { pub fn helper(x: u32) -> u32 { x + 1u32 } }\npub mod api { use crate::x::T as P; pub use crate::api::b as a; pub use crate::api::a as b; pub use P::c; }",
        );
        let record = one(&out, "app::deep");
        assert_eq!(record.access, ContextAccess::InternalFunction);
        assert_eq!(record.api_path, None);
    }

    #[test]
    fn a_route_through_an_ancestor_binding_follows_the_target_module() {
        let files = vec![file(
            "src/lib.rs",
            &[],
            "mod store { pub fn helper(x: u32) -> u32 { x + 1u32 } pub fn other(x: u32) -> u32 { x + 2u32 } }\nuse crate::store as P;\npub mod n { pub use P::helper; pub use Q::missing; }",
        )];
        let out = extract(&target(&files, true), "", &|_| true);
        let helper = out
            .iter()
            .find(|r| r.site.item == "app::store::helper")
            .unwrap();
        let other = out
            .iter()
            .find(|r| r.site.item == "app::store::other")
            .unwrap();
        assert_eq!(helper.access, ContextAccess::PublicFunction);
        assert_eq!(helper.api_path.as_deref(), Some("app::n::helper"));
        assert_eq!(other.access, ContextAccess::InternalFunction);
        assert_eq!(other.api_path, None);
    }

    #[test]
    fn a_receiver_follows_a_rebound_alias_to_the_original_type() {
        let out = records(
            "pub struct Box;\nuse crate::Box as B;\nmod n { use B as C; impl C { pub fn pack(&self) -> u32 { 1u32 } } }",
        );
        let record = one(&out, "app::n");
        assert_eq!(record.access, ContextAccess::PublicMethod);
        assert_eq!(record.api_path.as_deref(), Some("app::Box::pack"));
    }

    #[test]
    fn a_super_qualified_reexport_at_the_root_is_unresolvable() {
        let out = records(
            "mod inner { pub fn helper(x: u32) -> u32 { x + 1u32 } }\npub use super::inner::helper;",
        );
        let record = one(&out, "app::inner");
        assert_eq!(record.access, ContextAccess::InternalFunction);
        assert_eq!(record.api_path, None);
    }

    #[test]
    fn a_reexport_rest_stops_at_an_undeclared_module() {
        let files = vec![
            file("src/lib.rs", &[], "pub mod a;\npub use a::name as leaf;"),
            file("src/a.rs", &["a"], ""),
            file(
                "src/a/name/sub.rs",
                &["a", "name", "sub"],
                "pub fn helper(x: u32) -> u32 { x + 1u32 }",
            ),
        ];
        let out = extract(&target(&files, true), "", &|_| true);
        let record = one(&out, "app::a::name::sub");
        assert_eq!(record.access, ContextAccess::Unresolved);
        assert!(
            record
                .extraction_notes
                .iter()
                .any(|note| note.contains("module a::name is not found"))
        );
    }

    #[test]
    fn a_dot_prefixed_root_file_is_normalized() {
        let files = vec![
            file(
                "./lib.rs",
                &[],
                "pub mod m;\npub fn helper(x: u32) -> u32 { x + 1u32 }",
            ),
            file("m.rs", &["m"], "pub fn other(x: u32) -> u32 { x + 2u32 }"),
        ];
        let out = extract(&target(&files, true), "", &|_| true);
        let helper = out.iter().find(|r| r.site.item == "app::helper").unwrap();
        let other = out.iter().find(|r| r.site.item == "app::m::other").unwrap();
        assert_eq!(helper.site.file, "lib.rs");
        assert_eq!(helper.crate_root, "lib.rs");
        assert_eq!(helper.api_path.as_deref(), Some("app::helper"));
        assert_eq!(other.site.file, "m.rs");
        assert_eq!(other.api_path.as_deref(), Some("app::m::other"));
    }

    #[test]
    fn an_unclaimed_file_without_an_extension_keeps_its_context() {
        let out = extract(
            &target(
                &[file(
                    "m",
                    &["m"],
                    "pub fn helper(x: u32) -> u32 { x + 1u32 }",
                )],
                true,
            ),
            "",
            &|_| true,
        );
        let record = one(&out, "app::m");
        assert_eq!(record.site.file, "m");
        assert_eq!(record.access, ContextAccess::Unresolved);
        assert!(
            record
                .extraction_notes
                .iter()
                .any(|note| note.contains("module m is not found"))
        );
    }

    #[test]
    fn an_unclaimed_mod_rs_file_keeps_its_context() {
        let out = extract(
            &target(
                &[file(
                    "src/m/mod.rs",
                    &["m"],
                    "pub fn helper(x: u32) -> u32 { x + 1u32 }",
                )],
                true,
            ),
            "",
            &|_| true,
        );
        let record = one(&out, "app::m");
        assert_eq!(record.site.file, "src/m/mod.rs");
        assert_eq!(record.access, ContextAccess::Unresolved);
        assert!(
            record
                .extraction_notes
                .iter()
                .any(|note| note.contains("module m is not found"))
        );
    }

    #[test]
    fn an_inline_module_with_a_path_claim_links_its_children() {
        let files = vec![
            file(
                "lib.rs",
                &[],
                "#[path = \"m\"]\npub mod m { #[path = \"m/x.rs\"] pub mod child; }",
            ),
            file(
                "m/m/x.rs",
                &["m", "child"],
                "pub fn helper(x: u32) -> u32 { x + 1u32 }",
            ),
        ];
        let out = extract(&target(&files, true), "", &|_| true);
        let record = one(&out, "app::m::child");
        assert_eq!(record.site.file, "m/m/x.rs");
        assert_eq!(record.api_path.as_deref(), Some("app::m::child::helper"));
    }

    #[test]
    fn a_path_claim_without_an_extension_resolves() {
        let files = vec![
            file("lib.rs", &[], "#[path = \"m\"]\npub mod m;"),
            file("m", &["m"], "pub fn helper(x: u32) -> u32 { x + 1u32 }"),
        ];
        let out = extract(&target(&files, true), "", &|_| true);
        let record = one(&out, "app::m");
        assert_eq!(record.site.file, "m");
        assert_eq!(record.api_path.as_deref(), Some("app::m::helper"));
    }

    #[test]
    fn a_rooted_path_claim_keeps_its_absolute_form() {
        assert_eq!(lexical_join("src", "/abs/m.rs"), "/abs/m.rs");
        assert_eq!(lexical_join("src", "../up/m.rs"), "up/m.rs");
    }

    #[test]
    fn a_branch_onto_the_implicit_file_clears_the_module_conditions() {
        let files = vec![
            file(
                "src/lib.rs",
                &[],
                "#[cfg_attr(unix, path = \"m.rs\")]\npub mod m;",
            ),
            file(
                "src/m.rs",
                &["m"],
                "pub fn helper(x: u32) -> u32 { x + 1u32 }",
            ),
        ];
        let out = extract(&target(&files, true), "", &|_| true);
        let record = one(&out, "app::m");
        assert_eq!(record.site.file, "src/m.rs");
        assert_eq!(record.access, ContextAccess::PublicFunction);
        assert_eq!(record.api_path.as_deref(), Some("app::m::helper"));
        assert_eq!(record.conditions, Vec::<String>::new());
    }

    #[test]
    fn malformed_module_attributes_do_not_block_the_implicit_claim() {
        let files = vec![
            file(
                "lib.rs",
                &[],
                "#[doc = \"x\"]\npub mod a;\n#[cfg_attr(=)]\npub mod b;\n#[cfg_attr()]\npub mod c;",
            ),
            file("a.rs", &["a"], "pub fn helper(x: u32) -> u32 { x + 1u32 }"),
            file("b.rs", &["b"], "pub fn helper(x: u32) -> u32 { x + 1u32 }"),
            file("c.rs", &["c"], "pub fn helper(x: u32) -> u32 { x + 1u32 }"),
        ];
        let out = extract(&target(&files, true), "", &|_| true);
        for module in ["app::a", "app::b", "app::c"] {
            let record = one(&out, module);
            assert_eq!(record.access, ContextAccess::PublicFunction, "{module}");
            assert_eq!(
                record.api_path.as_deref(),
                Some(format!("{module}::helper").as_str())
            );
        }
    }

    #[test]
    fn nested_cfg_attr_noise_is_skipped_around_the_path() {
        let files = vec![
            file(
                "lib.rs",
                &[],
                "#[cfg_attr(unix, doc = \"x\", cfg(target_os = \"linux\"), cfg_attr(=), cfg_attr(), path = \"alt.rs\")]\npub mod m;",
            ),
            file("m.rs", &["m"], "pub fn helper(x: u32) -> u32 { x + 1u32 }"),
            file(
                "alt.rs",
                &["m"],
                "pub fn helper(x: u32) -> u32 { x + 2u32 }",
            ),
        ];
        let out = extract(&target(&files, true), "", &|_| true);
        let default = out
            .iter()
            .find(|r| r.site.file == "m.rs" && r.module == "app::m")
            .unwrap();
        let branch = out
            .iter()
            .find(|r| r.site.file == "alt.rs" && r.module == "app::m")
            .unwrap();
        assert_eq!(default.conditions, ["not(cfg(unix))"]);
        assert_eq!(branch.conditions, ["cfg(unix)"]);
    }

    #[test]
    fn module_scope_items_define_types_and_walk_expression_bodies() {
        let out = records(
            "const PICK: fn(u32) -> u32 = |x| x;\n\
             const IF: u32 = if true { 1u32 } else { 2u32 };\n\
             const FOR: u32 = for x in 0..1u32 { x };\n\
             const WHILE: u32 = while false { 1u32 };\n\
             const LOOP: u32 = loop { 1u32 };\n\
             const UNSAFE: u32 = unsafe { 1u32 };\n\
             const ASYNC: u32 = async { 1u32 };\n\
             const TRY: u32 = try { 1u32 };\n\
             const CONST: u32 = const { 1u32 };\n\
             const MATCH: u32 = match 0u32 { _ => 1u32 };\n\
             pub enum E { V }\n\
             impl E { pub fn on(&self) -> u32 { 1u32 } }\n\
             pub union U { x: u32 }\n\
             impl U { pub fn on(&self) -> u32 { 1u32 } }\n\
             pub type Num = u32;\n\
             impl Num { pub fn inc(&self) -> u32 { *self + 1u32 } }",
        );
        let on_e = out.iter().find(|r| r.site.item == "app::E::on").unwrap();
        let on_u = out.iter().find(|r| r.site.item == "app::U::on").unwrap();
        let inc = out.iter().find(|r| r.site.item == "app::Num::inc").unwrap();
        assert_eq!(on_e.access, ContextAccess::PublicMethod);
        assert_eq!(on_e.api_path.as_deref(), Some("app::E::on"));
        assert_eq!(on_u.access, ContextAccess::PublicMethod);
        assert_eq!(on_u.api_path.as_deref(), Some("app::U::on"));
        assert_eq!(inc.access, ContextAccess::PublicMethod);
        assert_eq!(inc.api_path.as_deref(), Some("app::Num::inc"));
        assert!(
            out.iter()
                .any(|r| r.site.item == "app::IF" && r.access == ContextAccess::Embedded)
        );
    }

    #[test]
    fn loop_bodies_are_embedded_contexts() {
        let out = records(
            "pub fn spin() -> u32 { let mut n = 0u32; while n < 1u32 { n += 1u32; } loop { n += 1u32; if n >= 3u32 { break; } } n }",
        );
        let embedded = out
            .iter()
            .filter(|r| r.access == ContextAccess::Embedded)
            .count();
        assert_eq!(embedded, 3);
        let spin = out.iter().find(|r| r.site.item == "app::spin").unwrap();
        assert_eq!(spin.access, ContextAccess::PublicFunction);
    }

    #[test]
    fn special_block_expressions_are_embedded_contexts() {
        let out = records(
            "pub fn outer() -> u32 { let u = unsafe { 1u32 }; let a = async { 1u32 }; let t = try { 1u32 }; let c = const { 1u32 }; drop((a, t)); u + c }",
        );
        let embedded = out
            .iter()
            .filter(|r| r.access == ContextAccess::Embedded)
            .count();
        assert_eq!(embedded, 4);
        assert!(out.iter().all(|r| r.module == "app"));
    }

    #[test]
    fn non_function_impl_and_trait_items_are_walked_without_contexts() {
        let out = records(
            "#[cfg(unix)]\nstatic C: u32 = 0u32;\npub struct A;\nimpl A { const V: u32 = 1u32; type T = u32; }\ntrait S { type Item; fn bare(&self) -> u32; }\npub fn helper(x: u32) -> u32 { x + 1u32 }",
        );
        let helper = out.iter().find(|r| r.site.item == "app::helper").unwrap();
        assert_eq!(helper.access, ContextAccess::PublicFunction);
        assert_eq!(helper.conditions, Vec::<String>::new());
        assert_eq!(out.len(), 1);
    }

    #[test]
    fn a_use_group_reexports_every_name() {
        let out = records(
            "mod inner { pub fn helper(x: u32) -> u32 { x + 1u32 } pub fn other(x: u32) -> u32 { x + 2u32 } }\npub use inner::{helper, other};",
        );
        let helper = out
            .iter()
            .find(|r| r.site.item == "app::inner::helper")
            .unwrap();
        let other = out
            .iter()
            .find(|r| r.site.item == "app::inner::other")
            .unwrap();
        assert_eq!(helper.api_path.as_deref(), Some("app::helper"));
        assert_eq!(other.api_path.as_deref(), Some("app::other"));
    }

    #[test]
    fn the_lookup_helper_reports_the_missing_module() {
        let out = records("pub fn helper(x: u32) -> u32 { x + 1u32 }");
        let result = std::panic::catch_unwind(|| one(&out, "app::missing"));
        assert!(result.is_err(), "the lookup of a missing module must fail");
    }

    /// A cfg attribute on a static carries into the embedded context of its initializer.
    #[test]
    fn a_cfgged_static_initializer_keeps_its_condition() {
        let out = records("#[cfg(unix)]\nstatic SUM: u32 = { 1u32 + 1u32 };");
        let record = out.iter().find(|r| r.site.item == "app::SUM").unwrap();
        assert_eq!(record.access, ContextAccess::Embedded);
        assert_eq!(record.conditions, vec!["# [cfg (unix)]"]);
    }

    /// A free function following a trait default is not misfiled as nested.
    #[test]
    fn a_function_after_a_trait_default_is_not_nested() {
        let out = records(
            "pub trait Seal { fn stamp(&self) -> u32 { 1u32 } }\npub fn helper(x: u32) -> u32 { x + 1u32 }",
        );
        let helper = out.iter().find(|r| r.site.item == "app::helper").unwrap();
        assert_eq!(helper.access, ContextAccess::PublicFunction);
        assert_eq!(helper.api_path.as_deref(), Some("app::helper"));
    }

    /// The written space of an impl Trait receiver survives type text normalization.
    #[test]
    fn an_impl_trait_receiver_note_keeps_the_written_space() {
        let out = records("impl impl Trait { pub fn m(&self) -> u32 { 1u32 } }");
        let record = out
            .iter()
            .find(|r| r.site.item == "app::impl Trait::m")
            .unwrap();
        assert_eq!(record.access, ContextAccess::Unresolved);
        assert_eq!(
            record.extraction_notes,
            vec!["the receiver impl Trait is not established from the scanned source".to_string()]
        );
    }

    /// A receiver resolved through a root definition is not shadowed by a foreign glob.
    #[test]
    fn a_root_type_receiver_in_a_module_is_not_glob_shadowed() {
        let files = vec![
            file("src/lib.rs", &[], "pub struct Box;\npub mod store;"),
            file(
                "src/store.rs",
                &["store"],
                "impl Box { pub fn pack(&self) -> u32 { 1u32 } }",
            ),
        ];
        let out = extract(&target(&files, true), "", &|_| true);
        let record = one(&out, "app::store");
        assert_eq!(record.access, ContextAccess::PublicMethod);
        assert_eq!(record.api_path.as_deref(), Some("app::Box::pack"));
    }

    /// Two linked branches of one module carry a disjunctive claim condition on the route.
    #[test]
    fn two_linked_branches_carry_a_disjunctive_claim_condition() {
        let files = vec![
            file(
                "src/lib.rs",
                &[],
                "#[cfg_attr(unix, path = \"u.rs\")]\n#[cfg_attr(windows, path = \"w.rs\")]\n#[cfg_attr(bsd, path = \"b.rs\")]\npub mod m;\n",
            ),
            file(
                "src/u.rs",
                &["m"],
                "pub fn other(x: u32) -> u32 { x + 2u32 }",
            ),
            file(
                "src/w.rs",
                &["m"],
                "pub fn third(x: u32) -> u32 { x + 3u32 }",
            ),
        ];
        let out = extract(&target(&files, true), "", &|_| true);
        let record = out
            .iter()
            .find(|r| r.site.file == "src/u.rs" && r.module == "app::m")
            .unwrap();
        assert_eq!(record.access, ContextAccess::PublicFunction);
        assert_eq!(record.api_path.as_deref(), Some("app::m::other"));
        assert_eq!(
            record.conditions,
            vec![
                "any(cfg(unix), all(cfg(windows), not(cfg(unix))))",
                "cfg(unix)"
            ]
        );
    }

    /// A struct declared inside a function body is not a module type.
    #[test]
    fn a_struct_in_a_function_body_is_not_a_module_type() {
        let out = records(
            "pub fn outer() -> u32 { struct A; 1u32 }\nimpl A { pub fn m(&self) -> u32 { 1u32 } }",
        );
        let m = out.iter().find(|r| r.site.item == "app::A::m").unwrap();
        assert_eq!(m.access, ContextAccess::Unresolved);
        assert!(
            m.extraction_notes
                .iter()
                .any(|note| note.contains("not defined in the scanned source"))
        );
    }

    /// A struct declared inside a method body is not a module type.
    #[test]
    fn a_struct_in_a_method_body_is_not_a_module_type() {
        let out = records(
            "pub struct A;\nimpl A { pub fn m(&self) -> u32 { struct B; 1u32 } }\nimpl B { pub fn n(&self) -> u32 { 1u32 } }",
        );
        let n = out.iter().find(|r| r.site.item == "app::B::n").unwrap();
        assert_eq!(n.access, ContextAccess::Unresolved);
        assert!(
            n.extraction_notes
                .iter()
                .any(|note| note.contains("not defined in the scanned source"))
        );
    }

    /// A struct declared inside a trait default body is not a module type.
    #[test]
    fn a_struct_in_a_trait_default_body_is_not_a_module_type() {
        let out = records(
            "pub trait Seal { fn stamp(&self) -> u32 { struct B; 1u32 } }\nimpl B { pub fn n(&self) -> u32 { 1u32 } }",
        );
        let n = out.iter().find(|r| r.site.item == "app::B::n").unwrap();
        assert_eq!(n.access, ContextAccess::Unresolved);
        assert!(
            n.extraction_notes
                .iter()
                .any(|note| note.contains("not defined in the scanned source"))
        );
    }

    /// A receiver type leading with an underscore is a bare name.
    #[test]
    fn an_underscore_leading_receiver_is_established() {
        let out = records("pub struct _T;\nimpl _T { pub fn m(&self) -> u32 { 1u32 } }");
        let m = out.iter().find(|r| r.site.item == "app::_T::m").unwrap();
        assert_eq!(m.access, ContextAccess::PublicMethod);
        assert_eq!(m.api_path.as_deref(), Some("app::_T::m"));
    }

    /// An underscore inside a receiver name does not break the bare name.
    #[test]
    fn an_underscore_inside_a_receiver_is_established() {
        let out = records("pub struct My_Type;\nimpl My_Type { pub fn m(&self) -> u32 { 1u32 } }");
        let m = out
            .iter()
            .find(|r| r.site.item == "app::My_Type::m")
            .unwrap();
        assert_eq!(m.access, ContextAccess::PublicMethod);
        assert_eq!(m.api_path.as_deref(), Some("app::My_Type::m"));
    }

    /// A receiver re-exported through eight hops still resolves within the redirect budget.
    #[test]
    fn an_eight_hop_reexport_chain_resolves() {
        let out = records(
            "pub struct B;\n\
             mod a { pub use crate::B; }\n\
             mod b { pub use crate::a::B; }\n\
             mod c { pub use crate::b::B; }\n\
             mod d { pub use crate::c::B; }\n\
             mod e { pub use crate::d::B; }\n\
             mod f { pub use crate::e::B; }\n\
             mod g { pub use crate::f::B; }\n\
             mod h { pub use crate::g::B; }\n\
             mod z { use crate::h::B; impl B { pub fn m(&self) -> u32 { 1u32 } } }",
        );
        let m = out.iter().find(|r| r.site.item == "app::z::B::m").unwrap();
        assert_eq!(m.access, ContextAccess::PublicMethod);
        assert_eq!(m.api_path.as_deref(), Some("app::B::m"));
    }

    /// A claimed file links its children through the directory named after its stem.
    #[test]
    fn a_stem_directory_links_the_children_of_a_claimed_file() {
        let files = vec![
            file("lib.rs", &[], "pub mod thing;"),
            file(
                "thing.rs",
                &["thing"],
                "pub mod inner;\nfn helper(x: u32) -> u32 { x + 1u32 }",
            ),
            file(
                "thing/inner.rs",
                &["thing", "inner"],
                "pub fn other(x: u32) -> u32 { x + 2u32 }",
            ),
        ];
        let out = extract(&target(&files, true), "", &|_| true);
        let helper = one(&out, "app::thing");
        assert_eq!(helper.access, ContextAccess::InternalFunction);
        let other = one(&out, "app::thing::inner");
        assert_eq!(other.access, ContextAccess::PublicFunction);
        assert_eq!(other.api_path.as_deref(), Some("app::thing::inner::other"));
    }

    /// A dot-prefixed file keeps the directory named after its whole dot-prefixed stem.
    #[test]
    fn a_dot_prefixed_stem_keeps_its_directory_link() {
        let files = vec![
            file("lib.rs", &[], "pub mod h;"),
            file("h.rs", &["h"], "pub fn h_fn(x: u32) -> u32 { x + 1u32 }"),
            file(".hidden.rs", &["h"], "pub mod inner;"),
            file(
                ".hidden/inner.rs",
                &["h", "inner"],
                "pub fn other(x: u32) -> u32 { x + 2u32 }",
            ),
        ];
        let out = extract(&target(&files, true), "", &|_| true);
        let other = one(&out, "app::h::inner");
        assert_eq!(other.access, ContextAccess::PublicFunction);
        assert_eq!(other.api_path.as_deref(), Some("app::h::inner::other"));
    }

    /// An extensionless dotfile keeps its whole name as the child directory stem.
    #[test]
    fn an_extensionless_dotfile_keeps_its_directory_link() {
        let files = vec![
            file("lib.rs", &[], "pub mod h;"),
            file("h.rs", &["h"], "pub fn h_fn(x: u32) -> u32 { x + 1u32 }"),
            file(".hidden", &["h"], "pub mod inner;"),
            file(
                ".hidden/inner.rs",
                &["h", "inner"],
                "pub fn other(x: u32) -> u32 { x + 2u32 }",
            ),
        ];
        let out = extract(&target(&files, true), "", &|_| true);
        let other = one(&out, "app::h::inner");
        assert_eq!(other.access, ContextAccess::PublicFunction);
        assert_eq!(other.api_path.as_deref(), Some("app::h::inner::other"));
    }

    /// A type defined after a module-scope block is still at module scope.
    #[test]
    fn a_type_after_a_module_scope_block_is_still_module_scope() {
        let out = records(
            "static C: u32 = { 1u32 };\npub struct B;\nimpl B { pub fn m(&self) -> u32 { 1u32 } }",
        );
        let m = out.iter().find(|r| r.site.item == "app::B::m").unwrap();
        assert_eq!(m.access, ContextAccess::PublicMethod);
        assert_eq!(m.api_path.as_deref(), Some("app::B::m"));
    }

    /// An unclaimed mod file links its children through its own directory.
    #[test]
    fn an_unclaimed_mod_file_links_its_children_through_its_directory() {
        let files = vec![
            file("lib.rs", &[], "pub fn helper(x: u32) -> u32 { x + 1u32 }"),
            file("orphan/mod.rs", &["orphan"], "pub mod child;"),
            file(
                "orphan/child.rs",
                &["orphan", "child"],
                "pub fn other(x: u32) -> u32 { x + 2u32 }",
            ),
        ];
        let out = extract(&target(&files, true), "", &|_| true);
        assert!(
            out.iter().any(|r| r.module == "app::child"),
            "the unclaimed mod file links its child"
        );
    }

    /// A struct in a const initializer block or a closure body is not a module type.
    #[test]
    fn a_struct_in_a_const_block_or_closure_is_not_a_module_type() {
        let out = records(
            "const X: () = { struct S; };\nimpl S { pub fn m(&self) -> u32 { 1u32 } }\n\
             const F: fn(u32) -> u32 = |x| { struct T; x };\nimpl T { pub fn n(&self) -> u32 { 1u32 } }",
        );
        let m = out.iter().find(|r| r.site.item == "app::S::m").unwrap();
        assert_eq!(m.access, ContextAccess::Unresolved);
        let n = out.iter().find(|r| r.site.item == "app::T::n").unwrap();
        assert_eq!(n.access, ContextAccess::Unresolved);
    }
}