silcrow 0.2.1

Deterministic CLI for a citable, checkable graph of laws in a git tree.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::OnceLock;

use anyhow::Result;
use serde::{Deserialize, Serialize};
use tree_sitter::Node;

use crate::policy::TestPaths;
use crate::span::{CodeFile, SpanMarker};
use crate::span_lang::{self, encode_digest, LangSpec};
use crate::walk;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum DeclMark {
    Technical,
    Functional,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CallMark {
    Skip,
    Follow,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FollowDecision {
    Follow,
    Stop,
}

/// First match wins: out of tree, call-site skip, declaration technical,
/// call-site follow, declaration functional, boundary, then the cone.
pub fn decide_follow(
    in_tree: bool,
    decl: Option<DeclMark>,
    call: Option<CallMark>,
    boundary: bool,
) -> FollowDecision {
    // § jncrstyg1.d@8k7nm
    if !in_tree {
        return FollowDecision::Stop;
    }
    if call == Some(CallMark::Skip) {
        return FollowDecision::Stop;
    }
    if decl == Some(DeclMark::Technical) {
        return FollowDecision::Stop;
    }
    if call == Some(CallMark::Follow) {
        return FollowDecision::Follow;
    }
    if decl == Some(DeclMark::Functional) {
        return FollowDecision::Follow;
    }
    // § one jncrstyg1.a@7dc0w
    if boundary {
        return FollowDecision::Stop;
    }
    FollowDecision::Follow
}

pub fn parse_decl_mark(line: &str) -> Option<DeclMark> {
    // § jncrstyg1.c@8sq9g
    let payload = mark_payload(line)?;
    match payload {
        "technical" => Some(DeclMark::Technical),
        "functional" => Some(DeclMark::Functional),
        _ => None,
    }
}

pub fn parse_call_mark(line: &str) -> Option<CallMark> {
    // § jncrstyg1.e@tc8rq
    let payload = mark_payload(line)?;
    match payload {
        "skip" => Some(CallMark::Skip),
        "follow" => Some(CallMark::Follow),
        _ => None,
    }
}

fn mark_payload(line: &str) -> Option<&str> {
    // § jncrstyg1.e@x7vz4
    let trimmed = line.trim();
    let body = trimmed
        .strip_prefix("//")
        .or_else(|| trimmed.strip_prefix('#'))
        .or_else(|| trimmed.strip_prefix("--"))
        .or_else(|| {
            trimmed
                .strip_prefix("/*")
                .and_then(|s| s.strip_suffix("*/"))
        })?;
    let body = body.trim().trim_end_matches('*').trim();
    body.strip_prefix("silcrow:")
}

/// The Levenshtein distance between `a` and `b`, by characters.
fn edits(a: &str, b: &str) -> usize {
    let b: Vec<char> = b.chars().collect();
    let mut row: Vec<usize> = (0..=b.len()).collect();
    for (i, ca) in a.chars().enumerate() {
        let mut diagonal = row[0];
        row[0] = i + 1;
        for (j, &cb) in b.iter().enumerate() {
            let next = (diagonal + usize::from(ca != cb))
                .min(row[j] + 1)
                .min(row[j + 1] + 1);
            diagonal = row[j + 1];
            row[j + 1] = next;
        }
    }
    row[b.len()]
}

/// A body a span may follow: a function, a class, a constant or an enum of the project.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct FnRec {
    path: PathBuf,
    start: usize,
    end: usize,
    body: Option<(usize, usize)>,
    /// The stretches its shape reads, in file order: a function with its attributes or
    /// decorators; a class by its header, the statements of its body that declare no method,
    /// and its constructors; a constant or an enum by its declaration and every top-level
    /// statement of its file that names it.
    reads: Vec<(usize, usize)>,
    name: String,
    decl: Option<DeclMark>,
    shape: String,
    boundary: bool,
    #[serde(with = "family_name")]
    lang: Family,
    /// The class, `impl`, trait or TypeScript namespace it sits in, by name, which a qualifier
    /// restricts a call to.
    owner: Option<String>,
    /// A member of a class, an `impl` or a trait, which no bare name reaches.
    member: bool,
    /// Declared outside any function and class, which a bare name of its own file follows
    /// alone.
    top: bool,
    /// The span of the innermost function around its declaration, where a bare name denotes it
    /// first.
    nested_in: Option<(usize, usize)>,
    kind: Kind,
    /// Declared in test code, which only a call from test code reaches.
    test: Option<TestCode>,
    /// A Rust declaration under a `cfg` other than `test`, of which a name may denote several.
    cfg: bool,
    /// The 1-based line of the first `ERROR` or `MISSING` node that can hide a declaration
    /// what it reads names.
    broken: Option<usize>,
    /// Where the name it declares is spelled in what it reads, which its shape does not write.
    names_at: Vec<usize>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
enum Kind {
    Function,
    /// A constant, a `static`, a class attribute or a top-level variable.
    Value,
    /// A Python, JavaScript or TypeScript class, which only a call of it reads.
    Class,
}

/// The two kinds of test code: a file its path names test code, and a Rust item compiled only
/// for tests. Each reaches the code of the project that is not test code, and test code of its
/// own kind only: a Rust integration test is another crate than the unit tests.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
enum TestCode {
    Dir,
    Cfg,
}

/// Whether code of the kind `caller` may reach a declaration of the kind `callee`.
fn reaches(caller: Option<TestCode>, callee: Option<TestCode>) -> bool {
    matches!(
        (caller, callee),
        (_, None)
            | (Some(TestCode::Dir), Some(TestCode::Dir))
            | (Some(TestCode::Cfg), Some(TestCode::Cfg))
    )
}

impl FnRec {
    /// Whether a call with `mark` follows this body.
    fn follows(&self, mark: Option<CallMark>) -> bool {
        decide_follow(true, self.decl, mark, self.boundary) == FollowDecision::Follow
    }

    /// Whether a call with `mark` would follow this body were it not a boundary.
    fn would_follow(&self, mark: Option<CallMark>) -> bool {
        decide_follow(true, self.decl, mark, false) == FollowDecision::Follow
    }
}

/// A byte range a span reads, with the ranges punched out of it.
type Stretch<'a> = (usize, usize, &'a [(usize, usize)]);

/// A body a span follows, by name, file and byte range.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Callee {
    pub name: String,
    pub path: PathBuf,
    pub start: usize,
    pub end: usize,
}

#[derive(Debug, Clone)]
struct SpanRec {
    path: PathBuf,
    line: usize,
    addr: String,
    /// The project and the id of the law its address names.
    law: (Option<String>, String),
    start: usize,
    end: usize,
    /// The function this span covers whole, when it opens with no explicit `end`.
    boundary_of: Option<usize>,
    pinned: bool,
    /// What its pin reads around it, whose constants it follows.
    prefix: Vec<span_lang::Stretch>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct CallRec {
    path: PathBuf,
    start: usize,
    end: usize,
    name: String,
    /// The qualifier of a scoped call, `a::b` of `a::b::f()` or `m` of `m.f()`, empty for a bare one.
    scope: Vec<String>,
    mark: Option<CallMark>,
    #[serde(with = "family_name")]
    lang: Family,
    /// A name read rather than a call.
    value: bool,
    /// A name of a refutable Rust pattern, which reads only a constant or a `static`.
    pattern: bool,
    /// The byte where its last name starts, `f` of `m.f()`.
    name_at: usize,
    /// The name is a local binding of a function around it, or the value a method is called on.
    local: bool,
    test: Option<TestCode>,
    /// A call or read through `self`, `this`, `cls` or `Self`, with the name of the class or
    /// `impl` around it.
    receiver: Option<Option<String>>,
    /// Every body of the project its last name may name.
    callees: Vec<usize>,
}

/// An import or `use` line, by its byte range, the import of each name it holds, and the names
/// it spells.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct ImportLine {
    units: Vec<ImportUnit>,
    /// The bytes of the statement in its file.
    bytes: (usize, usize),
    names: BTreeSet<String>,
    binds: Vec<Bind>,
}

/// The import of one name of an import line, as its tokens, and the names it spells.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct ImportUnit {
    text: String,
    names: BTreeSet<String>,
}

/// A name an import line binds, with where its text says the name comes from.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct Bind {
    name: String,
    origin: Origin,
}

/// Where an import line says a name comes from, by its text.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
enum Origin {
    /// A Rust `use` path, by its first segment.
    Root(String),
    /// A Python module or a JavaScript or TypeScript specifier, by its segments, and whether
    /// it is relative.
    Module(Vec<String>, bool),
    /// A relative Python module or JavaScript or TypeScript specifier, by its path from the
    /// directory of the importing file, `..` for each step up.
    Near(Vec<String>),
}

/// The project path a relative import of the file at `from` names by `near`.
fn near_path(from: &Path, near: &[String]) -> PathBuf {
    let mut out: Vec<&str> = from
        .parent()
        .into_iter()
        .flat_map(|p| p.components())
        .filter_map(|c| c.as_os_str().to_str())
        .collect();
    for segment in near {
        match segment.as_str() {
            ".." => {
                out.pop();
            }
            segment => out.push(segment),
        }
    }
    out.iter().collect()
}

/// Whether the file at `path` is the module a relative import names by the project path
/// `target`: that path with or without its extension, or the package file of that directory.
fn names_file(path: &Path, target: &Path) -> bool {
    let bare = |p: &Path| match p.extension().and_then(|e| e.to_str()) {
        Some("js" | "jsx" | "mjs" | "cjs" | "ts" | "tsx" | "mts" | "cts" | "py") => {
            p.with_extension("")
        }
        _ => p.to_path_buf(),
    };
    let target = bare(target);
    let package = matches!(
        path.file_stem().and_then(|s| s.to_str()),
        Some("index" | "__init__")
    );
    bare(path) == target || (package && path.parent() == Some(target.as_path()))
}

/// Whether the file at `path` is the one a module segment `unit` names by its text: its stem is
/// the segment, or it is the package file of a directory of that name, `__init__.py`,
/// `index.*` or `mod.rs`.
fn names_unit(path: &Path, unit: &str) -> bool {
    let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
        return false;
    };
    let dir = || {
        path.parent()
            .and_then(|p| p.file_name())
            .and_then(|d| d.to_str())
    };
    stem == unit || (matches!(stem, "__init__" | "index" | "mod") && dir() == Some(unit))
}

/// The Rust crates whose paths are never the project's.
const STD_ROOTS: [&str; 3] = ["std", "core", "alloc"];

/// Whether the follow index reads the file at `rel`: a code file a tested grammar reads, or a
/// `Cargo.toml`, whose crate names tell a workspace path from a dependency's.
pub fn reads_path(rel: &Path) -> bool {
    // § d1bc2zca5.d@9hssv
    // A data file the code reads at run time is none of these, so no call reaches it.
    span_lang::lang_for_path(rel).is_some()
        || rel
            .file_name()
            .is_some_and(|n| n == "Cargo.toml" || n == "tsconfig.json" || n == "deno.json")
}

#[derive(Debug, Default)]
pub struct FollowIndex {
    functions: Vec<FnRec>,
    calls: Vec<CallRec>,
    spans: Vec<SpanRec>,
    /// Indices into `spans` by file, in index order.
    spans_in: HashMap<PathBuf, Vec<usize>>,
    /// Built on the first drift notice, which a clean tree never asks for.
    span_edges: OnceLock<SpanEdges>,
    /// Per body, the callers that would follow it were it not a boundary.
    callers: Vec<BTreeSet<usize>>,
    /// Per body, the bodies it follows, and the callers that follow it.
    adj: Vec<BTreeSet<usize>>,
    followers: Vec<BTreeSet<usize>>,
    scc_of: Vec<usize>,
    /// A follow mark that attaches to nothing, names no mark or follows nothing, per file.
    mark_errors: Vec<String>,
    /// Per supernode, its members and the supernodes its members follow out of it.
    members: Vec<Vec<usize>>,
    scc_adj: Vec<BTreeSet<usize>>,
    supernode: Vec<String>,
    /// Indices into `functions` and `calls` by file, in index order.
    fns_in: HashMap<PathBuf, Vec<usize>>,
    calls_in: HashMap<PathBuf, Vec<usize>>,
    imports: HashMap<PathBuf, Vec<ImportLine>>,
    /// Each top-level item whose parse error may have swallowed a declaration.
    swallowed: Vec<Swallowed>,
    /// The reads that denote nothing and name a token of a swallowed item, which the calls
    /// leave out.
    unbound: Vec<CallRec>,
}

#[derive(Debug, Default)]
struct SpanEdges {
    calls: Vec<Vec<(usize, bool, bool)>>,
    calling: Vec<Vec<usize>>,
}

/// A top-level item whose parse error may have swallowed the code after it.
#[derive(Debug)]
struct Swallowed {
    path: PathBuf,
    lang: &'static str,
    /// The 1-based line of its error.
    line: usize,
    text: String,
}

impl Swallowed {
    /// Whether the item spells `name` as a whole token, as a declaration of it would.
    fn spells(&self, name: &str) -> bool {
        let ident = |c: char| c.is_alphanumeric() || c == '_';
        self.text.match_indices(name).any(|(at, _)| {
            !self.text[..at].ends_with(ident) && !self.text[at + name.len()..].starts_with(ident)
        })
    }
}

/// A body a pin cannot be hashed through, with the file and the 1-based line of the parse error
/// that can hide what it reads. `name`, when given, is a name the closure reads that denotes
/// nothing, and whose declaration the error may have swallowed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Broken {
    pub path: PathBuf,
    pub line: usize,
    pub name: Option<String>,
}

impl FollowIndex {
    /// Every file of the tree the index reads, with its text.
    pub fn sources(root: &Path) -> Result<Vec<(PathBuf, String)>> {
        // § pyw49tg9j.h@4wptp
        let mut files = Vec::new();
        for path in walk::code_files(root)? {
            if !reads_path(&path) {
                continue;
            }
            let text = std::fs::read_to_string(&path)?;
            let rel = path.strip_prefix(root).unwrap_or(&path).to_path_buf();
            files.push((rel, text));
        }
        Ok(files)
    }

    pub fn from_sources(files: &[(PathBuf, String)], tests: &TestPaths) -> Self {
        let files = crate::par::map(
            files.iter().collect(),
            |(_, source)| source.len(),
            |(path, source)| CodeFile::new(path.clone(), source.clone()),
        );
        Self::from_files(&files, tests)
    }

    /// The index over files a run already read and parsed.
    pub fn from_files(files: &[CodeFile], tests: &TestPaths) -> Self {
        // Unit tests ask for the closure of any stretch, not only of a marker's span.
        Self::build(files, tests, cfg!(test))
    }

    /// The index, reading the calls of every file when `every` asks, and otherwise only those a
    /// pin reads: both answer alike for every span of the tree.
    fn build(files: &[CodeFile], tests: &TestPaths, every: bool) -> Self {
        // § d1bc2zca5@twp9x
        let test_rows = crate::span::test_rows(files);
        let cfg_rows = crate::span::cfg_rows(files);
        let rows = |table: &BTreeMap<PathBuf, Vec<(usize, usize)>>, f: &CodeFile| {
            table.get(&f.rel).cloned().unwrap_or_default()
        };
        let analyse = |(f, calls): (&CodeFile, bool)| {
            // § faq86xmas.a@fn6pj
            let (test, cfg, in_tests) =
                (rows(&test_rows, f), rows(&cfg_rows, f), tests.holds(&f.rel));
            f.memo(&("file nodes", &test, &cfg, in_tests, calls), || {
                FileNodes::of(f, test.clone(), cfg.clone(), in_tests, calls)
            })
        };
        // Every declaration is read, since any name may denote it. The calls of a file are
        // read only when a pin reads them: it holds a marker or a follow mark, or a pin
        // follows a body of it. Each round reads the files the last one reached.
        let mut read: Vec<bool> = files
            .iter()
            .map(|f| every || !f.span_markers().is_empty() || f.text.contains("silcrow:"))
            .collect();
        // Reading more files than the rounds reach changes no answer, so the files the last
        // run reached start this one, which then needs a round or none.
        let seeds: Vec<&Path> = files
            .iter()
            .zip(&read)
            .filter(|&(_, &r)| r)
            .map(|(f, _)| f.rel.as_path())
            .collect();
        let hint = format!(
            "follow reads {}",
            blake3::hash(format!("{seeds:?}").as_bytes())
        );
        let hinted: HashSet<PathBuf> = crate::cache::hint(&hint)
            .and_then(|bytes| bincode::deserialize(&bytes).ok())
            .unwrap_or_default();
        for (r, f) in read.iter_mut().zip(files) {
            *r |= hinted.contains(&f.rel);
        }
        let mut parts = crate::par::map(
            files.iter().zip(read.iter().copied()).collect(),
            |(f, _)| f.text.len(),
            analyse,
        );
        let at: HashMap<&Path, usize> = files
            .iter()
            .enumerate()
            .map(|(i, f)| (f.rel.as_path(), i))
            .collect();
        let mut shared = None;
        loop {
            let mut index = Self::assemble(files, parts.clone(), &mut shared);
            let reached = match every {
                true => vec![true; index.functions.len()],
                false => index.reached(),
            };
            let pending: BTreeSet<usize> = reached
                .iter()
                .enumerate()
                .filter(|&(_, &r)| r)
                .map(|(i, _)| at[index.functions[i].path.as_path()])
                .filter(|&i| !read[i])
                .collect();
            if pending.is_empty() {
                let reads: HashSet<PathBuf> = reached
                    .iter()
                    .zip(&index.functions)
                    .filter(|&(&r, _)| r)
                    .map(|(_, rec)| rec.path.clone())
                    .collect();
                if reads != hinted {
                    if let Ok(bytes) = bincode::serialize(&reads) {
                        crate::cache::set_hint(&hint, &bytes);
                    }
                }
                index.hash_supernodes(files, &reached);
                return index;
            }
            let redone = crate::par::map(
                pending.iter().map(|&i| (&files[i], true)).collect(),
                |(f, _)| f.text.len(),
                analyse,
            );
            for (i, part) in pending.into_iter().zip(redone) {
                read[i] = true;
                parts[i] = part;
            }
        }
    }

    /// The bodies a span follows, directly or through followed calls: the only ones whose
    /// hash a pin reads.
    fn reached(&self) -> Vec<bool> {
        let mut seen = vec![false; self.functions.len()];
        let mut queue: Vec<usize> = self
            .spans
            .iter()
            .flat_map(|z| self.followed_from(&z.path, z.start, z.end, &[], &z.prefix))
            .collect();
        while let Some(i) = queue.pop() {
            if !std::mem::replace(&mut seen[i], true) {
                queue.extend(self.adj[i].iter().copied());
            }
        }
        seen
    }

    fn assemble(
        files: &[CodeFile],
        parts: Vec<Option<FileNodes>>,
        shared: &mut Option<(HashMap<PathBuf, Vec<ImportLine>>, Outside)>,
    ) -> Self {
        let mut functions: Vec<FnRec> = Vec::new();
        let mut calls: Vec<CallRec> = Vec::new();
        let mut imports = HashMap::new();
        let mut mark_errors = Vec::new();
        let mut spans = Vec::new();
        let mut fns_in: HashMap<PathBuf, Vec<usize>> = HashMap::new();
        let mut calls_in: HashMap<PathBuf, Vec<usize>> = HashMap::new();
        let mut parsed = Vec::new();
        let mut swallowed = Vec::new();
        let mut carriers = Vec::new();
        for (file, part) in files.iter().zip(parts) {
            let Some(mut part) = part else {
                continue;
            };
            if let Some(lang) = file.lang {
                swallowed.extend(
                    file.swallowing_items()
                        .into_iter()
                        .map(|(start, end, line)| Swallowed {
                            path: file.rel.clone(),
                            lang: family(lang),
                            line,
                            text: file.text[start..end].to_string(),
                        }),
                );
            }
            for rec in &mut part.functions {
                rec.broken = rec.reads.iter().find_map(|&(s, e)| file.hiding_error(s, e));
            }
            let spans_of: Vec<(usize, usize)> = part
                .functions
                .iter()
                .filter(|f| f.kind == Kind::Function)
                .map(|f| (f.start, f.end))
                .collect();
            for rec in &mut part.functions {
                let around = spans_of
                    .iter()
                    .copied()
                    .filter(|&(s, e)| {
                        s <= rec.start && rec.end <= e && (s, e) != (rec.start, rec.end)
                    })
                    .min_by_key(|&(s, e)| e - s);
                rec.top = !rec.member && around.is_none();
                rec.nested_in = around.filter(|_| !rec.member);
            }
            let path = file.rel.as_path();
            let at = functions.len();
            fns_in
                .entry(path.to_path_buf())
                .or_default()
                .extend(at..at + part.functions.len());
            functions.extend(part.functions);
            mark_errors.extend(part.mark_errors);
            imports.insert(path.to_path_buf(), part.imports);
            spans.extend(part.spans.into_iter().map(|z| (path.to_path_buf(), z)));
            carriers.extend(
                part.carriers
                    .iter()
                    .map(|&(s, e)| (path.to_path_buf(), s, e)),
            );
            parsed.push((path.to_path_buf(), part.calls));
        }
        // Every free name of every file is a candidate read: keep those a body of the project
        // declares, those a mark names, and those an import line of their file names.
        let declared: BTreeSet<&str> = functions.iter().map(|f| f.name.as_str()).collect();
        let mut unbound = Vec::new();
        for (path, mut part) in parsed {
            let lines = &imports[&path];
            let (kept, dropped): (Vec<CallRec>, Vec<CallRec>) =
                part.into_iter().partition(|c: &CallRec| {
                    !c.value
                        || c.mark.is_some()
                        || declared.contains(c.name.as_str())
                        || lines.iter().any(|l: &ImportLine| l.names.contains(&c.name))
                });
            part = kept;
            unbound.extend(
                dropped
                    .into_iter()
                    .filter(|c| swallowed.iter().any(|s: &Swallowed| s.spells(&c.name))),
            );
            calls_in
                .entry(path)
                .or_default()
                .extend(calls.len()..calls.len() + part.len());
            calls.extend(part);
        }
        let spans = mark_boundaries(&mut functions, &fns_in, spans);
        let mut spans_in: HashMap<PathBuf, Vec<usize>> = HashMap::new();
        for (i, z) in spans.iter().enumerate() {
            spans_in.entry(z.path.clone()).or_default().push(i);
        }
        let mut by_name: BTreeMap<&str, Vec<usize>> = BTreeMap::new();
        for (idx, rec) in functions.iter().enumerate() {
            by_name.entry(rec.name.as_str()).or_default().push(idx);
        }
        // They read the declarations and the import lines alone, which every round reads alike.
        let (imports, outside) = &*shared.get_or_insert_with(|| {
            resolve_aliases(files, &mut imports);
            let outside = Outside::of(files, &imports, &functions);
            (imports, outside)
        });
        let imports = imports.clone();
        let lookup = Lookup {
            functions: &functions,
            by_name: &by_name,
            imports: &imports,
            outside,
        };
        let resolved =
            crate::par::map_many(calls.iter().collect(), |call| callees_of(&lookup, call));
        for (call, callees) in calls.iter_mut().zip(resolved) {
            call.callees = callees;
        }
        mark_errors.extend(pass_marks(files, &lookup, &mut calls, &calls_in, &carriers));

        let mut adj: Vec<BTreeSet<usize>> = vec![BTreeSet::new(); functions.len()];
        let mut callers: Vec<BTreeSet<usize>> = vec![BTreeSet::new(); functions.len()];
        let mut link = |caller: usize, call: &CallRec| {
            for &callee in &call.callees {
                if functions[callee].would_follow(call.mark) {
                    callers[callee].insert(caller);
                }
                if functions[callee].follows(call.mark) {
                    adj[caller].insert(callee);
                }
            }
        };
        // § kv22y3ap6.d@2ye0g
        // A function owns the calls it holds outside the functions nested in it, and those of
        // its attributes; a class every call in what it reads; a constant or an enum those of
        // its declaration alone, so two constants one statement names do not join one cycle.
        for call in &calls {
            if let Some(caller) =
                innermost_fn(&functions, &fns_in, &call.path, call.start, call.end)
            {
                link(caller, call);
            }
        }
        for (caller, rec) in functions.iter().enumerate() {
            let stretches: Vec<(usize, usize)> = match rec.kind {
                Kind::Function => rec
                    .reads
                    .iter()
                    .filter(|&&(s, _)| s < rec.start)
                    .map(|&(s, _)| (s, rec.start))
                    .collect(),
                Kind::Class => rec.reads.clone(),
                Kind::Value => vec![(rec.start, rec.end)],
            };
            for (start, end) in stretches {
                for &i in in_file(&calls_in, &rec.path) {
                    if within(&calls[i], (start, end, &[])) {
                        link(caller, &calls[i]);
                    }
                }
            }
        }
        // § end kv22y3ap6.d
        let mut followers: Vec<BTreeSet<usize>> = vec![BTreeSet::new(); functions.len()];
        for (caller, succs) in adj.iter().enumerate() {
            for &callee in succs {
                followers[callee].insert(caller);
            }
        }

        let adj_list: Vec<Vec<usize>> = adj.iter().map(|s| s.iter().copied().collect()).collect();
        let scc_of = tarjan(functions.len(), &adj_list);
        let scc_count = scc_of.iter().copied().max().map(|n| n + 1).unwrap_or(0);
        let mut members: Vec<Vec<usize>> = vec![Vec::new(); scc_count];
        for (idx, &scc) in scc_of.iter().enumerate() {
            members[scc].push(idx);
        }
        // § d1bc2zca5.a@4p4gp
        for group in &mut members {
            group.sort_by_key(|&i| (path_key(&functions[i].path), functions[i].start));
        }
        // § end d1bc2zca5.a

        let mut scc_adj: Vec<BTreeSet<usize>> = vec![BTreeSet::new(); scc_count];
        for (src, succs) in adj.iter().enumerate() {
            for &dst in succs {
                if scc_of[src] != scc_of[dst] {
                    scc_adj[scc_of[src]].insert(scc_of[dst]);
                }
            }
        }

        Self {
            functions,
            calls,
            spans,
            spans_in,
            span_edges: OnceLock::new(),
            callers,
            adj,
            followers,
            scc_of,
            members,
            scc_adj,
            supernode: vec![String::new(); scc_count],
            mark_errors,
            fns_in,
            calls_in,
            imports,
            swallowed,
            unbound,
        }
    }

    /// Hashes the shape of every body `reached` holds and every supernode of them, callees
    /// first: a followed call names its callee by the supernode hash it enters by, so a callee
    /// is hashed before its callers. A body no span follows is read by no pin.
    fn hash_supernodes(&mut self, files: &[CodeFile], reached: &[bool]) {
        let by_path: HashMap<&Path, &CodeFile> =
            files.iter().map(|f| (f.rel.as_path(), f)).collect();
        // Tarjan numbers a supernode after every supernode it reaches, so each level only
        // follows lower ones and its members hash in parallel.
        let mut level = vec![0usize; self.members.len()];
        for scc in 0..self.members.len() {
            level[scc] = self.scc_adj[scc]
                .iter()
                .map(|&next| level[next] + 1)
                .max()
                .unwrap_or(0);
        }
        let mut by_level: Vec<Vec<usize>> = Vec::new();
        for (scc, &at) in level.iter().enumerate() {
            if by_level.len() <= at {
                by_level.resize(at + 1, Vec::new());
            }
            by_level[at].push(scc);
        }
        for mut sccs in by_level {
            sccs.retain(|&scc| self.members[scc].iter().any(|&i| reached[i]));
            let jobs: Vec<usize> = sccs
                .iter()
                .flat_map(|&scc| self.members[scc].iter().copied())
                .collect();
            let index = &*self;
            let shapes = crate::par::map(
                jobs,
                |&i| index.functions[i].end - index.functions[i].start,
                |i| {
                    let file = by_path.get(index.functions[i].path.as_path()).copied();
                    (
                        i,
                        file.map(|f| index.record_shape(f, i)).unwrap_or_default(),
                    )
                },
            );
            for (i, shape) in shapes {
                self.functions[i].shape = shape;
            }
            for scc in sccs {
                self.supernode[scc] = supernode_hash(
                    &self.members[scc],
                    &self.scc_adj[scc],
                    &self.functions,
                    &self.supernode,
                );
            }
        }
    }

    /// The shape of the body `idx`, the walk of the stretches it reads with every followed
    /// call named by its callee's supernode hash.
    fn record_shape(&self, file: &CodeFile, idx: usize) -> String {
        // § faq86xmas.a@hpgj9
        let Some(lang) = file.lang.filter(|_| file.parsed()) else {
            return String::new();
        };
        let rec = &self.functions[idx];
        let own = Some(self.scc_of[idx]);
        // A call of a function nested in this one is that function's to follow, so its callee
        // may not be hashed yet: only what this one follows is named by its hash.
        let reach = Some(&self.scc_adj[self.scc_of[idx]]);
        let mut tokens = HashMap::new();
        for &(start, end) in &rec.reads {
            let calls = self.span_calls(&rec.path, start, end, &[]);
            tokens.extend(self.tokens_in(calls, own, reach));
        }
        // § k6rfj5k37.c@zq6ht
        if rec.lang != "bash" {
            for &at in &rec.names_at {
                tokens.insert(at, "declared".to_string());
            }
        }
        // § end k6rfj5k37.c
        let mut named: Vec<(&usize, &String)> = tokens.iter().collect();
        named.sort();
        file.memo(&("callee shape", &rec.reads, &named), || {
            let Some(tree) = file.tree() else {
                return String::new();
            };
            let parts: Vec<String> = rec
                .reads
                .iter()
                .map(|&(start, end)| {
                    span_lang::callee_shape(lang, &file.text, tree, start, end, &|at| {
                        tokens.get(&at).cloned()
                    })
                })
                .collect();
            parts.join("\n")
        })
    }

    /// What the shape of the span at `start..end` of `path` writes for each name a call or read
    /// in it, or a constant read in its `prefix`, names, keyed by the byte the name starts at:
    /// the supernode hash a followed callee enters by. Any other call keeps its text.
    pub fn name_tokens(
        &self,
        path: &Path,
        start: usize,
        end: usize,
        punch: &[(usize, usize)],
        prefix: &[span_lang::Stretch],
    ) -> HashMap<usize, String> {
        let own = innermost_fn(&self.functions, &self.fns_in, path, start, end)
            .map(|idx| self.scc_of[idx]);
        self.tokens_in(self.pin_calls(path, start, end, punch, prefix), own, None)
    }

    /// The names of `name_tokens` for `calls`, read from the supernode `own`, only those whose
    /// callees' supernodes are all in `reach` when it is given.
    fn tokens_in<'a>(
        &'a self,
        calls: impl Iterator<Item = &'a CallRec>,
        own: Option<usize>,
        reach: Option<&BTreeSet<usize>>,
    ) -> HashMap<usize, String> {
        // § k6rfj5k37.c@zwgwj
        let mut out = HashMap::new();
        for call in calls {
            let followed = self.followed_by(call);
            // § jncrstyg1.f@3m7cv
            let inside = followed.iter().any(|&c| Some(self.scc_of[c]) == own);
            let reached =
                reach.is_none_or(|r| followed.iter().all(|c| r.contains(&self.scc_of[*c])));
            if followed.is_empty() || inside || !reached {
                continue;
            }
            // § end jncrstyg1.f
            let mut names: Vec<String> = followed.iter().map(|&c| self.callee_token(c)).collect();
            names.sort();
            names.dedup();
            out.insert(call.name_at, names.join("+"));
        }
        out
    }

    /// The bodies `call` follows: each of its callees its mark and their own marks and
    /// boundaries let it follow, but the function that holds it.
    fn followed_by(&self, call: &CallRec) -> Vec<usize> {
        let around = innermost_fn(
            &self.functions,
            &self.fns_in,
            &call.path,
            call.start,
            call.end,
        );
        call.callees
            .iter()
            .copied()
            .filter(|&c| self.functions[c].follows(call.mark) && Some(c) != around)
            .collect()
    }

    /// The name a followed call writes for `callee`: the hash of its supernode, with its name
    /// when the supernode holds more than one member, since every member shares that hash.
    fn callee_token(&self, callee: usize) -> String {
        let scc = self.scc_of[callee];
        if self.members[scc].len() == 1 {
            format!("§{}", self.supernode[scc])
        } else {
            format!("§{} {}", self.supernode[scc], self.functions[callee].name)
        }
    }

    /// The imports of the file of `call` that name one of the names it writes, followed or
    /// not: an import that rebinds a followed call changes what it runs as well.
    fn import_lines_of(&self, call: &CallRec) -> Vec<String> {
        // § kv22y3ap6.h@e5n1k
        let mut out: Vec<String> = self
            .imports
            .get(&call.path)
            .into_iter()
            .flatten()
            .flat_map(|line| &line.units)
            .filter(|unit| spells(&unit.names, call))
            .map(|unit| unit.text.clone())
            .collect();
        out.sort();
        out.dedup();
        out
    }

    /// The bytes of each import line of `path` that the pin of the span `start..end` reads.
    pub fn pin_import_bytes(
        &self,
        path: &Path,
        start: usize,
        end: usize,
        punch: &[(usize, usize)],
        prefix: &[span_lang::Stretch],
    ) -> Vec<(usize, usize)> {
        let calls: Vec<&CallRec> = self.pin_calls(path, start, end, punch, prefix).collect();
        self.imports
            .get(path)
            .into_iter()
            .flatten()
            .filter(|line| calls.iter().any(|call| spells(&line.names, call)))
            .map(|line| line.bytes)
            .collect()
    }

    /// The names a span of the project, or a body it follows, calls or reads, resolved or not:
    /// a declaration of one of them elsewhere changes what the call reads.
    pub fn read_names(&self) -> BTreeSet<String> {
        // § pga7yfvm9.d@wbrt6
        let mut out = BTreeSet::new();
        for z in &self.spans {
            out.extend(
                self.pin_calls(&z.path, z.start, z.end, &[], &z.prefix)
                    .map(|c| c.name.clone()),
            );
            for callee in self.followed_callees(&z.path, z.start, z.end, &[], &z.prefix) {
                out.extend(
                    self.span_calls(&callee.path, callee.start, callee.end, &[])
                        .map(|c| c.name.clone()),
                );
            }
        }
        out
    }

    /// The names the file at `path` declares as functions or constants that a bare name reaches.
    pub fn declared_in(&self, path: &Path) -> BTreeSet<String> {
        in_file(&self.fns_in, path)
            .iter()
            .map(|&i| &self.functions[i])
            .filter(|rec| !rec.member)
            .map(|rec| rec.name.clone())
            .collect()
    }

    /// The files that declare a function or a constant named `name`, one entry per declaration.
    pub fn declarations_of(&self, name: &str) -> Vec<&Path> {
        self.functions
            .iter()
            .filter(|rec| rec.name == name && rec.kind != Kind::Class)
            .map(|rec| rec.path.as_path())
            .collect()
    }

    /// Each name an unmarked call of the span at `start..end` of `path` spells, outside every
    /// `punch` range, that follows nothing only because the one declaration of the name lies
    /// outside the cone of `path`, the directory of that file and below it, with the file of
    /// that declaration.
    pub fn outside_cone(
        &self,
        path: &Path,
        start: usize,
        end: usize,
        punch: &[(usize, usize)],
    ) -> BTreeMap<String, PathBuf> {
        // § z0xqn70bp.c@cz1v0
        in_file(&self.calls_in, path)
            .iter()
            .map(|&i| &self.calls[i])
            .filter(|c| within(c, (start, end, punch)))
            .filter(|c| c.callees.is_empty() && !c.local && c.mark.is_none())
            .filter_map(|c| {
                let mut decls = self
                    .functions
                    .iter()
                    .filter(|rec| rec.name == c.name && rec.kind != Kind::Class);
                match (decls.next(), decls.next()) {
                    (Some(rec), None)
                        if rec.decl.is_none()
                            && rec.lang == c.lang
                            && (rec.test.is_none() || c.test.is_some())
                            && !in_cone(path, &rec.path) =>
                    {
                        Some((c.name.clone(), rec.path.clone()))
                    }
                    _ => None,
                }
            })
            .collect()
    }

    /// The file and the 1-based line of a parse error that may have swallowed a declaration of
    /// `name`.
    pub fn swallowing(&self, name: &str) -> Option<(&Path, usize)> {
        self.swallowed
            .iter()
            .find(|s| s.spells(name))
            .map(|s| (s.path.as_path(), s.line))
    }

    /// Each follow mark that attaches to nothing, names no mark or follows nothing.
    pub fn mark_errors(&self) -> &[String] {
        &self.mark_errors
    }

    /// The warning owed when the pin on `line` drifts and covers a boundary whose callers
    /// carry laws, or `None`.
    pub fn drift_notice(&self, path: &Path, line: usize, addr: &str) -> Option<String> {
        let carried = self.caller_laws(path, line);
        if carried.is_empty() {
            return None;
        }
        Some(format!(
            "{}:{line}: § {addr} drifted; callers carry {}. Re-read them.",
            path.display(),
            carried.join(", ")
        ))
    }

    /// The laws whose spans reach the boundary opened on `line` without following it, by a call
    /// of their own, outside their nested spans, to the boundary or to a function that reaches
    /// it through followed calls. A span that follows the boundary fails its own pin instead.
    /// Sorted by path and line.
    pub fn caller_laws(&self, path: &Path, line: usize) -> Vec<String> {
        // § jncrstyg1.b@zn092
        let here = in_file(&self.spans_in, path);
        let Some(boundary) = here
            .iter()
            .map(|&i| &self.spans[i])
            .find(|z| z.line == line)
            .and_then(|z| z.boundary_of)
        else {
            return Vec::new();
        };
        let mut carried: Vec<(String, usize, &str)> = self
            .reaching(boundary)
            .into_iter()
            .filter(|&(i, sees)| !(sees || (self.spans[i].line == line && here.contains(&i))))
            .map(|(i, _)| &self.spans[i])
            .map(|z| (path_key(&z.path), z.line, z.addr.as_str()))
            .collect();
        carried.sort();
        carried.dedup();
        carried
            .into_iter()
            .map(|(path, line, addr)| format!("§ {addr} ({path}:{line})"))
            .collect()
    }

    /// The spans that reach the function `boundary` where it does not follow, by a call of
    /// their own, outside their nested spans, to it or to a function that reaches it through
    /// followed calls, by index, each with whether it also follows it.
    fn reaching(&self, boundary: usize) -> Vec<(usize, bool)> {
        let up = |from: &BTreeSet<usize>| {
            let mut seen = from.clone();
            let mut queue: Vec<usize> = from.iter().copied().collect();
            while let Some(callee) = queue.pop() {
                queue.extend(
                    self.followers[callee]
                        .iter()
                        .copied()
                        .filter(|&f| seen.insert(f)),
                );
            }
            seen
        };
        // The bodies whose hash reads the boundary, and those that call it, directly or
        // through followed calls.
        let sees = up(&BTreeSet::from([boundary]));
        let reaches = up(&self.callers[boundary]);
        let edges = self.span_edges.get_or_init(|| self.edges_of_spans());
        let candidates: BTreeSet<usize> = std::iter::once(boundary)
            .chain(reaches.iter().copied())
            .flat_map(|callee| edges.calling[callee].iter().copied())
            .collect();
        candidates
            .into_iter()
            .filter_map(|z| {
                let (mut reach, mut see) = (false, false);
                for &(callee, follows, would_follow) in &edges.calls[z] {
                    reach |= (callee == boundary && would_follow)
                        || (follows && reaches.contains(&callee));
                    see |= follows && sees.contains(&callee);
                }
                reach.then_some((z, see))
            })
            .collect()
    }

    /// Per span, each body its pin calls with whether the call follows it and whether it
    /// would were it not a boundary, outside its pinned nested spans; per body, the spans that
    /// call it.
    fn edges_of_spans(&self) -> SpanEdges {
        let mut calls = Vec::with_capacity(self.spans.len());
        let mut calling = vec![Vec::new(); self.functions.len()];
        for (i, z) in self.spans.iter().enumerate() {
            let punch: Vec<(usize, usize)> = in_file(&self.spans_in, &z.path)
                .iter()
                .map(|&j| &self.spans[j])
                .filter(|inner| inner.pinned)
                .map(|inner| (inner.start, inner.end))
                .filter(|&inner| crate::span::nests_in(inner, (z.start, z.end)))
                .collect();
            let mut out = Vec::new();
            for call in self.pin_calls(&z.path, z.start, z.end, &punch, &z.prefix) {
                for &callee in &call.callees {
                    let rec = &self.functions[callee];
                    out.push((callee, rec.follows(call.mark), rec.would_follow(call.mark)));
                    if calling[callee].last() != Some(&i) {
                        calling[callee].push(i);
                    }
                }
            }
            calls.push(out);
        }
        SpanEdges { calls, calling }
    }

    /// The bodies the span follows, directly or through followed calls, sorted by file and
    /// offset. The function holding the span is not its own callee.
    pub fn followed_callees(
        &self,
        path: &Path,
        span_start: usize,
        span_end: usize,
        punch: &[(usize, usize)],
        prefix: &[span_lang::Stretch],
    ) -> Vec<Callee> {
        let own = innermost_fn(&self.functions, &self.fns_in, path, span_start, span_end);
        let mut seen = BTreeSet::new();
        let mut queue = self.followed_from(path, span_start, span_end, punch, prefix);
        while let Some(idx) = queue.pop() {
            if Some(idx) == own || !seen.insert(idx) {
                continue;
            }
            queue.extend(self.adj[idx].iter().copied());
        }
        // A constant, an enum or a class shows each stretch it is read by.
        let mut out: Vec<Callee> = seen
            .into_iter()
            .flat_map(|idx| {
                let rec = &self.functions[idx];
                let stretches = match rec.kind {
                    Kind::Function => vec![(rec.start, rec.end)],
                    _ => rec.reads.clone(),
                };
                stretches.into_iter().map(|(start, end)| Callee {
                    name: rec.name.clone(),
                    path: rec.path.clone(),
                    start,
                    end,
                })
            })
            .collect();
        out.sort_by_key(|c| (path_key(&c.path), c.start));
        out
    }

    /// The files of every body a span of the project reads through what it follows.
    pub fn followed_paths(&self) -> BTreeSet<PathBuf> {
        self.spans
            .iter()
            .flat_map(|z| self.followed_callees(&z.path, z.start, z.end, &[], &z.prefix))
            .map(|callee| callee.path)
            .collect()
    }

    /// The bodies followed by the calls of `pin_calls`, recursion excluded.
    fn followed_from(
        &self,
        path: &Path,
        start: usize,
        end: usize,
        punch: &[(usize, usize)],
        prefix: &[span_lang::Stretch],
    ) -> Vec<usize> {
        self.pin_calls(path, start, end, punch, prefix)
            .flat_map(|call| self.followed_by(call))
            .collect()
    }

    /// A body the span at `start..end` of `path` reads through what it follows, callees of
    /// callees included, whose file holds an `ERROR` or `MISSING` node that can hide a
    /// declaration it reads, or a name the span or such a body reads that denotes nothing while
    /// a file in its cone may have swallowed a declaration of it. Such a pin is not hashed, as
    /// one whose span does not parse is not.
    pub fn broken_callee(
        &self,
        path: &Path,
        start: usize,
        end: usize,
        punch: &[(usize, usize)],
        prefix: &[span_lang::Stretch],
    ) -> Option<Broken> {
        // § d1bc2zca5.c@pj363
        let self_fn = innermost_fn(&self.functions, &self.fns_in, path, start, end);
        let mut stack: Vec<usize> = self
            .followed_from(path, start, end, punch, prefix)
            .into_iter()
            .map(|callee| self.scc_of[callee])
            .collect();
        let mut seen = BTreeSet::new();
        let mut bodies = Vec::new();
        while let Some(scc) = stack.pop() {
            if !seen.insert(scc) {
                continue;
            }
            for &member in &self.members[scc] {
                let rec = &self.functions[member];
                match rec.broken {
                    Some(line) if Some(member) != self_fn => {
                        return Some(Broken {
                            path: rec.path.clone(),
                            line,
                            name: None,
                        })
                    }
                    _ => bodies.push(member),
                }
            }
            stack.extend(self.scc_adj[scc].iter().copied());
        }
        if self.swallowed.is_empty() {
            return None;
        }
        let mut reads: Vec<&CallRec> = self.pin_calls(path, start, end, punch, prefix).collect();
        let mut stretches: Vec<(&Path, Stretch<'_>)> = vec![(path, (start, end, punch))];
        stretches.extend(
            prefix
                .iter()
                .map(|(s, e, holes)| (path, (*s, *e, holes.as_slice()))),
        );
        for &member in &bodies {
            let rec = &self.functions[member];
            for &(s, e) in &rec.reads {
                stretches.push((rec.path.as_path(), (s, e, &[])));
                reads.extend(
                    in_file(&self.calls_in, &rec.path)
                        .iter()
                        .map(|&i| &self.calls[i])
                        .filter(|c| within(c, (s, e, &[]))),
                );
            }
        }
        reads.extend(self.unbound.iter().filter(|c| {
            stretches
                .iter()
                .any(|&(at, stretch)| within(c, stretch) && c.path == at)
        }));
        reads
            .into_iter()
            .filter(|c| c.callees.is_empty() && !c.local && c.mark != Some(CallMark::Skip))
            .find_map(|c| {
                let hides = self.swallowed.iter().find(|s| {
                    s.lang == c.lang
                        && (in_cone(&c.path, &s.path) || c.mark == Some(CallMark::Follow))
                        && s.spells(&c.name)
                })?;
                Some(Broken {
                    path: hides.path.clone(),
                    line: hides.line,
                    name: Some(c.name.clone()),
                })
            })
    }

    /// Whether the project declares a function, class or constant named `name` in the language
    /// family of `lang`.
    pub fn declares(&self, lang: &LangSpec, name: &str) -> bool {
        // § rr512n5e2.g@c409g
        let family = family(lang);
        self.functions
            .iter()
            .any(|f| f.lang == family && f.name == name)
    }

    /// Whether a call or a read of the span at `start..end` of `path`, outside every `punch`
    /// range, follows a declaration of the project.
    pub fn follows_any(
        &self,
        path: &Path,
        start: usize,
        end: usize,
        punch: &[(usize, usize)],
    ) -> bool {
        // A call within the cycle of the function around the span is that function's own
        // recursion: its body is the span's code, whatever cut stops callers from reading it.
        let own = innermost_fn(&self.functions, &self.fns_in, path, start, end)
            .map(|idx| self.scc_of[idx]);
        self.span_calls(path, start, end, punch).any(|call| {
            call.callees
                .iter()
                .any(|&c| self.functions[c].follows(call.mark) || Some(self.scc_of[c]) == own)
        })
    }

    /// Whether a call of the span at `start..end` of `path`, outside every `punch` range,
    /// denotes a boundary whose own marker carries the law of `addr`, whose pin then guards the
    /// code that acts.
    pub fn calls_boundary_of(
        &self,
        path: &Path,
        start: usize,
        end: usize,
        punch: &[(usize, usize)],
        addr: &crate::marker::MarkerAddr,
    ) -> bool {
        // § rr512n5e2.ga@yp2g2
        let of_law = |callee: usize| {
            self.spans.iter().any(|z| {
                z.boundary_of == Some(callee) && z.law.0 == addr.project && z.law.1 == addr.id
            })
        };
        self.span_calls(path, start, end, punch)
            .any(|call| call.callees.iter().any(|&c| of_law(c)))
    }

    /// The calls of `path` inside `start..end` and outside every `punch` range: a call in a
    /// nested span is that span's to follow, not its outer span's.
    fn span_calls<'a>(
        &'a self,
        path: &Path,
        start: usize,
        end: usize,
        punch: &'a [(usize, usize)],
    ) -> impl Iterator<Item = &'a CallRec> + 'a {
        in_file(&self.calls_in, path)
            .iter()
            .map(|&i| &self.calls[i])
            .filter(move |call| within(call, (start, end, punch)))
    }

    /// The calls and reads a pin of the span follows: those of `span_calls`, and each read in
    /// `prefix`, the code the pin reads around the span, that names no function or class.
    fn pin_calls<'a>(
        &'a self,
        path: &Path,
        start: usize,
        end: usize,
        punch: &'a [(usize, usize)],
        prefix: &'a [span_lang::Stretch],
    ) -> impl Iterator<Item = &'a CallRec> + 'a {
        // § kv22y3ap6.g@0mtpq
        let constant = |call: &CallRec| {
            call.value
                && call
                    .callees
                    .iter()
                    .all(|&c| self.functions[c].kind == Kind::Value)
        };
        let around = in_file(&self.calls_in, path)
            .iter()
            .map(|&i| &self.calls[i])
            .filter(move |call| {
                constant(call)
                    && prefix
                        .iter()
                        .any(|(s, e, holes)| within(call, (*s, *e, holes.as_slice())))
            });
        self.span_calls(path, start, end, punch).chain(around)
    }

    pub fn pin_blob(
        &self,
        path: &Path,
        span_start: usize,
        span_end: usize,
        punch: &[(usize, usize)],
        prefix: &[span_lang::Stretch],
    ) -> String {
        // § m6v1vwnh0@atjzp
        let self_fn = innermost_fn(&self.functions, &self.fns_in, path, span_start, span_end);
        let self_scc = self_fn.map(|idx| self.scc_of[idx]);
        let mut outgoing = BTreeSet::new();
        let mut reaches_own = false;
        let mut lines = BTreeSet::new();
        for call in self.pin_calls(path, span_start, span_end, punch, prefix) {
            lines.extend(self.import_lines_of(call));
            for callee in self.followed_by(call) {
                let callee_scc = self.scc_of[callee];
                if Some(callee_scc) == self_scc {
                    reaches_own = true;
                } else {
                    outgoing.insert(self.supernode[callee_scc].clone());
                }
            }
        }
        // A span that calls into its own cycle reads every other member, and what each of
        // them follows out of the cycle, since any of them may run under that call.
        let mut parts: Vec<String> = Vec::new();
        if let Some(scc) = self_scc.filter(|_| reaches_own) {
            parts.extend(
                self.members[scc]
                    .iter()
                    .filter(|&&i| Some(i) != self_fn)
                    .map(|&i| self.functions[i].shape.clone()),
            );
            outgoing.extend(self.scc_adj[scc].iter().map(|&n| self.supernode[n].clone()));
        }
        parts.sort();
        parts.extend(outgoing);
        parts.extend(lines.into_iter().map(|line| format!("§import {line}")));
        if parts.is_empty() {
            String::new()
        } else {
            format!("\n{}", parts.join("\n"))
        }
    }
}

/// Whether `call` lies in the stretch and outside its holes.
fn within(call: &CallRec, (start, end, holes): Stretch<'_>) -> bool {
    call.start >= start
        && call.end <= end
        && !holes.iter().any(|&(s, e)| call.start >= s && call.end <= e)
}

/// Which bodies of its name a call may reach by the text of its qualifier.
#[derive(Clone, Copy)]
enum Place<'a> {
    /// The members of the class, `impl`, trait, enum or namespace of that name.
    Owner(&'a str),
    /// What no class, `impl` or trait holds.
    Free,
    /// Every homonym.
    Any,
}

/// The body `call` denotes, if one: the candidates `candidates_of` leaves, when they are one
/// body or `cfg` twins of Rust, and only those whose file sits in the directory of the caller's
/// file or below it, unless a `functional` or `follow` mark pulls them in.
fn callees_of(lookup: &Lookup<'_>, call: &CallRec) -> Vec<usize> {
    let functions = lookup.functions;
    let mut out = candidates_of(lookup, call);
    // § jncrstyg1.d@nn95q
    // A method on a value names no owner, so a follow mark reads the one method of its name.
    if out.is_empty() && call.mark == Some(CallMark::Follow) && !call.scope.is_empty() {
        out = methods_named(lookup, call);
        if out.len() > 1 {
            out.clear();
        }
    }
    // § end jncrstyg1.d
    // § pyw49tg9j.f@qr781
    let twins = out
        .iter()
        .all(|&i| functions[i].lang == "rust" && functions[i].cfg);
    if out.len() > 1 && !twins {
        out.clear();
    }
    // § end pyw49tg9j.f
    // § jncrstyg1.g@kpwm7
    out.retain(|&i| {
        in_cone(&call.path, &functions[i].path)
            || call.mark == Some(CallMark::Follow)
            || functions[i].decl == Some(DeclMark::Functional)
    });
    // § end jncrstyg1.g
    out
}

/// Whether `callee_file` sits in the directory of `caller_file` or below it.
fn in_cone(caller_file: &Path, callee_file: &Path) -> bool {
    callee_file.starts_with(caller_file.parent().unwrap_or(Path::new("")))
}

/// Every body of the project the last name of `call` may name, in its language and its kind of
/// test code: through `self`, `this`, `cls` or `Self`, the members of the class or `impl` around
/// it; through a qualifier that starts with a capital, the members of the class, type, trait
/// or namespace of that name; bare or through any other qualifier, every body no class, `impl`
/// or trait holds. A call that such a restriction leaves with no body may name every homonym.
fn candidates_of(lookup: &Lookup<'_>, call: &CallRec) -> Vec<usize> {
    let Lookup {
        functions,
        by_name,
        imports,
        outside,
    } = *lookup;
    // § pyw49tg9j.a@9p4sq
    if call.local {
        return Vec::new();
    }
    // § end pyw49tg9j.a
    // § pyw49tg9j.c@edd3r
    let capital = call
        .scope
        .last()
        .map(String::as_str)
        .filter(|q| q.starts_with(|c: char| c.is_uppercase()));
    let place = match &call.receiver {
        Some(Some(class)) => Place::Owner(class),
        Some(None) if call.value => return Vec::new(),
        Some(None) => Place::Any,
        None => capital.map_or(Place::Free, Place::Owner),
    };
    // § end pyw49tg9j.c
    // § pyw49tg9j.g@w3mgf
    // A function never stands in a pattern, which only a constant makes a match.
    let kind_fits = |rec: &FnRec| match rec.kind {
        Kind::Class => !call.value && !call.pattern,
        Kind::Value => true,
        Kind::Function => !call.pattern,
    };
    let fits =
        |rec: &FnRec| rec.lang == call.lang && reaches(call.test, rec.test) && kind_fits(rec);
    // § end pyw49tg9j.g
    let homonyms = |place: Place<'_>| -> Vec<usize> {
        by_name
            .get(call.name.as_str())
            .into_iter()
            .flatten()
            .copied()
            .filter(|&i| {
                let rec = &functions[i];
                let held = match place {
                    Place::Owner(owner) => rec.owner.as_deref() == Some(owner),
                    Place::Free => !rec.member,
                    Place::Any => true,
                };
                held && fits(rec)
            })
            .collect()
    };
    let mut out = homonyms(place);
    // § pyw49tg9j.ba@mc6wc
    // Bash defines a nested function for the whole program once its outer one runs.
    let holds_call = |&i: &usize| {
        functions[i].path == call.path
            && functions[i]
                .nested_in
                .is_some_and(|(s, e)| s <= call.start && call.end <= e)
    };
    if call.scope.is_empty() && call.receiver.is_none() && call.lang != "bash" {
        let innermost = out
            .iter()
            .filter(|i| holds_call(i))
            .filter_map(|&i| functions[i].nested_in)
            .min_by_key(|&(s, e)| e - s);
        if innermost.is_some() {
            out.retain(|i| holds_call(i) && functions[*i].nested_in == innermost);
            return out;
        }
    }
    // § end pyw49tg9j.ba
    // § pyw49tg9j.b@nx716
    // A bare name its own file declares outside any function and class is that declaration,
    // unless an import line of the file spells the name, which may bind it elsewhere.
    let bare = call.scope.is_empty() && call.receiver.is_none();
    let spelled = |name: &str| {
        imports
            .get(&call.path)
            .into_iter()
            .flatten()
            .any(|l| l.names.contains(name))
    };
    let own = |&i: &usize| functions[i].top && functions[i].path == call.path;
    if bare && out.iter().any(own) {
        if spelled(&call.name) && !outside.holds(call) {
            return out;
        }
        out.retain(own);
        return out;
    }
    // § end pyw49tg9j.b
    if call.receiver.is_none() && outside.holds(call) {
        return Vec::new();
    }
    // § pyw49tg9j.j@w8b7q
    if call.lang == "rust" && call.receiver.is_none() {
        let lines = imports
            .get(&call.path)
            .map(Vec::as_slice)
            .unwrap_or_default();
        let crates = outside.crates_named(call, lines);
        let held = |&i: &usize| {
            outside
                .crate_of(&functions[i].path)
                .is_some_and(|dir| crates.contains(&dir))
        };
        if out.iter().any(held) {
            out.retain(held);
        }
    }
    // § end pyw49tg9j.j
    // § pyw49tg9j.k@9fsqj
    if bare {
        let targets: BTreeSet<PathBuf> = imports
            .get(&call.path)
            .into_iter()
            .flatten()
            .flat_map(|l| &l.binds)
            .filter_map(|b| match &b.origin {
                Origin::Near(near) if b.name == call.name => Some(near_path(&call.path, near)),
                _ => None,
            })
            .collect();
        if let [target] = Vec::from_iter(targets).as_slice() {
            let named = |&i: &usize| {
                names_file(&functions[i].path, target) && !outside.star.contains(&functions[i].path)
            };
            if out.iter().any(named) {
                out.retain(named);
            }
        }
    }
    // § end pyw49tg9j.k
    // § pyw49tg9j.d@jv225
    // A qualifier names a module by its own text: the homonyms of the files it names, when one
    // of them declares the name.
    let by_qualifier = |out: &mut Vec<usize>, q: &str| {
        let named_by = |&i: &usize| names_unit(&functions[i].path, q);
        if out.iter().any(named_by) {
            out.retain(named_by);
        }
    };
    if let (Place::Free, Some(q)) = (place, call.scope.last()) {
        by_qualifier(&mut out, q);
    }
    // § end pyw49tg9j.d
    // § pyw49tg9j.e@xsv2k
    // A qualifier that names no member of that name restricts to nothing: the call names
    // every homonym instead, those of the module a capitalised qualifier names first. A read
    // through a receiver is an instance attribute, read by none.
    let call_or_named = call.receiver.is_none() || !call.value;
    if out.is_empty() && matches!(place, Place::Owner(_)) && call_or_named {
        out = homonyms(Place::Any);
        if let (None, Some(q)) = (&call.receiver, capital) {
            by_qualifier(&mut out, q);
        }
    }
    // § end pyw49tg9j.e
    out
}

/// The tables a call is looked up in.
#[derive(Clone, Copy)]
struct Lookup<'a> {
    functions: &'a [FnRec],
    by_name: &'a BTreeMap<&'a str, Vec<usize>>,
    imports: &'a HashMap<PathBuf, Vec<ImportLine>>,
    outside: &'a Outside,
}

/// The directories and file stems of `path`.
fn path_segments(path: &Path) -> impl Iterator<Item = &str> {
    let last = path.file_stem().and_then(|s| s.to_str());
    path.parent()
        .into_iter()
        .flat_map(|p| p.components())
        .filter_map(|c| c.as_os_str().to_str())
        .chain(last)
}

/// What the text of a project says lies outside it: per file, the names its import lines bind
/// to the Rust standard crates, to a crate the workspace does not declare, or to a Python,
/// JavaScript or TypeScript module no project file provides by its path, and the Rust crate
/// and module names the project declares.
#[derive(Debug, Default)]
struct Outside {
    external: HashMap<PathBuf, BTreeSet<String>>,
    project: HashMap<PathBuf, BTreeSet<String>>,
    /// The crate names of the workspace and every name a Rust `mod` item or a file path of the
    /// project spells.
    known: BTreeSet<String>,
    /// Every name the project declares a body, a class, an `impl`, a trait or a Rust type
    /// under, which a capitalised qualifier may name.
    declared: BTreeSet<String>,
    /// The directory of each `Cargo.toml`, with the crate names it declares.
    crates: Vec<(PathBuf, Vec<String>)>,
    /// Each JavaScript, TypeScript or Python file that re-exports or imports a module with a
    /// star, whose names any module may then provide.
    star: HashSet<PathBuf>,
}

impl Outside {
    fn of(
        files: &[CodeFile],
        imports: &HashMap<PathBuf, Vec<ImportLine>>,
        functions: &[FnRec],
    ) -> Self {
        let mut known: BTreeSet<String> = BTreeSet::new();
        let mut declared: BTreeSet<String> = functions
            .iter()
            .flat_map(|f| std::iter::once(&f.name).chain(&f.owner))
            .cloned()
            .collect();
        let per_file = crate::par::map(
            files.iter().collect(),
            |file| file.text.len(),
            |file| {
                let mut names = Vec::new();
                let mut types = Vec::new();
                if file.rel.file_name().is_some_and(|n| n == "Cargo.toml") {
                    names.extend(cargo_names(&file.text));
                }
                if file.lang.is_some_and(|lang| family(lang) == "rust") {
                    let (mods, declared) = file.memo(&"rust item names", || {
                        file.tree()
                            .map(|tree| rust_item_names(tree.root_node(), &file.text))
                            .unwrap_or_default()
                    });
                    names.extend(mods);
                    types.extend(declared);
                }
                let star = file
                    .lang
                    .is_some_and(|lang| matches!(family(lang), "javascript" | "python"))
                    && file.tree().is_some_and(|tree| stars(tree.root_node()));
                (names, types, star)
            },
        );
        // Every run of consecutive segments of a project path, which a module path may spell.
        let mut provided_runs: HashSet<Vec<String>> = HashSet::new();
        let mut crates = Vec::new();
        let mut star = HashSet::new();
        for (file, (names, types, stars)) in files.iter().zip(per_file) {
            if stars {
                star.insert(file.rel.clone());
            }
            if file.rel.file_name().is_some_and(|n| n == "Cargo.toml") {
                let dir = file.rel.parent().unwrap_or(Path::new(""));
                crates.push((dir.to_path_buf(), names.clone()));
            }
            let segments: Vec<String> = path_segments(&file.rel).map(str::to_string).collect();
            known.extend(segments.iter().cloned());
            for len in 1..=segments.len() {
                provided_runs.extend(segments.windows(len).map(<[String]>::to_vec));
            }
            known.extend(names);
            declared.extend(types);
        }
        let provided = |module: &[String]| module.is_empty() || provided_runs.contains(module);
        let mut out = Self::default();
        for (path, lines) in imports {
            let (mut external, mut project) = (BTreeSet::new(), BTreeSet::new());
            for Bind { name, origin, .. } in lines.iter().flat_map(|l| &l.binds) {
                let outside = match origin {
                    Origin::Root(root) => {
                        STD_ROOTS.contains(&root.as_str())
                            || (!matches!(root.as_str(), "crate" | "self" | "super")
                                && !known.contains(root))
                    }
                    Origin::Module(module, relative) => !relative && !provided(module),
                    Origin::Near(_) => false,
                };
                if outside {
                    external.insert(name.clone());
                } else {
                    project.insert(name.clone());
                }
            }
            out.external.insert(path.clone(), external);
            out.project.insert(path.clone(), project);
        }
        out.known = known;
        out.declared = declared;
        out.crates = crates;
        out.star = star;
        out
    }

    /// The directory of the crate that holds `path`, the nearest `Cargo.toml` above it.
    fn crate_of(&self, path: &Path) -> Option<&Path> {
        self.crates
            .iter()
            .map(|(dir, _)| dir.as_path())
            .filter(|dir| path.starts_with(dir))
            .max_by_key(|dir| dir.components().count())
    }

    /// The crates a Rust `call` names by the head of its path, or by the `use` paths in `lines`
    /// that bind that head when they agree: the caller's own for `crate`, each that declares the
    /// name otherwise.
    fn crates_named(&self, call: &CallRec, lines: &[ImportLine]) -> Vec<&Path> {
        // § pyw49tg9j.j@qrbnm
        let head = call.scope.first().unwrap_or(&call.name);
        let bound: BTreeSet<&String> = lines
            .iter()
            .flat_map(|l| &l.binds)
            .filter_map(|b| match &b.origin {
                Origin::Root(root) if &b.name == head => Some(root),
                _ => None,
            })
            .collect();
        let mut bound = bound.into_iter();
        let root = match (bound.next(), bound.next()) {
            (Some(root), None) => root,
            (None, _) => match call.scope.first() {
                Some(root) => root,
                None => return Vec::new(),
            },
            _ => return Vec::new(),
        };
        if root == "crate" {
            return self.crate_of(&call.path).into_iter().collect();
        }
        self.crates
            .iter()
            .filter(|(_, names)| names.contains(root))
            .map(|(dir, _)| dir.as_path())
            .collect()
    }

    /// Whether the first name of `call` lies outside the project by its text: bound so by an
    /// import line of its file and by none to the project, a Rust path that starts at a
    /// standard crate or at a crate the project does not declare, or a capitalised qualifier
    /// that the project declares nothing under, `String::new()` or `Math.max()`.
    fn holds(&self, call: &CallRec) -> bool {
        let head = call.scope.first().unwrap_or(&call.name);
        if self
            .project
            .get(&call.path)
            .is_some_and(|p| p.contains(head))
        {
            return false;
        }
        if self
            .external
            .get(&call.path)
            .is_some_and(|e| e.contains(head))
        {
            return true;
        }
        if !call.scope.is_empty()
            && head.starts_with(|c: char| c.is_uppercase())
            && !self.declared.contains(head)
        {
            return true;
        }
        call.lang == "rust"
            && !call.scope.is_empty()
            && (STD_ROOTS.contains(&head.as_str())
                || (head.starts_with(|c: char| c.is_lowercase())
                    && !matches!(head.as_str(), "crate" | "self" | "super")
                    && !self.known.contains(head)))
    }
}

/// Whether a top-level statement under `root` is `export * from ..` or `from .. import *`.
fn stars(root: Node<'_>) -> bool {
    let mut cursor = root.walk();
    let found = root.named_children(&mut cursor).any(|statement| {
        let mut inner = statement.walk();
        let star = statement
            .children(&mut inner)
            .any(|c| matches!(c.kind(), "*" | "wildcard_import"));
        star && matches!(
            statement.kind(),
            "export_statement" | "import_from_statement"
        )
    });
    found
}

/// The library and package names a `Cargo.toml` declares, with `-` read as `_`.
fn cargo_names(text: &str) -> Vec<String> {
    let mut section = String::new();
    let mut out = Vec::new();
    for line in text.lines().map(str::trim) {
        if let Some(header) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
            section = header.trim().to_string();
            continue;
        }
        let Some((key, value)) = line.split_once('=') else {
            continue;
        };
        let value = value.trim().trim_matches('"');
        if matches!(section.as_str(), "package" | "lib") && key.trim() == "name" {
            out.push(value.replace('-', "_"));
        }
    }
    out
}

/// The names of the `mod` items of a Rust file, and of its structs, unions, traits and type
/// aliases, at any depth.
fn rust_item_names(root: Node<'_>, source: &str) -> (Vec<String>, Vec<String>) {
    let (mut mods, mut types) = (Vec::new(), Vec::new());
    let mut stack = vec![root];
    while let Some(node) = stack.pop() {
        match node.kind() {
            "mod_item" => mods.extend(name_field(node, source)),
            "struct_item" | "union_item" | "trait_item" | "type_item" => {
                types.extend(name_field(node, source))
            }
            _ => {}
        }
        let mut cursor = node.walk();
        stack.extend(node.named_children(&mut cursor));
    }
    (mods, types)
}

/// A function is a boundary when a marker's span is the whole function, not an explicit
/// `end` stretch. Its pin already reviews its body, so callers need not hash it again.
/// A bare marker counts too: `fix` mints every new pin of a run from one index, so a
/// caller pinned beside its callee must already see the boundary.
fn mark_boundaries(
    functions: &mut [FnRec],
    fns_in: &HashMap<PathBuf, Vec<usize>>,
    spans: Vec<(PathBuf, (SpanMarker, Vec<span_lang::Stretch>))>,
) -> Vec<SpanRec> {
    // § jncrstyg1.a@xqrzk
    spans
        .into_iter()
        .map(|(path, (z, prefix))| {
            let range = (z.start, z.end);
            let boundary_of = if z.explicit {
                None
            } else {
                in_file(fns_in, &path).iter().copied().find(|&i| {
                    let f = &functions[i];
                    f.kind == Kind::Function && ((f.start, f.end) == range || f.body == Some(range))
                })
            };
            if let Some(idx) = boundary_of {
                functions[idx].boundary = true;
            }
            SpanRec {
                path,
                line: z.line,
                addr: z.addr.display(),
                law: (z.addr.project.clone(), z.addr.id.clone()),
                start: z.start,
                end: z.end,
                boundary_of,
                pinned: z.addr.digest.is_some(),
                prefix,
            }
        })
        .collect()
}

/// Passes the `silcrow:follow` mark of each call that denotes nothing, a call record or a call on
/// a value in `carriers`, to what it holds, as `reach` does. A mark that reaches no body, known by
/// the line of what it takes, is one error naming the outermost calls it takes.
fn pass_marks(
    files: &[CodeFile],
    lookup: &Lookup<'_>,
    calls: &mut [CallRec],
    calls_in: &HashMap<PathBuf, Vec<usize>>,
    carriers: &[(PathBuf, usize, usize)],
) -> Vec<String> {
    // § jncrstyg1.h@71sxa
    let texts: HashMap<&Path, &str> = files
        .iter()
        .map(|f| (f.rel.as_path(), f.text.as_str()))
        .collect();
    let text = |path: &Path| texts.get(path).copied().unwrap_or_default();
    let line = |path: &Path, at: usize| text(path)[..at].matches('\n').count() + 1;
    let roots: Vec<(PathBuf, usize, usize, Option<usize>)> = calls
        .iter()
        .enumerate()
        .filter(|(_, c)| c.mark == Some(CallMark::Follow))
        .map(|(i, c)| (c.path.clone(), c.start, c.end, Some(i)))
        .chain(carriers.iter().map(|(p, s, e)| (p.clone(), *s, *e, None)))
        .collect();
    type Taken = Vec<(usize, usize, String, String)>;
    let mut marks: BTreeMap<(PathBuf, usize), (bool, bool, Taken)> = BTreeMap::new();
    for (path, start, end, idx) in roots {
        let in_path = in_file(calls_in, &path);
        let holds = in_path.iter().any(|&i| {
            let c = &calls[i];
            start <= c.start && c.end <= end && (c.start, c.end) != (start, end)
        });
        let reached = match idx {
            Some(i) if !calls[i].callees.is_empty() => true,
            _ => reach(lookup, calls, in_path, (start, end)),
        };
        // § z0xqn70bp.d@g42n1
        let (named, why) = match idx {
            Some(i) => (spelled_call(&calls[i]), refusal(lookup, &calls[i])),
            None => (
                text(&path)[start..end]
                    .lines()
                    .next()
                    .unwrap_or_default()
                    .trim()
                    .to_string(),
                "a call on a value names no declaration, so the mark passes to what it holds (jncrstyg1.h). Remove the mark, or put it above a call of a project function.".to_string(),
            ),
        };
        // § end z0xqn70bp.d
        let at = line(&path, start);
        let mark = marks.entry((path, at)).or_default();
        mark.0 |= reached;
        mark.1 |= holds;
        mark.2.push((start, end, named, why));
    }
    let mut out: Vec<String> = marks
        .into_iter()
        .filter(|(_, (reached, _, _))| !reached)
        .map(|((path, line), (_, holds, taken))| {
            let held = |s: usize, e: usize| {
                taken
                    .iter()
                    .any(|&(os, oe, _, _)| os <= s && e <= oe && (os, oe) != (s, e))
            };
            let outer: Vec<&(usize, usize, String, String)> =
                taken.iter().filter(|t| !held(t.0, t.1)).collect();
            let named: Vec<&str> = outer.iter().map(|t| t.2.as_str()).collect();
            let why: Vec<String> = match outer.as_slice() {
                [(_, _, _, why)] => vec![why.clone()],
                _ => outer
                    .iter()
                    .map(|(_, _, named, why)| format!("for `{named}`, {why}"))
                    .collect(),
            };
            let held = if holds {
                " No call or name it holds denotes one either, as jncrstyg1.h reads them."
            } else {
                ""
            };
            format!(
                "{}:{line}: `silcrow:follow` marks `{}`, which names no single function, class or constant of the project, so nothing is followed: {}{held}",
                path.display(),
                named.join("`, `"),
                why.join(" ")
            )
        })
        .collect();
    out.sort();
    out
}

/// Marks `silcrow:follow` on each outermost call and read of the file strictly inside `range`
/// that no mark took, and passes on through each that denotes nothing, so the mark stops at the
/// first that denote a body. Whether one does.
fn reach(
    lookup: &Lookup<'_>,
    calls: &mut [CallRec],
    in_path: &[usize],
    (start, end): (usize, usize),
) -> bool {
    // § jncrstyg1.h@s2f7h
    let inside = |c: &CallRec, (s, e): (usize, usize)| {
        s <= c.start && c.end <= e && (c.start, c.end) != (s, e)
    };
    let inner: Vec<usize> = in_path
        .iter()
        .copied()
        .filter(|&i| inside(&calls[i], (start, end)))
        .collect();
    let outer: Vec<usize> = inner
        .iter()
        .copied()
        .filter(|&i| {
            !inner
                .iter()
                .any(|&o| inside(&calls[i], (calls[o].start, calls[o].end)))
        })
        .collect();
    let mut reached = false;
    for i in outer {
        if calls[i].mark.is_some() {
            continue;
        }
        calls[i].mark = Some(CallMark::Follow);
        calls[i].callees = callees_of(lookup, &calls[i]);
        if calls[i].callees.is_empty() {
            calls[i].mark = None;
            reached |= reach(lookup, calls, in_path, (calls[i].start, calls[i].end));
        } else {
            reached = true;
        }
    }
    reached
}

/// `call` as its qualifier and name spell it in its language.
fn spelled_call(call: &CallRec) -> String {
    let sep = if call.lang == "rust" { "::" } else { "." };
    let mut named = call.scope.join(sep);
    if !named.is_empty() {
        named.push_str(sep);
    }
    named + &call.name
}

/// Why the `silcrow:follow` call `call` denotes no single body, and the form that would.
fn refusal(lookup: &Lookup<'_>, call: &CallRec) -> String {
    // § z0xqn70bp.d@h3ne7
    let Lookup {
        functions,
        by_name,
        outside,
        ..
    } = *lookup;
    let name = &call.name;
    let named = |forms: Vec<String>, files: &[usize]| -> String {
        forms
            .into_iter()
            .zip(files)
            .filter(|(form, _)| !form.is_empty())
            .map(|(form, &i)| format!("{form} for {}", path_key(&functions[i].path)))
            .collect::<Vec<_>>()
            .join("; ")
    };
    let method = call.receiver.is_none() && !call.scope.is_empty();
    if method && candidates_of(lookup, call).is_empty() {
        let methods = methods_named(lookup, call);
        if methods.len() > 1 {
            let sep = if call.lang == "rust" { "::" } else { "." };
            let forms: Vec<String> = methods
                .iter()
                .map(|&i| {
                    let owner = functions[i].owner.as_deref().unwrap_or_default();
                    let mut through = call.clone();
                    through.scope = vec![owner.to_string()];
                    through.local = false;
                    let fits = call.lang != "javascript" && candidates_of(lookup, &through) == [i];
                    if fits {
                        format!("`{owner}{sep}{name}(..)`")
                    } else {
                        String::new()
                    }
                })
                .collect();
            let owners: Vec<String> = methods
                .iter()
                .map(|&i| {
                    let owner = functions[i].owner.as_deref().unwrap_or_default();
                    format!("`{owner}{sep}{name}`")
                })
                .collect();
            let forms = named(forms, &methods);
            let fix = if forms.is_empty() {
                "Give the method a name no other method of the project has, or remove the mark."
                    .to_string()
            } else {
                format!("Call it through its type: {forms}.")
            };
            return format!(
                "a method called on a value denotes the one method of its name, and the project declares {}, {} (jncrstyg1.d). {fix}",
                methods.len(),
                owners.join(", ")
            );
        }
    }
    let homonyms: Vec<usize> = by_name
        .get(name.as_str())
        .into_iter()
        .flatten()
        .copied()
        .filter(|&i| functions[i].lang == call.lang)
        .collect();
    if homonyms.is_empty() {
        return format!("the project declares no function, class or constant `{name}` in this language (pyw49tg9j). Remove the mark, or put it above a call of a project function.");
    }
    let sided: Vec<usize> = homonyms
        .iter()
        .copied()
        .filter(|&i| reaches(call.test, functions[i].test))
        .collect();
    if sided.is_empty() {
        return format!("only test code of another kind than the call declares `{name}`, which the call does not reach (pyw49tg9j). Remove the mark.");
    }
    match call.scope.first() {
        _ if !call.local => {}
        None => return format!("`{name}` is a local of the function around it, which denotes no declaration (pyw49tg9j.a). Rename the local, or remove the mark."),
        Some(head) => return format!("`{head}` is a local of the function around it, and a method called on a value denotes the one method of its name, of which the project declares none (jncrstyg1.d). Call the helper by its name, or remove the mark."),
    }
    if call.receiver.is_none() && outside.holds(call) {
        let forms: Vec<String> = sided
            .iter()
            .map(|&i| resolving_forms(lookup, call, i).join(" or "))
            .collect();
        let forms = named(forms, &sided);
        let fix = if forms.is_empty() {
            "Remove the mark.".to_string()
        } else {
            format!("To follow the project's, write {forms}.")
        };
        let head = call.scope.first().unwrap_or(name);
        return format!("`{head}` lies outside the project by its text, a standard or library path or an import from outside (pyw49tg9j.h). {fix}");
    }
    let candidates = candidates_of(lookup, call);
    if candidates.len() > 1 {
        let mut files: Vec<String> = candidates
            .iter()
            .map(|&i| path_key(&functions[i].path))
            .collect();
        files.dedup();
        let forms: Vec<String> = candidates
            .iter()
            .map(|&i| resolving_forms(lookup, call, i).join(" or "))
            .collect();
        let forms = named(forms, &candidates);
        let fix = if forms.is_empty() {
            "Rename one of them, or remove the mark.".to_string()
        } else {
            format!("Name one: {forms}.")
        };
        return format!(
            "`{name}` has {} candidates, {}, and the closed list of pyw49tg9j leaves it none. {fix}",
            candidates.len(),
            files.join(", ")
        );
    }
    if call.pattern {
        return format!("`{name}` stands in a refutable pattern, which reads only a constant or a `static` (pyw49tg9j.g). Remove the mark.");
    }
    format!("`{name}` is read without a call or through a receiver, which reads no function or class of its name (pyw49tg9j.g). Call it, or remove the mark.")
}

/// The methods a call on a value may name for a follow mark: each member function of its name,
/// language and side of test code, other than one around the call.
fn methods_named(lookup: &Lookup<'_>, call: &CallRec) -> Vec<usize> {
    // § jncrstyg1.d@gy89p
    lookup
        .by_name
        .get(call.name.as_str())
        .into_iter()
        .flatten()
        .copied()
        .filter(|&i| {
            let rec = &lookup.functions[i];
            let around = rec.path == call.path && rec.start <= call.start && call.end <= rec.end;
            rec.member
                && !around
                && rec.kind == Kind::Function
                && rec.lang == call.lang
                && reaches(call.test, rec.test)
        })
        .collect()
}

/// The forms of `call` that denote the body `target` alone: a call through the path of its
/// module, `crate_a::ensure(..)` or `rates.fee(..)`, and in Rust a `use` line when the crate the
/// path starts at tells it apart.
fn resolving_forms(lookup: &Lookup<'_>, call: &CallRec, target: usize) -> Vec<String> {
    // § z0xqn70bp.d@mwjsp
    let rec = &lookup.functions[target];
    let denotes = |scope: &[String]| {
        let mut named = call.clone();
        named.scope = scope.to_vec();
        named.local = false;
        named.receiver = None;
        candidates_of(lookup, &named) == [target]
    };
    let segments = |path: &Path| -> Vec<String> {
        let mut segments: Vec<String> = path_segments(path).map(str::to_string).collect();
        if call.lang == "rust" {
            if segments.first().is_some_and(|s| s == "src") {
                segments.remove(0);
            }
            if segments
                .last()
                .is_some_and(|s| matches!(s.as_str(), "lib" | "main" | "mod"))
            {
                segments.pop();
            }
        } else if segments
            .last()
            .is_some_and(|s| matches!(s.as_str(), "__init__" | "index"))
        {
            segments.pop();
        }
        segments
    };
    if call.lang != "rust" {
        let unit = segments(&rec.path).pop();
        return unit
            .filter(|unit| denotes(std::slice::from_ref(unit)))
            .map(|unit| format!("`{unit}.{}(..)`", call.name))
            .into_iter()
            .collect();
    }
    let outside = lookup.outside;
    let home = outside.crate_of(&rec.path);
    let root = if home == outside.crate_of(&call.path) {
        Some("crate".to_string())
    } else {
        outside
            .crates
            .iter()
            .find(|(dir, _)| Some(dir.as_path()) == home)
            .and_then(|(_, names)| names.first().cloned())
    };
    let Some(root) = root else {
        return Vec::new();
    };
    let within = rec
        .path
        .strip_prefix(home.unwrap_or(Path::new("")))
        .unwrap_or(&rec.path);
    let path: Vec<String> = std::iter::once(root).chain(segments(within)).collect();
    let mut out = Vec::new();
    if denotes(&path) {
        out.push(format!("`{}::{}(..)`", path.join("::"), call.name));
    }
    if denotes(&path[..1]) {
        out.push(format!("`use {}::{};`", path.join("::"), call.name));
    }
    out
}

/// A call-site mark attaches to each call or read that starts on the line below it and lies in
/// no other marked one, so a call nested in the arguments or the callee of another is unmarked.
fn outermost_marks(calls: &mut [CallRec], row_of: impl Fn(usize) -> usize) {
    // § jncrstyg1.e@f0v6e
    let marked: Vec<(usize, usize, usize)> = calls
        .iter()
        .filter(|c| c.mark.is_some())
        .map(|c| (row_of(c.start), c.start, c.end))
        .collect();
    for call in calls.iter_mut().filter(|c| c.mark.is_some()) {
        let row = row_of(call.start);
        let nested = marked.iter().any(|&(r, start, end)| {
            r == row
                && start <= call.start
                && call.end <= end
                && (start, end) != (call.start, call.end)
        });
        if nested {
            call.mark = None;
        }
    }
}

/// What one file contributes to the index, gathered on its own thread.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
struct FileNodes {
    functions: Vec<FnRec>,
    calls: Vec<CallRec>,
    imports: Vec<ImportLine>,
    mark_errors: Vec<String>,
    spans: Vec<(SpanMarker, Vec<span_lang::Stretch>)>,
    /// The byte ranges of the outermost calls a `silcrow:follow` mark takes that no call record
    /// names, a call on a value.
    carriers: Vec<(usize, usize)>,
}

struct SourceTree<'a> {
    path: &'a Path,
    source: &'a str,
    lines: &'a [&'a str],
    /// Whether each 0-based line opens inside a string, a heredoc or a template.
    literal: &'a [bool],
    lang: &'a LangSpec,
    /// Whether its calls and reads are gathered, or its declarations alone.
    calls: bool,
    /// The 1-based lines of the follow marks a declaration or a call took.
    used: std::cell::RefCell<BTreeSet<usize>>,
    /// Each class, `impl` and trait, by its byte range and its name.
    classes: Vec<(usize, usize, Option<String>)>,
    /// Every name of the file no binding of the item around it binds, and where each starts.
    free: Vec<(String, usize, usize)>,
    free_at: BTreeSet<usize>,
    /// Its path names the whole file test code.
    in_tests: bool,
    /// 0-based inclusive rows of the Rust items compiled only for tests.
    test_rows: Vec<(usize, usize)>,
    /// 0-based inclusive rows of the Rust items under a `cfg` other than `test`.
    cfg_rows: Vec<(usize, usize)>,
}

impl SourceTree<'_> {
    /// The name of the innermost class, `impl` or trait that holds byte `at`, `None` inside
    /// one with no name, and none outside every one.
    fn class_at(&self, at: usize) -> Option<Option<String>> {
        self.classes
            .iter()
            .filter(|&&(start, end, _)| start <= at && at < end)
            .min_by_key(|&&(start, end, _)| end - start)
            .map(|(_, _, name)| name.clone())
    }

    /// The kind of test code 0-based `row` is, as the code duty counts it, none for other code.
    fn is_test(&self, row: usize) -> Option<TestCode> {
        // § pyw49tg9j@aqvve
        if self.in_tests {
            return Some(TestCode::Dir);
        }
        self.test_rows
            .iter()
            .any(|&(start, end)| start <= row && row <= end)
            .then_some(TestCode::Cfg)
    }

    /// The mark `parse` reads on the line above 1-based `line`, recorded as attached.
    fn mark<T>(&self, line: usize, parse: fn(&str) -> Option<T>) -> Option<T> {
        // § xs2e8kj86.a@64nhx
        let literal = line >= 2 && self.literal.get(line - 2).copied().unwrap_or(false);
        let found = (line >= 2)
            .then(|| self.lines.get(line - 2).copied())
            .flatten()
            .filter(|_| !literal)
            .and_then(parse);
        if found.is_some() {
            self.used.borrow_mut().insert(line - 1);
        }
        found
    }

    /// The declaration mark of `item`, above its doc comments, attributes and decorators.
    fn decl_mark(&self, item: Node<'_>) -> Option<DeclMark> {
        // § jncrstyg1.e@47swe
        let mut head = item;
        if let Some(parent) = item.parent().filter(|p| p.kind() == "decorated_definition") {
            head = parent;
        }
        while let Some(prev) = head.prev_sibling() {
            let text = prev.utf8_text(self.source.as_bytes()).unwrap_or("");
            let doc = prev.kind().contains("comment")
                && ["///", "//!", "/**", "/*!"]
                    .iter()
                    .any(|p| text.starts_with(p));
            if !(doc || matches!(prev.kind(), "attribute_item" | "decorator")) {
                break;
            }
            head = prev;
        }
        self.mark(head.start_position().row + 1, parse_decl_mark)
    }

    /// Each follow mark the file writes that no declaration or call took, or that names no
    /// mark, as a `check` error.
    fn stray_marks(&self, root: Node<'_>) -> Vec<String> {
        // § jncrstyg1.e@7mdzv
        let mut out = Vec::new();
        let mut stack = vec![root];
        while let Some(node) = stack.pop() {
            let mut cursor = node.walk();
            stack.extend(node.children(&mut cursor));
            if !node.kind().contains("comment") {
                continue;
            }
            let line = node.start_position().row + 1;
            let text = node.utf8_text(self.source.as_bytes()).unwrap_or("");
            let Some(payload) = mark_payload(text) else {
                continue;
            };
            const MARKS: [&str; 4] = ["technical", "functional", "skip", "follow"];
            if !MARKS.contains(&payload) {
                // § z0xqn70bp.d@ytptm
                let near = MARKS
                    .iter()
                    .find(|mark| edits(mark, payload) <= 2)
                    .map(|mark| format!(" Write `silcrow:{mark}`."))
                    .unwrap_or_default();
                out.push(format!(
                    "{}:{line}: `silcrow:{payload}` is not a follow mark (jncrstyg1.e).{near} A declaration takes `silcrow:technical` or `silcrow:functional`, a call `silcrow:skip` or `silcrow:follow`.",
                    self.path.display()
                ));
                // § end z0xqn70bp.d
            } else if !self.used.borrow().contains(&line) {
                out.push(format!(
                    "{}:{line}: `silcrow:{payload}` attaches to nothing (jncrstyg1.e). A declaration mark sits above a function or a constant, its doc comments and attributes between, and a call mark on the line above the call: move it there, or remove it.",
                    self.path.display()
                ));
            }
        }
        out.sort();
        out
    }

    /// A body record of `node`, read by `reads`.
    fn record(
        &self,
        node: Node<'_>,
        name: String,
        kind: Kind,
        (owner, member): (Option<&str>, bool),
        reads: Vec<(usize, usize)>,
    ) -> FnRec {
        FnRec {
            path: self.path.to_path_buf(),
            start: node.start_byte(),
            end: node.end_byte(),
            body: named_field(node, "body").map(|b| (b.start_byte(), b.end_byte())),
            reads,
            name,
            decl: self.decl_mark(node),
            shape: String::new(),
            boundary: false,
            lang: family(self.lang),
            owner: owner.map(str::to_string),
            member,
            top: false,
            nested_in: None,
            kind,
            test: self.is_test(node.start_position().row),
            cfg: {
                let row = node.start_position().row;
                self.cfg_rows.iter().any(|&(a, b)| a <= row && row <= b)
            },
            broken: None,
            names_at: Vec::new(),
        }
    }

    fn call(&self, name: String, scope: Vec<String>, start: usize, end: usize) -> CallRec {
        CallRec {
            path: self.path.to_path_buf(),
            start,
            end,
            name,
            scope,
            mark: None,
            lang: family(self.lang),
            value: false,
            pattern: false,
            name_at: start,
            local: false,
            test: self.is_test(self.row_of(start)),
            receiver: None,
            callees: Vec::new(),
        }
    }

    fn row_of(&self, at: usize) -> usize {
        self.source[..at.min(self.source.len())]
            .matches('\n')
            .count()
    }
}

/// The class context of a walk: the class, `impl`, trait or namespace whose body holds a node
/// with no function between, by name, and whether what it declares there is one of its members.
type Context = Option<(Option<String>, bool)>;

impl FileNodes {
    /// `test_rows` are the 0-based inclusive rows of the file compiled only for tests,
    /// `cfg_rows` those under a `cfg` other than `test`, and `in_tests` whether its path names
    /// the whole file test code. `calls` asks for its calls and reads as well as its
    /// declarations.
    fn of(
        file: &CodeFile,
        test_rows: Vec<(usize, usize)>,
        cfg_rows: Vec<(usize, usize)>,
        in_tests: bool,
        calls: bool,
    ) -> Option<Self> {
        let (Some(lang), Some(tree)) = (file.lang, file.tree()) else {
            return None;
        };
        let (path, source) = (file.rel.as_path(), file.text.as_str());
        let lines: Vec<&str> = source.lines().collect();
        // Only a follow mark reads whether a line opens inside a literal.
        let marks = source.contains("silcrow:");
        let literal = match marks {
            true => crate::span::lines_opening_in(source, &span_lang::literal_ranges(lang, tree)),
            false => Vec::new(),
        };
        let root = tree.root_node();
        let mut classes = Vec::new();
        let mut stack = vec![root];
        while let Some(node) = stack.pop() {
            let mut cursor = node.walk();
            stack.extend(node.named_children(&mut cursor));
            if let Some(name) = class_name(node, source) {
                classes.push((node.start_byte(), node.end_byte(), name));
            }
        }
        let free = match calls {
            true => span_lang::free_names(lang, source, tree),
            false => Vec::new(),
        };
        let src = SourceTree {
            // § pyw49tg9j@rmx1b
            path,
            source,
            lines: &lines,
            literal: &literal,
            lang,
            calls,
            used: Default::default(),
            classes,
            free_at: free.iter().map(|&(_, start, _)| start).collect(),
            free,
            in_tests,
            test_rows,
            cfg_rows,
        };
        let mut out = Self {
            functions: Vec::new(),
            calls: Vec::new(),
            imports: import_lines(lang, root, source),
            mark_errors: Vec::new(),
            spans: file
                .span_markers()
                .into_iter()
                .map(|z| {
                    let prefix = file.prefix(z.start, z.end);
                    (z, prefix)
                })
                .collect(),
            carriers: Vec::new(),
        };
        collect_nodes(&src, root, &None, &mut out);
        top_level_values(&src, root, &mut out);
        value_reads(&src, root, &mut out.functions);
        if calls {
            collect_reads(&src, tree, &mut out.calls);
            // A Rust attribute is read as its text: a name it holds, a derive, a proc macro or a
            // field a `#[error("{status}")]` string captures, is not followed.
            let attributes = rust_attributes(lang, root);
            out.calls
                .retain(|c| !attributes.iter().any(|&(s, e)| s <= c.start && c.end <= e));
            let newlines: Vec<usize> = source.match_indices('\n').map(|(at, _)| at).collect();
            let row_of = |at: usize| newlines.partition_point(|&n| n < at);
            outermost_marks(&mut out.calls, row_of);
            // § jncrstyg1.h@30czp
            let held = |(s, e): (usize, usize), (start, end): (usize, usize)| {
                row_of(s) == row_of(start) && s <= start && end <= e && (s, e) != (start, end)
            };
            let marked: Vec<(usize, usize)> = out
                .calls
                .iter()
                .filter(|c| c.mark == Some(CallMark::Follow))
                .map(|c| (c.start, c.end))
                .collect();
            let carriers = out.carriers.clone();
            out.carriers
                .retain(|&c| !marked.iter().chain(&carriers).any(|&outer| held(outer, c)));
            // § end jncrstyg1.h
        }
        if marks {
            out.mark_errors = src.stray_marks(root);
        }
        Some(out)
    }
}

/// The byte ranges of the Rust attributes of a file, outer and inner.
fn rust_attributes(lang: &LangSpec, root: Node<'_>) -> Vec<(usize, usize)> {
    if family(lang) != "rust" {
        return Vec::new();
    }
    let mut out = Vec::new();
    let mut stack = vec![root];
    while let Some(node) = stack.pop() {
        if matches!(node.kind(), "attribute_item" | "inner_attribute_item") {
            out.push((node.start_byte(), node.end_byte()));
            continue;
        }
        let mut cursor = node.walk();
        stack.extend(node.named_children(&mut cursor));
    }
    out
}

/// The name of the class, `impl`, trait or TypeScript namespace `node` declares, `None` for one
/// with no name, none for any other node.
fn class_name(node: Node<'_>, source: &str) -> Option<Option<String>> {
    match node.kind() {
        "impl_item" => Some(
            node.child_by_field_name("type")
                .and_then(|ty| rust_type_name(ty, source)),
        ),
        "trait_item" | "class_definition" | "class_declaration" | "abstract_class_declaration" => {
            Some(name_field(node, source))
        }
        "class" if node.is_named() => Some(name_field(node, source)),
        _ => None,
    }
}

/// The name a Rust type is declared under: `Plan` of `Plan`, `Plan<T>` or `m::Plan`.
fn rust_type_name(ty: Node<'_>, source: &str) -> Option<String> {
    match ty.kind() {
        "type_identifier" => Some(ty.utf8_text(source.as_bytes()).ok()?.to_string()),
        "generic_type" => rust_type_name(ty.child_by_field_name("type")?, source),
        "scoped_type_identifier" => rust_type_name(ty.child_by_field_name("name")?, source),
        _ => None,
    }
}

/// The start of `node` with the attributes or decorators written before it.
fn with_attributes(node: Node<'_>) -> usize {
    if let Some(parent) = node.parent().filter(|p| p.kind() == "decorated_definition") {
        return parent.start_byte();
    }
    let mut start = node.start_byte();
    let mut prev = node.prev_named_sibling();
    while let Some(p) = prev {
        match p.kind() {
            "attribute_item" => start = p.start_byte(),
            "line_comment" | "block_comment" => {}
            _ => break,
        }
        prev = p.prev_named_sibling();
    }
    start
}

/// Every function, class, Rust `const`, `static` and enum, TypeScript enum, Python class
/// attribute and JavaScript or TypeScript `static` field `node` holds, with every call it holds.
fn collect_nodes(file: &SourceTree<'_>, node: Node<'_>, context: &Context, out: &mut FileNodes) {
    let source = file.source;
    let kind = node.kind();
    let (owner, member) = context
        .as_ref()
        .map_or((None, false), |(o, m)| (o.as_deref(), *m));
    if is_fn_kind(kind) || (kind == "method_definition" && member) {
        if let Some(name) = name_field(node, source) {
            let reads = vec![(with_attributes(node), node.end_byte())];
            let mut rec = file.record(node, name, Kind::Function, (owner, member), reads);
            rec.names_at = named_field(node, "name")
                .map(|n| n.start_byte())
                .into_iter()
                .collect();
            out.functions.push(rec);
        }
    }
    // § kv22y3ap6.e@10p6k
    match (family(file.lang), kind) {
        ("rust", "const_item" | "static_item") => {
            if let Some(name) = named_field(node, "name").filter(|n| n.kind() == "identifier") {
                let name = name.utf8_text(source.as_bytes()).unwrap_or("").to_string();
                let reads = vec![(with_attributes(node), node.end_byte())];
                out.functions
                    .push(file.record(node, name, Kind::Value, (owner, member), reads));
            }
        }
        // An instance field that holds a function is a method, called through `this`.
        ("javascript", "field_definition" | "public_field_definition") if member => {
            let name = node
                .child_by_field_name("property")
                .or_else(|| node.child_by_field_name("name"))
                .filter(|n| n.kind() == "property_identifier");
            let function = node.child_by_field_name("value").is_some_and(|v| {
                matches!(
                    v.kind(),
                    "arrow_function" | "function_expression" | "function"
                )
            });
            let kind = match (is_static(node), function) {
                (true, _) => Some(Kind::Value),
                (false, true) => Some(Kind::Function),
                (false, false) => None,
            };
            if let (Some(at), Some(kind)) = (name, kind) {
                let name = at.utf8_text(source.as_bytes()).unwrap_or("").to_string();
                let reads = vec![(node.start_byte(), node.end_byte())];
                let mut rec = file.record(node, name, kind, (owner, member), reads);
                if kind == Kind::Function {
                    rec.names_at = vec![at.start_byte()];
                }
                out.functions.push(rec);
            }
        }
        ("python", "expression_statement") if member => {
            for name in assigned_names(node, source) {
                let reads = vec![(node.start_byte(), node.end_byte())];
                out.functions
                    .push(file.record(node, name, Kind::Value, (owner, member), reads));
            }
        }
        // § kv22y3ap6.d@68z4g
        ("python", "class_definition")
        | ("javascript", "class_declaration" | "abstract_class_declaration") => {
            if let Some(name) = name_field(node, source) {
                let reads = class_reads(node, source);
                out.functions
                    .push(file.record(node, name, Kind::Class, (owner, member), reads));
            }
        }
        // § end kv22y3ap6.d
        _ => {}
    }
    // § end kv22y3ap6.e
    // § pyw49tg9j@zcw7m
    let call = file.calls.then(|| {
        jsx_component(file.lang, node, source).or_else(|| {
            (span_lang::is_call_kind(kind) && kind != "macro_invocation")
                .then(|| callee_ident(node, source))
                .flatten()
        })
    });
    if let Some((name, scope, head, name_at, method)) = call.flatten() {
        let mut call = file.call(name, scope, node.start_byte(), node.end_byte());
        call.name_at = name_at;
        call.mark = file.mark(node.start_position().row + 1, parse_call_mark);
        set_receiver(file, &mut call, head, method);
        out.calls.push(call);
    } else if file.calls && span_lang::is_call_kind(kind) && kind != "macro_invocation" {
        // § jncrstyg1.h@mzth4
        let follow = |line: &str| parse_call_mark(line).filter(|&m| m == CallMark::Follow);
        if file.mark(node.start_position().row + 1, follow).is_some() {
            out.carriers.push((node.start_byte(), node.end_byte()));
        }
        // § end jncrstyg1.h
    }
    // § end pyw49tg9j
    // A namespace names its members for a qualifier, which a bare name still reaches.
    let inner: Context = if let Some(name) = class_name(node, source) {
        Some((name, true))
    } else if kind == "internal_module" {
        Some((name_field(node, source), false))
    } else if is_fn_kind(kind) || is_closure_kind(kind) {
        None
    } else {
        context.clone()
    };
    let mut cursor = node.walk();
    if cursor.goto_first_child() {
        loop {
            collect_nodes(file, cursor.node(), &inner, out);
            if !cursor.goto_next_sibling() {
                break;
            }
        }
    }
}

/// Sets what `call`, whose callee starts at `head`, is called through: a receiver `self`,
/// `this`, `cls` or `Self` and the class or `impl` around it, or a local of a function around
/// it, which names no body of the project.
fn set_receiver(file: &SourceTree<'_>, call: &mut CallRec, head: usize, method: bool) {
    let receiver = match (file.lang.id, call.scope.as_slice()) {
        ("rust", [s]) => s == "Self" || (s == "self" && method),
        ("python", [s]) => s == "self" || s == "cls",
        ("javascript" | "typescript" | "tsx", [s]) => s == "this",
        _ => false,
    };
    if receiver {
        call.receiver = Some(file.class_at(call.start).flatten());
        return;
    }
    // § pyw49tg9j.a@y2vtg
    // Bash has no local function names, and a Rust path never starts at a local.
    let checked = match file.lang.id {
        "bash" => false,
        "rust" => call.scope.is_empty(),
        _ => true,
    };
    if checked {
        call.local = !file.free_at.contains(&head);
    }
    // § end pyw49tg9j.a
}

/// The Python, JavaScript and TypeScript variables the top level of the file binds, one record
/// per name: the target of an assignment, an augmented assignment, a `for` loop or a walrus, and
/// a `const`, `let` or `var`, at any depth of the top-level statements outside any function and
/// class.
fn top_level_values(file: &SourceTree<'_>, root: Node<'_>, out: &mut FileNodes) {
    // § kv22y3ap6.e@dep2g
    let lang = family(file.lang);
    if !matches!(lang, "python" | "javascript") {
        return;
    }
    let mut seen: BTreeSet<String> = BTreeSet::new();
    let mut cursor = root.walk();
    for statement in root.named_children(&mut cursor) {
        if holds_a_body(statement) {
            continue;
        }
        let mut names = Vec::new();
        let mut stack = vec![statement];
        while let Some(node) = stack.pop() {
            if node.id() != statement.id() && (holds_a_body(node) || is_closure_kind(node.kind())) {
                continue;
            }
            let target = match node.kind() {
                "assignment"
                | "augmented_assignment"
                | "for_statement"
                | "for_in_statement"
                | "assignment_expression"
                | "augmented_assignment_expression" => node.child_by_field_name("left"),
                "variable_declarator" | "named_expression" => node.child_by_field_name("name"),
                _ => None,
            };
            if let Some(target) = target {
                binding_names(target, file.source, &mut names);
            }
            let mut inner = node.walk();
            stack.extend(node.named_children(&mut inner));
        }
        for name in names {
            if seen.insert(name.clone()) {
                out.functions.push(file.record(
                    statement,
                    name,
                    Kind::Value,
                    (None, false),
                    Vec::new(),
                ));
            }
        }
    }
    // § end kv22y3ap6.e
}

/// Each name a target or a pattern binds: a name, and the names of a tuple, list, object or
/// array pattern, but not a member or a subscript, which change a name and bind none.
fn binding_names(node: Node<'_>, source: &str, out: &mut Vec<String>) {
    let text = || node.utf8_text(source.as_bytes()).unwrap_or("").to_string();
    match node.kind() {
        "identifier" | "shorthand_property_identifier_pattern" => out.push(text()),
        "pattern_list" | "tuple_pattern" | "list_pattern" | "list_splat_pattern"
        | "object_pattern" | "array_pattern" | "rest_pattern" => {
            let mut cursor = node.walk();
            for child in node.named_children(&mut cursor) {
                binding_names(child, source, out);
            }
        }
        "pair_pattern" => {
            if let Some(value) = node.child_by_field_name("value") {
                binding_names(value, source, out);
            }
        }
        "assignment_pattern" | "object_assignment_pattern" => {
            if let Some(left) = node.child_by_field_name("left") {
                binding_names(left, source, out);
            }
        }
        _ => {}
    }
}

/// The Python names an assignment statement of a class body binds.
fn assigned_names(statement: Node<'_>, source: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut cursor = statement.walk();
    for child in statement.named_children(&mut cursor) {
        if matches!(child.kind(), "assignment" | "augmented_assignment") {
            if let Some(left) = child.child_by_field_name("left") {
                binding_names(left, source, &mut out);
            }
        }
    }
    out
}

/// Whether the statement `node` declares a function, a class, an `impl`, a trait or a module
/// body, which its own records read.
fn holds_a_body(node: Node<'_>) -> bool {
    let kind = node.kind();
    is_fn_kind(kind)
        || matches!(
            kind,
            "decorated_definition"
                | "class_definition"
                | "class_declaration"
                | "abstract_class_declaration"
                | "impl_item"
                | "trait_item"
        )
        || (kind == "mod_item" && node.child_by_field_name("body").is_some())
        || (kind == "export_statement"
            && node
                .child_by_field_name("declaration")
                .is_some_and(holds_a_body))
}

/// Reads each constant and enum by its declaration and every top-level statement of its file
/// that spells its name, a token, whatever its form, but one that declares a function, a
/// class, an `impl`, a trait or a module body. Every spelling of the name there is what it
/// declares.
fn value_reads(file: &SourceTree<'_>, root: Node<'_>, functions: &mut [FnRec]) {
    // § kv22y3ap6.f@b8qww
    let mut statements: Vec<(usize, usize, BTreeMap<String, Vec<usize>>)> = Vec::new();
    let mut cursor = root.walk();
    // A Rust item at the top level declares and never changes another: only its declaration
    // is read.
    let items = if family(file.lang) == "rust" {
        Vec::new()
    } else {
        root.named_children(&mut cursor).collect()
    };
    for statement in items {
        if holds_a_body(statement) || statement.kind().contains("comment") {
            continue;
        }
        let mut leaves: BTreeMap<String, Vec<usize>> = BTreeMap::new();
        let mut stack = vec![statement];
        while let Some(node) = stack.pop() {
            if node.child_count() == 0 {
                let text = node.utf8_text(file.source.as_bytes()).unwrap_or("");
                leaves
                    .entry(text.to_string())
                    .or_default()
                    .push(node.start_byte());
                continue;
            }
            let mut inner = node.walk();
            stack.extend(node.children(&mut inner));
        }
        statements.push((statement.start_byte(), statement.end_byte(), leaves));
    }
    for rec in functions.iter_mut().filter(|r| r.kind == Kind::Value) {
        let mut reads = rec.reads.clone();
        let mut names_at = Vec::new();
        for (start, end, leaves) in &statements {
            if let Some(at) = leaves.get(&rec.name) {
                reads.push((*start, *end));
                names_at.extend(at.iter().copied());
            }
        }
        if reads.is_empty() {
            reads.push((rec.start, rec.end));
        }
        reads.sort_unstable();
        let mut kept: Vec<(usize, usize)> = Vec::new();
        for (s, e) in reads {
            match kept.last_mut() {
                Some(last) if s < last.1 => last.1 = last.1.max(e),
                _ => kept.push((s, e)),
            }
        }
        // The spellings in its own declaration outside the top-level statements.
        let own = &rec.reads;
        let mut stack = vec![root];
        while let Some(node) = stack.pop() {
            let inside = own
                .iter()
                .any(|&(s, e)| node.start_byte() < e && node.end_byte() > s);
            if !inside {
                continue;
            }
            if node.child_count() == 0 {
                if node.utf8_text(file.source.as_bytes()).ok() == Some(rec.name.as_str()) {
                    names_at.push(node.start_byte());
                }
                continue;
            }
            let mut inner = node.walk();
            stack.extend(node.children(&mut inner));
        }
        names_at.sort_unstable();
        names_at.dedup();
        rec.reads = kept;
        rec.names_at = names_at;
    }
    // § end kv22y3ap6.f
}

/// Every read a name makes without a call: a free name, a Rust path or type, a name inside a
/// Rust macro argument, a read `m.NAME` whose head is a free name, and a read through `self`,
/// `this` or `cls`.
fn collect_reads(file: &SourceTree<'_>, tree: &tree_sitter::Tree, calls: &mut Vec<CallRec>) {
    let (lang, source) = (file.lang, file.source);
    let root = tree.root_node();
    let read = |name: String, scope: Vec<String>, node: Node<'_>| {
        let mut rec = file.call(name, scope, node.start_byte(), node.end_byte());
        rec.value = true;
        rec.mark = file.mark(node.start_position().row + 1, parse_call_mark);
        rec
    };
    // § kv22y3ap6.d@wxpdk
    // The callee of a bare call is that call, which a mark may skip, not a read of its own.
    let mut taken: BTreeSet<usize> = calls
        .iter()
        .filter(|c| c.scope.is_empty())
        .map(|c| c.start.max(c.name_at))
        .collect();
    taken.extend(
        calls
            .iter()
            .filter(|c| c.scope.is_empty())
            .map(|c| c.name_at),
    );
    if lang.id == "rust" {
        // § kv22y3ap6.e@dvfyh
        rust_paths(root, source, &mut |name, scope, node| {
            let mut rec = read(name, scope, node);
            if rec.scope == ["Self"] {
                rec.receiver = Some(file.class_at(rec.start).flatten());
            }
            calls.push(rec);
        });
        macro_calls(root, source, &file.free_at, &mut taken, &mut |call| {
            let (name, scope, start, end, called) = call;
            let mut rec = file.call(name, scope, start, end);
            rec.value = !called;
            rec.mark = file.mark(file.row_of(start) + 1, parse_call_mark);
            calls.push(rec);
        });
    }
    // § pyw49tg9j.b@rmay7
    if matches!(family(lang), "python" | "javascript") {
        module_reads(root, source, &mut |name, scope, node, head| {
            let mut rec = read(name, scope, node);
            set_receiver(file, &mut rec, head, false);
            calls.push(rec);
        });
    }
    // § end pyw49tg9j.b
    for (name, start, end) in &file.free {
        let node = root.descendant_for_byte_range(*start, *end);
        let qualifier = node.is_some_and(is_path_qualifier);
        if !qualifier && !taken.contains(start) {
            let mut rec = file.call(name.clone(), Vec::new(), *start, *end);
            rec.value = true;
            rec.pattern = lang.id == "rust" && node.is_some_and(span_lang::refutable);
            rec.mark = file.mark(file.row_of(*start) + 1, parse_call_mark);
            calls.push(rec);
        }
    }
    // § end kv22y3ap6.d
}

/// Every path read `a::NAME` outside a `use` and outside a call's callee, with its last name,
/// its qualifier and the node of that name.
fn rust_paths<'a>(
    node: Node<'a>,
    source: &str,
    read: &mut impl FnMut(String, Vec<String>, Node<'a>),
) {
    match node.kind() {
        "use_declaration" | "scoped_type_identifier" => return,
        "scoped_identifier" => {
            let callee = node.parent().is_some_and(|p| {
                p.kind() == "call_expression"
                    && p.child_by_field_name("function")
                        .is_some_and(|f| f.id() == node.id())
            });
            let at = node.child_by_field_name("name").filter(|_| !callee);
            if let Some((at, (name, scope))) = at.zip(scoped_name(node, source)) {
                read(name, scope, at);
            }
            return;
        }
        _ => {}
    }
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        rust_paths(child, source, read);
    }
}

/// Whether `node` is the qualifier of a Rust path `a::b`, a module or a type, never a value.
fn is_path_qualifier(node: Node<'_>) -> bool {
    node.parent().is_some_and(|p| {
        matches!(p.kind(), "scoped_identifier" | "scoped_type_identifier")
            && p.child_by_field_name("path")
                .is_some_and(|q| q.id() == node.id())
    })
}

/// A call or read a Rust macro argument writes: its last name, its qualifier, its byte range
/// and whether a parenthesised group follows it.
type MacroCall = (String, Vec<String>, usize, usize, bool);

/// Every call `f(..)` or `a::b::f(..)` and path read `a::b::NAME` inside the token trees of
/// Rust macro invocations, whose head is a free name or `crate`, `self` or `super`. Each name
/// of such a path, and each name after `.`, a field or a method, goes into `taken`, so no free
/// read is made of it.
fn macro_calls(
    node: Node<'_>,
    source: &str,
    free_at: &BTreeSet<usize>,
    taken: &mut BTreeSet<usize>,
    emit: &mut impl FnMut(MacroCall),
) {
    if node.kind() == "token_tree" {
        let mut cursor = node.walk();
        let tokens: Vec<Node<'_>> = node.children(&mut cursor).collect();
        let text = |n: Node<'_>| n.utf8_text(source.as_bytes()).unwrap_or("").to_string();
        let mut at = 0;
        while at < tokens.len() {
            let head = tokens[at];
            let after_dot = at > 0 && text(tokens[at - 1]) == ".";
            let named = matches!(head.kind(), "identifier" | "crate" | "self" | "super");
            if !named || after_dot {
                if head.kind() == "identifier" && after_dot {
                    taken.insert(head.start_byte());
                }
                at += 1;
                continue;
            }
            let mut path = vec![head];
            while at + 2 < tokens.len()
                && text(tokens[at + 1]) == "::"
                && tokens[at + 2].kind() == "identifier"
            {
                at += 2;
                path.push(tokens[at]);
            }
            at += 1;
            let free = head.kind() != "identifier" || free_at.contains(&head.start_byte());
            let last = *path.last().expect("a path holds its head");
            let called = tokens
                .get(at)
                .is_some_and(|t| t.kind() == "token_tree" && text(*t).starts_with('('));
            if path.len() > 1 {
                taken.extend(path.iter().map(|n| n.start_byte()));
            }
            if free && (path.len() > 1 || called) {
                taken.insert(last.start_byte());
                let scope = path[..path.len() - 1].iter().map(|n| text(*n)).collect();
                emit((
                    text(last),
                    scope,
                    last.start_byte(),
                    last.end_byte(),
                    called,
                ));
            }
        }
    }
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        macro_calls(child, source, free_at, taken, emit);
    }
}

/// Every Python or JavaScript read `a.b.NAME` outside a call's callee, the outer link of its
/// chain, with its last name, its qualifier, the node of that name and the byte its head
/// starts at.
fn module_reads<'a>(
    node: Node<'a>,
    source: &str,
    read: &mut impl FnMut(String, Vec<String>, Node<'a>, usize),
) {
    let (object, last) = match node.kind() {
        "attribute" => ("object", "attribute"),
        "member_expression" => ("object", "property"),
        _ => ("", ""),
    };
    if !object.is_empty() {
        let holds = |p: Node<'_>, field: &str| {
            p.child_by_field_name(field)
                .is_some_and(|f| f.id() == node.id())
        };
        let inner = node.parent().is_some_and(|p| {
            (matches!(p.kind(), "call" | "call_expression") && holds(p, "function"))
                || (p.kind() == node.kind() && holds(p, object))
        });
        if let Some((at, (name, scope))) = node
            .child_by_field_name(last)
            .filter(|_| !inner)
            .zip(scoped_name(node, source))
        {
            read(name, scope, at, node.start_byte());
        }
    }
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        module_reads(child, source, read);
    }
}

/// The import and `use` lines of a file, at any depth: a Rust `use`, a Python `import` or
/// `from` import, a JavaScript or TypeScript `import`, and a `const`, `let` or `var` whose
/// value is a `require(..)` call.
fn import_lines(lang: &LangSpec, root: Node<'_>, source: &str) -> Vec<ImportLine> {
    // § kv22y3ap6.h@6bbxr
    let kinds: &[&str] = match family(lang) {
        "rust" => &["use_declaration"],
        "python" => &[
            "import_statement",
            "import_from_statement",
            "future_import_statement",
        ],
        "javascript" => &["import_statement"],
        _ => &[],
    };
    let mut out = Vec::new();
    let mut stack = vec![root];
    while let Some(node) = stack.pop() {
        let required = family(lang) == "javascript" && !requires(node, source).is_empty();
        if !kinds.contains(&node.kind()) && !required {
            let mut cursor = node.walk();
            stack.extend(node.named_children(&mut cursor));
            continue;
        }
        let mut names = BTreeSet::new();
        let mut leaves = vec![node];
        while let Some(n) = leaves.pop() {
            if n.child_count() == 0 {
                names.insert(n.utf8_text(source.as_bytes()).unwrap_or("").to_string());
            }
            let mut cursor = n.walk();
            leaves.extend(n.children(&mut cursor));
        }
        let mut binds = Vec::new();
        match family(lang) {
            "rust" => {
                if let Some(arg) = node.child_by_field_name("argument") {
                    rust_use_binds(arg, source, None, &mut binds);
                }
            }
            "python" => python_import_binds(node, source, &mut binds),
            "javascript" => js_import_binds(node, source, &mut binds),
            _ => {}
        }
        out.push(ImportLine {
            units: import_units(lang, node, source),
            bytes: (node.start_byte(), node.end_byte()),
            names,
            binds,
        });
    }
    out
}

/// The import of each name an import line holds, as its tokens: `use a::{b, c};` is
/// `use a::b;` and `use a::c;`, `import { b, c } from "a"` is `import { b } from "a"` and
/// `import { c } from "a"`, and `from a import (b, c)` is `from a import b` and
/// `from a import c`. The order of the names, the group around them, its trailing comma, the
/// quotes of a JavaScript specifier and its `;` are then formatting. A `require` line is one
/// import.
fn import_units(lang: &LangSpec, node: Node<'_>, source: &str) -> Vec<ImportUnit> {
    // § kv22y3ap6.h@yk78v
    let leaves = |n: Node<'_>| {
        let mut out = Vec::new();
        import_tokens(n, source, &mut out);
        out
    };
    let unit = |tokens: Vec<String>| ImportUnit {
        text: tokens.join(" "),
        names: tokens.iter().cloned().collect(),
    };
    let mut units = Vec::new();
    match (family(lang), node.kind()) {
        ("rust", "use_declaration") => {
            let mut head = Vec::new();
            let mut cursor = node.walk();
            for child in node.named_children(&mut cursor) {
                if child.kind() == "visibility_modifier" {
                    head.extend(leaves(child));
                }
            }
            head.push("use".to_string());
            if let Some(arg) = node.child_by_field_name("argument") {
                let mut paths = Vec::new();
                rust_use_paths(arg, source, Vec::new(), &mut paths);
                for path in paths {
                    units.push(unit([head.clone(), path].concat()));
                }
            }
        }
        ("python", _) => {
            let head = match node.child_by_field_name("module_name") {
                Some(module) => {
                    let mut head = vec!["from".to_string()];
                    head.extend(leaves(module));
                    head.push("import".to_string());
                    head
                }
                None if node.kind() == "future_import_statement" => {
                    vec!["from".into(), "__future__".into(), "import".into()]
                }
                None => vec!["import".to_string()],
            };
            let mut cursor = node.walk();
            let names: Vec<Node<'_>> = node.children_by_field_name("name", &mut cursor).collect();
            for name in names {
                units.push(unit([head.clone(), leaves(name)].concat()));
            }
            let mut cursor = node.walk();
            let wildcard = node
                .named_children(&mut cursor)
                .find(|c| c.kind() == "wildcard_import");
            if let Some(wildcard) = wildcard {
                units.push(unit([head, leaves(wildcard)].concat()));
            }
        }
        ("javascript", "import_statement") => {
            let mut cursor = node.walk();
            let children: Vec<Node<'_>> = node.children(&mut cursor).collect();
            let typed = children.iter().any(|c| c.kind() == "type");
            let mut head = vec!["import".to_string()];
            if typed {
                head.push("type".to_string());
            }
            let mut tail = vec!["from".to_string()];
            let mut clause = None;
            for child in &children {
                match child.kind() {
                    "import_clause" => clause = Some(*child),
                    "string" | "import_attribute" => tail.extend(leaves(*child)),
                    _ => {}
                }
            }
            let Some(clause) = clause else {
                head.extend(tail.into_iter().skip(1));
                return vec![unit(head)];
            };
            let mut cursor = clause.walk();
            for part in clause.named_children(&mut cursor) {
                if part.kind() == "named_imports" {
                    let mut cursor = part.walk();
                    for spec in part.named_children(&mut cursor) {
                        if spec.kind() == "import_specifier" {
                            let one = [vec!["{".to_string()], leaves(spec), vec!["}".into()]];
                            units.push(unit([head.clone(), one.concat(), tail.clone()].concat()));
                        }
                    }
                } else if part.kind() != "comment" {
                    units.push(unit([head.clone(), leaves(part), tail.clone()].concat()));
                }
            }
        }
        _ => units.push(unit(leaves(node))),
    }
    units
}

/// The leaves of an import `node` as tokens, comments, `;` and `,` left out: a JavaScript
/// string is its text between quotes, written between `"`.
fn import_tokens(node: Node<'_>, source: &str, out: &mut Vec<String>) {
    let text = node.utf8_text(source.as_bytes()).unwrap_or("");
    if node.kind() == "string" && !text.contains('\\') && text.len() >= 2 {
        let quote = &text[..1];
        if (quote == "\"" || quote == "'") && text.ends_with(quote) {
            out.push(format!("\"{}\"", &text[1..text.len() - 1]));
            return;
        }
    }
    if node.child_count() == 0 {
        if !matches!(
            node.kind(),
            ";" | "," | "comment" | "line_comment" | "block_comment"
        ) {
            out.push(text.to_string());
        }
        return;
    }
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        import_tokens(child, source, out);
    }
}

/// Each path a Rust use tree imports, as its tokens after `use`, with `prefix` before it.
fn rust_use_paths(node: Node<'_>, source: &str, prefix: Vec<String>, out: &mut Vec<Vec<String>>) {
    let leaves = |n: Node<'_>| {
        let mut tokens = Vec::new();
        import_tokens(n, source, &mut tokens);
        tokens
    };
    match node.kind() {
        "scoped_use_list" => {
            let mut prefix = prefix;
            if let Some(path) = node.child_by_field_name("path") {
                prefix.extend(leaves(path));
            }
            prefix.push("::".to_string());
            if let Some(list) = node.child_by_field_name("list") {
                rust_use_paths(list, source, prefix, out);
            }
        }
        "use_list" => {
            let mut cursor = node.walk();
            for child in node.named_children(&mut cursor) {
                if !matches!(child.kind(), "line_comment" | "block_comment") {
                    rust_use_paths(child, source, prefix.clone(), out);
                }
            }
        }
        _ => out.push([prefix, leaves(node)].concat()),
    }
}

/// The text of each import of each import line of `source`, as it enters a pin.
#[cfg(test)]
pub(crate) fn import_texts(lang: &LangSpec, source: &str) -> Vec<String> {
    let tree = span_lang::parse_source(lang, source).expect("parse");
    import_lines(lang, tree.root_node(), source)
        .into_iter()
        .flat_map(|line| line.units)
        .map(|unit| unit.text)
        .collect()
}

/// Whether `names` spells a name `call` writes, the call's own or one of its scope.
fn spells(names: &BTreeSet<String>, call: &CallRec) -> bool {
    names.contains(&call.name) || call.scope.iter().any(|s| names.contains(s))
}

/// A name an import line binds from `origin`.
fn bind(name: String, origin: Origin) -> Bind {
    Bind { name, origin }
}

/// The names a Rust use tree binds, with the first segment of the path each comes from.
/// `prefix` is the root and the last segment of the path a `{ .. }` group stands under.
fn rust_use_binds(node: Node<'_>, source: &str, prefix: Option<(&str, &str)>, out: &mut Vec<Bind>) {
    let text = |n: Node<'_>| n.utf8_text(source.as_bytes()).unwrap_or("").to_string();
    let root_of = |path: Node<'_>| -> String {
        let mut first = path;
        while first.kind() == "scoped_identifier" {
            match first.child_by_field_name("path") {
                Some(p) => first = p,
                None => break,
            }
        }
        if first.kind() == "scoped_identifier" {
            first = first.child_by_field_name("name").unwrap_or(first);
        }
        prefix.map_or_else(|| text(first), |(root, _)| root.to_string())
    };
    let last_of = |path: Node<'_>| -> String {
        path.child_by_field_name("name")
            .map_or_else(|| text(path), text)
    };
    let origin = |path: Node<'_>| Origin::Root(root_of(path));
    match node.kind() {
        "identifier" | "crate" | "super" | "self" => {
            let name = text(node);
            match prefix {
                // `m::{self}` binds the module `m`, which no file stem names as a body's.
                Some((root, last)) if name == "self" => {
                    out.push(bind(last.to_string(), Origin::Root(root.to_string())));
                }
                Some((root, _)) => out.push(bind(name, Origin::Root(root.to_string()))),
                None => out.push(bind(name.clone(), Origin::Root(name))),
            }
        }
        "scoped_identifier" => {
            out.push(bind(last_of(node), origin(node)));
        }
        "use_as_clause" => {
            if let (Some(path), Some(alias)) = (
                node.child_by_field_name("path"),
                node.child_by_field_name("alias"),
            ) {
                out.push(bind(text(alias), origin(path)));
            }
        }
        "scoped_use_list" => {
            let path = node.child_by_field_name("path");
            let root = path.map(root_of);
            let last = path.map(last_of);
            let inner = match (&root, &last) {
                (Some(root), Some(last)) => Some((root.as_str(), last.as_str())),
                _ => prefix,
            };
            if let Some(list) = node.child_by_field_name("list") {
                rust_use_binds(list, source, inner, out);
            }
        }
        "use_list" => {
            let mut cursor = node.walk();
            for item in node.named_children(&mut cursor) {
                rust_use_binds(item, source, prefix, out);
            }
        }
        _ => {}
    }
}

/// The names a Python `import` or `from` import binds, with the module each comes from.
fn python_import_binds(node: Node<'_>, source: &str, out: &mut Vec<Bind>) {
    let text = |n: Node<'_>| n.utf8_text(source.as_bytes()).unwrap_or("").to_string();
    let segments = |n: Node<'_>| -> Vec<String> {
        text(n)
            .trim_start_matches('.')
            .split('.')
            .filter(|s| !s.is_empty())
            .map(str::to_string)
            .collect()
    };
    let (module, relative) = match node.child_by_field_name("module_name") {
        Some(m) => (Some(segments(m)), m.kind() == "relative_import"),
        None => (None, false),
    };
    let mut cursor = node.walk();
    for name in node.children_by_field_name("name", &mut cursor) {
        // `import a.b as c` binds the module `b`, `import a.b` the module `a`.
        let (bound, path) = match name.kind() {
            "aliased_import" => {
                let Some(alias) = name.child_by_field_name("alias") else {
                    continue;
                };
                let path = name
                    .child_by_field_name("name")
                    .map(segments)
                    .unwrap_or_default();
                (text(alias), path)
            }
            _ => {
                let path = segments(name);
                (path.first().cloned().unwrap_or_default(), path)
            }
        };
        let origin = match &module {
            // `from ..a import b`: each dot past the first is a step up.
            Some(module) if relative => {
                let dots = node
                    .child_by_field_name("module_name")
                    .map_or(1, |m| text(m).chars().take_while(|&c| c == '.').count());
                let mut near = vec!["..".to_string(); dots.saturating_sub(1)];
                near.extend(module.iter().cloned());
                match name.kind() {
                    "aliased_import" => renamed(&Origin::Near(near)),
                    _ => Origin::Near(near),
                }
            }
            Some(module) => Origin::Module(module.clone(), relative),
            None if name.kind() == "aliased_import" => Origin::Module(path, false),
            None => Origin::Module(path.into_iter().take(1).collect(), false),
        };
        out.push(bind(bound, origin));
    }
}

/// A plain prefix mapping of a `tsconfig.json` or `deno.json`: the specifier segments it
/// replaces, the project path segments it writes, and the directory whose files it serves.
struct Alias {
    from: Vec<String>,
    to: Vec<String>,
    dir: PathBuf,
}

/// The plain prefix mappings of each `tsconfig.json` `compilerOptions.paths` and `deno.json`
/// `imports` among `files`: a `<prefix>/*` key with one `<path>/*` target, or a `<prefix>/` key
/// with a relative `<path>/` value. A file that is not plain JSON maps nothing.
fn aliases(files: &[CodeFile]) -> Vec<Alias> {
    // § pyw49tg9j.i@zesac
    let segments = |text: &str| -> Vec<String> {
        text.split('/')
            .filter(|s| !s.is_empty())
            .map(str::to_string)
            .collect()
    };
    let mut out = Vec::new();
    for file in files {
        let name = file.rel.file_name().and_then(|n| n.to_str());
        let (Some(name @ ("tsconfig.json" | "deno.json")), Ok(json)) =
            (name, serde_json::from_str::<serde_json::Value>(&file.text))
        else {
            continue;
        };
        let dir = file.rel.parent().unwrap_or(Path::new("")).to_path_buf();
        let mut map = |prefix: &str, target: &str, base: &Path| {
            if prefix.contains('*') || target.contains('*') || target.starts_with('/') {
                return;
            }
            let mut to: Vec<String> = Vec::new();
            for part in path_segments(&base.join(target)) {
                match part {
                    "." => {}
                    ".." => {
                        to.pop();
                    }
                    part => to.push(part.to_string()),
                }
            }
            out.push(Alias {
                from: segments(prefix),
                to,
                dir: dir.clone(),
            });
        };
        if name == "deno.json" {
            for (key, value) in json["imports"].as_object().into_iter().flatten() {
                // A value that is not a relative path names a package, outside the project.
                let target = value.as_str().filter(|t| t.starts_with('.'));
                if let (Some(prefix), Some(target)) = (
                    key.strip_suffix('/'),
                    target.and_then(|t| t.strip_suffix('/')),
                ) {
                    map(prefix, target, &dir);
                }
            }
            continue;
        }
        let options = &json["compilerOptions"];
        let base = dir.join(options["baseUrl"].as_str().unwrap_or("."));
        for (key, value) in options["paths"].as_object().into_iter().flatten() {
            let targets = value.as_array().map(Vec::as_slice).unwrap_or_default();
            if let (Some(prefix), [target]) = (key.strip_suffix("/*"), targets) {
                if let Some(target) = target.as_str().and_then(|t| t.strip_suffix("/*")) {
                    map(prefix, target, &base);
                }
            }
        }
    }
    out
}

/// Each JavaScript or TypeScript import from a specifier an alias of `files` maps, rewritten to
/// the project path it maps to, so the name it binds is a name of the project.
fn resolve_aliases(files: &[CodeFile], imports: &mut HashMap<PathBuf, Vec<ImportLine>>) {
    // § pyw49tg9j.i@z6mbn
    let aliases = aliases(files);
    if aliases.is_empty() {
        return;
    }
    for (path, lines) in imports.iter_mut() {
        let js = span_lang::lang_for_path(path).is_some_and(|lang| family(lang) == "javascript");
        if !js {
            continue;
        }
        // The nearest config to the importing file maps it.
        let serving = aliases
            .iter()
            .filter(|a| path.starts_with(&a.dir))
            .max_by_key(|a| a.dir.components().count());
        let Some(depth) = serving.map(|a| a.dir.components().count()) else {
            continue;
        };
        for bind in lines.iter_mut().flat_map(|l| l.binds.iter_mut()) {
            let Origin::Module(module, false) = &bind.origin else {
                continue;
            };
            let found = aliases
                .iter()
                .filter(|a| path.starts_with(&a.dir) && a.dir.components().count() == depth)
                .filter(|a| module.starts_with(&a.from))
                .max_by_key(|a| a.from.len());
            if let Some(alias) = found {
                let mut to = alias.to.clone();
                to.extend(module[alias.from.len()..].iter().cloned());
                bind.origin = Origin::Module(to, false);
            }
        }
    }
}

/// Where a JavaScript or TypeScript specifier says its names come from.
fn js_specifier(text: &str) -> Origin {
    let spec = text.trim_matches(|c| c == '"' || c == '\'' || c == '`');
    let segments = |skip: &[&str]| {
        spec.trim_start_matches("node:")
            .split('/')
            .filter(|s| !s.is_empty() && !skip.contains(s))
            .map(str::to_string)
            .collect()
    };
    if spec == "." || spec == ".." || spec.starts_with("./") || spec.starts_with("../") {
        return Origin::Near(segments(&["."]));
    }
    let relative = spec.starts_with('.') || spec.starts_with('/');
    Origin::Module(segments(&[".", ".."]), relative)
}

/// `origin` for a name bound under another name than the one its module declares: a relative
/// module stays relative and narrows nothing.
fn renamed(origin: &Origin) -> Origin {
    match origin {
        Origin::Near(near) => {
            Origin::Module(near.iter().filter(|s| *s != "..").cloned().collect(), true)
        }
        other => other.clone(),
    }
}

/// The names a JavaScript or TypeScript `import` binds, with the specifier each comes from.
fn js_import_binds(node: Node<'_>, source: &str, out: &mut Vec<Bind>) {
    let text = |n: Node<'_>| n.utf8_text(source.as_bytes()).unwrap_or("").to_string();
    for (target, spec) in requires(node, source) {
        let spec = renamed(&js_specifier(&text(spec)));
        let mut names = Vec::new();
        binding_names(target, source, &mut names);
        out.extend(names.into_iter().map(|name| bind(name, spec.clone())));
    }
    let Some(spec) = node.child_by_field_name("source") else {
        return;
    };
    let spec = js_specifier(&text(spec));
    let mut stack = vec![node];
    while let Some(n) = stack.pop() {
        let bound = match n.kind() {
            "import_clause" => n
                .named_child(0)
                .filter(|c| c.kind() == "identifier")
                .map(|c| (text(c), renamed(&spec))),
            "namespace_import" => n.named_child(0).map(|c| (text(c), renamed(&spec))),
            "import_specifier" => match n.child_by_field_name("alias") {
                Some(alias) => Some((text(alias), renamed(&spec))),
                None => n
                    .child_by_field_name("name")
                    .map(|c| (text(c), spec.clone())),
            },
            _ => None,
        };
        if let Some((name, origin)) = bound {
            out.push(bind(name, origin));
        }
        let mut cursor = n.walk();
        stack.extend(n.named_children(&mut cursor));
    }
}

/// The declarators of a `const`, `let` or `var` whose value is a `require(..)` call of a
/// string, by the target each binds and the string it requires.
fn requires<'a>(node: Node<'a>, source: &str) -> Vec<(Node<'a>, Node<'a>)> {
    if !matches!(node.kind(), "lexical_declaration" | "variable_declaration") {
        return Vec::new();
    }
    let mut cursor = node.walk();
    let declarators: Vec<Node<'a>> = node.named_children(&mut cursor).collect();
    declarators
        .into_iter()
        .filter(|d| d.kind() == "variable_declarator")
        .filter_map(|d| {
            let value = d.child_by_field_name("value")?;
            let called = value.kind() == "call_expression"
                && value
                    .child_by_field_name("function")
                    .and_then(|f| f.utf8_text(source.as_bytes()).ok())
                    == Some("require");
            let spec = value
                .child_by_field_name("arguments")?
                .named_child(0)
                .filter(|a| matches!(a.kind(), "string" | "template_string"))?;
            called.then_some((d.child_by_field_name("name")?, spec))
        })
        .collect()
}

/// The stretches a call of the class `node` reads: its header with its decorators up to its
/// body, then each statement of its body that declares no method, and its constructors,
/// `__init__`, `__new__` and `__post_init__` in Python and `constructor` in JavaScript and
/// TypeScript.
fn class_reads(node: Node<'_>, source: &str) -> Vec<(usize, usize)> {
    // § kv22y3ap6.d@4hgej
    let body = node.child_by_field_name("body");
    let start = with_attributes(node);
    let mut out = vec![(start, body.map_or(node.end_byte(), |b| b.start_byte()))];
    let Some(body) = body else {
        return out;
    };
    let mut cursor = body.walk();
    for member in body.named_children(&mut cursor) {
        let definition = match member.kind() {
            "decorated_definition" => member.child_by_field_name("definition"),
            _ => Some(member),
        };
        let method = definition.filter(|d| {
            matches!(
                d.kind(),
                "function_definition" | "method_definition" | "class_definition"
            )
        });
        let constructor = method.and_then(|m| name_field(m, source)).is_some_and(|n| {
            matches!(
                n.as_str(),
                "__init__" | "__new__" | "__post_init__" | "constructor"
            )
        });
        if (method.is_none() && !member.kind().contains("comment")) || constructor {
            out.push((member.start_byte(), member.end_byte()));
        }
    }
    out
}

/// Whether a JavaScript or TypeScript class member is `static`.
fn is_static(node: Node<'_>) -> bool {
    let mut cursor = node.walk();
    let found = node.children(&mut cursor).any(|c| c.kind() == "static");
    found
}

/// The component a JSX element names, as a call names its callee: a tag that is a capitalised
/// name or a member path, never an intrinsic element such as `div`. Its name, its qualifier,
/// the byte its tag starts at, the byte its last name starts at, and no method.
fn jsx_component(
    lang: &LangSpec,
    node: Node<'_>,
    source: &str,
) -> Option<(String, Vec<String>, usize, usize, bool)> {
    // § kv22y3ap6.d@p0e91
    if family(lang) != "javascript"
        || !matches!(
            node.kind(),
            "jsx_opening_element" | "jsx_self_closing_element"
        )
    {
        return None;
    }
    let tag = node.child_by_field_name("name")?;
    match tag.kind() {
        "identifier" => {
            let name = tag.utf8_text(source.as_bytes()).ok()?;
            name.starts_with(|c: char| c.is_ascii_uppercase()).then(|| {
                (
                    name.to_string(),
                    Vec::new(),
                    tag.start_byte(),
                    tag.start_byte(),
                    false,
                )
            })
        }
        "member_expression" => {
            let (name, scope) = scoped_name(tag, source)?;
            let at = tag.child_by_field_name("property")?.start_byte();
            Some((name, scope, tag.start_byte(), at, false))
        }
        _ => None,
    }
}

fn is_fn_kind(kind: &str) -> bool {
    matches!(
        kind,
        "function_item"
            | "function_definition"
            | "function_declaration"
            | "generator_function_declaration"
    )
}

/// A function written as an expression or a method, whose body is a scope of its own.
fn is_closure_kind(kind: &str) -> bool {
    matches!(
        kind,
        "arrow_function"
            | "function_expression"
            | "function"
            | "generator_function"
            | "method_definition"
            | "closure_expression"
            | "lambda"
    )
}

fn name_field(node: Node<'_>, source: &str) -> Option<String> {
    let text = named_field(node, "name")?
        .utf8_text(source.as_bytes())
        .ok()?
        .trim();
    (!text.is_empty()).then(|| text.to_string())
}

fn named_field<'a>(node: Node<'a>, field: &str) -> Option<Node<'a>> {
    let mut cursor = node.walk();
    if !cursor.goto_first_child() {
        return None;
    }
    loop {
        if cursor.field_name() == Some(field) {
            return Some(cursor.node());
        }
        if !cursor.goto_next_sibling() {
            return None;
        }
    }
}

/// The name a call names, the qualifier before it, `a::b` of `a::b::f()` or `m` of `m.f()`,
/// the byte where its callee starts, the byte where that name starts, and whether it is a
/// method call. A Rust method call is one only on `self`.
fn callee_ident(node: Node<'_>, source: &str) -> Option<(String, Vec<String>, usize, usize, bool)> {
    let text = |n: Node<'_>| Some(n.utf8_text(source.as_bytes()).ok()?.trim().to_string());
    let callee = if node.kind() == "command" {
        // § pyw49tg9j.a@c4h2d
        named_field(node, "name")?
            .named_child(0)
            .filter(|n| n.kind() == "word")?
    } else {
        named_field(node, "function")
            .or_else(|| named_field(node, "method"))
            .or_else(|| node.named_child(0))?
    };
    let (name, scope) = match callee.kind() {
        "word" | "identifier" | "simple_identifier" => (text(callee)?, Vec::new()),
        "field_expression" => {
            let value = callee.child_by_field_name("value")?;
            if value.kind() != "self" {
                return None;
            }
            (
                text(callee.child_by_field_name("field")?)?,
                vec!["self".to_string()],
            )
        }
        _ => scoped_name(callee, source)?,
    };
    let method = matches!(
        callee.kind(),
        "field_expression" | "attribute" | "member_expression"
    );
    let name_at = ["name", "attribute", "property", "field"]
        .iter()
        .find_map(|f| callee.child_by_field_name(f))
        .map_or(callee.start_byte(), |n| n.start_byte());
    (!name.is_empty()).then_some((name, scope, callee.start_byte(), name_at, method))
}

/// The last name of a path `a::b::f`, `m.f` or `m.n.f` and the qualifier before it, when every
/// link of the qualifier is a name, not a value such as a call or an index.
fn scoped_name(node: Node<'_>, source: &str) -> Option<(String, Vec<String>)> {
    let text = |n: Node<'_>| Some(n.utf8_text(source.as_bytes()).ok()?.trim().to_string());
    let (mut scope, mut head) = (Vec::new(), node);
    let name = loop {
        let (qualifier, last) = match head.kind() {
            "scoped_identifier" | "scoped_type_identifier" => ("path", "name"),
            "attribute" => ("object", "attribute"),
            "member_expression" => ("object", "property"),
            _ => return None,
        };
        scope.push(text(head.child_by_field_name(last)?)?);
        let next = head.child_by_field_name(qualifier)?;
        if next.named_child_count() == 0 {
            scope.push(text(next)?);
            break scope.remove(0);
        }
        head = next;
    };
    scope.reverse();
    Some((name, scope))
}

/// The language a call resolves in: JavaScript and TypeScript are one.
fn family(lang: &LangSpec) -> &'static str {
    match lang.id {
        "javascript" | "typescript" | "tsx" => "javascript",
        id => id,
    }
}

/// A language family, `family` of a grammar. Named, it is not a borrow serde would tie to the
/// bytes it reads.
type Family = &'static str;

/// A language family kept in the cache by its name. A name no grammar writes reads as no
/// entry, which the run derives again.
mod family_name {
    use serde::{Deserialize, Deserializer, Serializer};

    pub fn serialize<S: Serializer>(family: &&'static str, out: S) -> Result<S::Ok, S::Error> {
        out.serialize_str(family)
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(input: D) -> Result<&'static str, D::Error> {
        let name = String::deserialize(input)?;
        crate::span_lang::PINNED
            .iter()
            .map(|lang| lang.id)
            .find(|id| *id == name)
            .ok_or_else(|| serde::de::Error::custom(format!("no language family `{name}`")))
    }
}

fn in_file<'a>(index: &'a HashMap<PathBuf, Vec<usize>>, path: &Path) -> &'a [usize] {
    index.get(path).map(Vec::as_slice).unwrap_or_default()
}

/// The innermost function of `path` that holds `start..end`.
fn innermost_fn(
    functions: &[FnRec],
    fns_in: &HashMap<PathBuf, Vec<usize>>,
    path: &Path,
    start: usize,
    end: usize,
) -> Option<usize> {
    in_file(fns_in, path)
        .iter()
        .copied()
        .filter(|&i| {
            let rec = &functions[i];
            rec.kind == Kind::Function && rec.start <= start && rec.end >= end
        })
        .min_by_key(|&i| functions[i].end - functions[i].start)
}

fn path_key(path: &Path) -> String {
    path.to_string_lossy().replace('\\', "/")
}

/// The hash of a supernode whose `members` are hashed and whose `next` supernodes, the ones it
/// follows out of it, are hashed in `supernode`.
fn supernode_hash(
    members: &[usize],
    next: &BTreeSet<usize>,
    functions: &[FnRec],
    supernode: &[String],
) -> String {
    // § d1bc2zca5.a@9cj7b
    let mut parts: Vec<String> = members
        .iter()
        .map(|&i| functions[i].shape.clone())
        .collect();
    parts.sort();
    let mut outgoing: Vec<String> = next.iter().map(|&n| supernode[n].clone()).collect();
    outgoing.sort();
    parts.extend(outgoing);
    encode_digest(&parts.join("\n"))
}

struct Tarjan {
    index: i32,
    stack: Vec<usize>,
    indices: Vec<i32>,
    lowlink: Vec<i32>,
    on_stack: Vec<bool>,
    scc_of: Vec<usize>,
    scc_count: usize,
}

fn tarjan(n: usize, adj: &[Vec<usize>]) -> Vec<usize> {
    // § d1bc2zca5.a@67g91
    let mut state = Tarjan {
        index: 0,
        stack: Vec::new(),
        indices: vec![-1; n],
        lowlink: vec![-1; n],
        on_stack: vec![false; n],
        scc_of: vec![0; n],
        scc_count: 0,
    };
    for v in 0..n {
        if state.indices[v] < 0 {
            strongconnect(v, adj, &mut state);
        }
    }
    state.scc_of
}

fn strongconnect(v: usize, adj: &[Vec<usize>], state: &mut Tarjan) {
    state.indices[v] = state.index;
    state.lowlink[v] = state.index;
    state.index += 1;
    state.stack.push(v);
    state.on_stack[v] = true;
    for &w in &adj[v] {
        if state.indices[w] < 0 {
            strongconnect(w, adj, state);
            state.lowlink[v] = state.lowlink[v].min(state.lowlink[w]);
        } else if state.on_stack[w] {
            state.lowlink[v] = state.lowlink[v].min(state.indices[w]);
        }
    }
    if state.lowlink[v] == state.indices[v] {
        loop {
            let w = state.stack.pop().expect("scc stack");
            state.on_stack[w] = false;
            state.scc_of[w] = state.scc_count;
            if w == v {
                break;
            }
        }
        state.scc_count += 1;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    impl FollowIndex {
        /// What each query a pin makes answers for every span, as text.
        fn answers(&self) -> Vec<String> {
            let mut out = vec![
                format!("{:?}", self.read_names()),
                format!("{:?}", self.followed_paths()),
                format!("{:?}", self.mark_errors),
            ];
            for z in &self.spans {
                let punch: Vec<(usize, usize)> = in_file(&self.spans_in, &z.path)
                    .iter()
                    .map(|&j| &self.spans[j])
                    .filter(|inner| inner.pinned)
                    .map(|inner| (inner.start, inner.end))
                    .filter(|&inner| crate::span::nests_in(inner, (z.start, z.end)))
                    .collect();
                for punch in [&[][..], &punch] {
                    let (path, s, e, prefix) = (z.path.as_path(), z.start, z.end, &z.prefix);
                    let mut tokens: Vec<_> = self
                        .name_tokens(path, s, e, punch, prefix)
                        .into_iter()
                        .collect();
                    tokens.sort();
                    out.push(format!(
                        "{} {} {:?} {:?} {:?} {:?} {:?} {:?} {}",
                        z.addr,
                        self.pin_blob(path, s, e, punch, prefix),
                        tokens,
                        self.pin_import_bytes(path, s, e, punch, prefix),
                        self.followed_callees(path, s, e, punch, prefix),
                        self.broken_callee(path, s, e, punch, prefix),
                        self.outside_cone(path, s, e, punch),
                        self.caller_laws(path, z.line),
                        self.follows_any(path, s, e, punch),
                    ));
                }
            }
            out
        }
    }

    /// A pin reads the same closure whether the index reads the calls of every file or only of
    /// those a pin reaches, over Silcrow's own code and a tree in every family of languages.
    #[test]
    fn reading_only_the_calls_pins_reach_answers_every_span_alike() {
        let root = Path::new(env!("CARGO_MANIFEST_DIR"));
        let mut own: Vec<(PathBuf, String)> = FollowIndex::sources(root)
            .unwrap()
            .into_iter()
            .filter(|(rel, _)| rel.starts_with("src"))
            .collect();
        own.sort();
        let mixed = sources(&[
            ("src/app.ts", "import { fee } from \"./fees\";\n\nexport function charge(x: number): number {\n  // § abcdefgh1\n  return fee(x) + RATE;\n}\n\nconst RATE = 2;\n"),
            ("src/fees.ts", "import { base } from \"./base\";\n\nexport function fee(x: number): number {\n  return base(x) * 2;\n}\n\nexport function unused(x: number): number {\n  return other(x);\n}\n"),
            ("src/base.ts", "export function base(x: number): number {\n  return x + 1;\n}\n"),
            ("src/other.ts", "export function other(x: number): number {\n  return x - 1;\n}\n"),
            ("src/refund.py", "from src.helpers import cap\n\n\ndef refund(charge):\n    # § abcdefgh2\n    return cap(charge)\n"),
            ("src/helpers.py", "def cap(charge):\n    return limit(charge)\n\n\ndef limit(charge):\n    return charge\n"),
        ]);
        for files in [own, mixed] {
            let parsed: Vec<CodeFile> = files
                .into_iter()
                .map(|(rel, text)| CodeFile::new(rel, text))
                .collect();
            let tests = crate::policy::TestPaths::conventions();
            let every = FollowIndex::build(&parsed, &tests, true).answers();
            let lazy = FollowIndex::build(&parsed, &tests, false).answers();
            assert_eq!(every.len(), lazy.len());
            for (a, b) in every.iter().zip(&lazy) {
                assert_eq!(a, b);
            }
        }
    }

    fn sources(files: &[(&str, &str)]) -> Vec<(PathBuf, String)> {
        files
            .iter()
            .map(|(path, text)| (PathBuf::from(path), text.to_string()))
            .collect()
    }

    /// The span of the first file from `from` to its end.
    fn span_of(text: &str, from: &str) -> (usize, usize) {
        (text.find(from).expect("the span"), text.len())
    }

    fn blob_from(files: &[(&str, &str)], from: &str) -> String {
        let sources = sources(files);
        let (start, end) = span_of(&sources[0].1, from);
        let prefix = CodeFile::new(sources[0].0.clone(), sources[0].1.clone()).prefix(start, end);
        FollowIndex::from_sources(&sources, &crate::policy::TestPaths::conventions()).pin_blob(
            &sources[0].0,
            start,
            end,
            &[],
            &prefix,
        )
    }

    /// What a pin of the span of the first file from `from` hashes: its shape with the names
    /// the index writes, then the follow blob.
    fn stream_from(files: &[(&str, &str)], from: &str) -> String {
        stream_at(files, &|text| span_of(text, from))
    }

    /// What a pin of the span `span` finds in the first file hashes.
    fn stream_at(files: &[(&str, &str)], span: &dyn Fn(&str) -> (usize, usize)) -> String {
        let sources = sources(files);
        let index = FollowIndex::from_sources(&sources, &crate::policy::TestPaths::conventions());
        let file = CodeFile::new(sources[0].0.clone(), sources[0].1.clone());
        let (lang, tree) = (file.lang.expect("a code file"), file.tree().unwrap());
        let (start, end) = span(&file.text);
        let prefix = file.prefix(start, end);
        let names = index.name_tokens(&file.rel, start, end, &[], &prefix);
        let shape = span_lang::shape_in_span(lang, &file.text, tree, start, end, &[], &|at| {
            names.get(&at).cloned()
        });
        format!(
            "{shape}{}",
            index.pin_blob(&file.rel, start, end, &[], &prefix)
        )
    }

    fn edited(files: &[(&str, &str)], edit: (&str, &str)) -> Vec<(String, String)> {
        let out: Vec<(String, String)> = files
            .iter()
            .map(|(p, s)| (p.to_string(), s.replace(edit.0, edit.1)))
            .collect();
        assert!(
            files.iter().zip(&out).any(|((_, s), (_, e))| s != e),
            "the edit {edit:?} applies"
        );
        out
    }

    /// Whether the edit, applied to every file, moves the pin of the span from `from`.
    fn moves(files: &[(&str, &str)], from: &str, edit: (&str, &str)) -> bool {
        let after = edited(files, edit);
        let after: Vec<(&str, &str)> = after
            .iter()
            .map(|(p, s)| (p.as_str(), s.as_str()))
            .collect();
        stream_from(files, from) != stream_from(&after, from)
    }

    /// Whether the edit, applied to every file, moves the pin of the span that covers exactly
    /// the text `span` of the first file.
    fn moves_span(files: &[(&str, &str)], span: &str, edit: (&str, &str)) -> bool {
        let after = edited(files, edit);
        let after: Vec<(&str, &str)> = after
            .iter()
            .map(|(p, s)| (p.as_str(), s.as_str()))
            .collect();
        let at = |text: &str| {
            let start = text.find(span).expect("the span");
            (start, start + span.len())
        };
        stream_at(files, &at) != stream_at(&after, &at)
    }

    #[test]
    fn marks_parse_from_wrappers() {
        assert_eq!(
            parse_decl_mark("// silcrow:technical"),
            Some(DeclMark::Technical)
        );
        assert_eq!(
            parse_decl_mark("# silcrow:functional"),
            Some(DeclMark::Functional)
        );
        assert_eq!(parse_call_mark("-- silcrow:skip"), Some(CallMark::Skip));
        assert_eq!(
            parse_call_mark("/* silcrow:follow */"),
            Some(CallMark::Follow)
        );
    }

    #[test]
    fn resolution_order() {
        use FollowDecision::*;
        let (tech, func) = (Some(DeclMark::Technical), Some(DeclMark::Functional));
        let (skip, follow) = (Some(CallMark::Skip), Some(CallMark::Follow));
        for boundary in [false, true] {
            assert_eq!(decide_follow(false, None, None, boundary), Stop);
            assert_eq!(decide_follow(false, func, follow, boundary), Stop);
            assert_eq!(decide_follow(true, None, skip, boundary), Stop);
            assert_eq!(decide_follow(true, func, skip, boundary), Stop);
            assert_eq!(decide_follow(true, tech, None, boundary), Stop);
            assert_eq!(decide_follow(true, tech, follow, boundary), Stop);
            assert_eq!(decide_follow(true, None, follow, boundary), Follow);
            assert_eq!(decide_follow(true, func, None, boundary), Follow);
        }
        assert_eq!(decide_follow(true, None, None, true), Stop);
        assert_eq!(decide_follow(true, None, None, false), Follow);
    }

    const RS: &str = "src/lib.rs";

    #[test]
    fn a_helper_body_enters_its_caller_by_shape() {
        let src = "fn helper(x: i32) { save(x); }\nfn caller() { helper(1); }\n";
        let files = [(RS, src)];
        assert!(!blob_from(&files, "fn caller").is_empty());
        assert!(!moves(
            &files,
            "fn caller",
            ("(x: i32) { save(x)", "(y: i32) { save(y)")
        ));
        assert!(
            moves(&files, "fn caller", ("x: i32", "x: i64")),
            "a Rust type"
        );
        assert!(moves(&files, "fn caller", ("save(x)", "save(x + 1)")));
    }

    #[test]
    fn a_helper_in_the_cone_is_followed_and_test_code_reaches_only_tests() {
        let caller = ("src/billing/invoice.rs", "fn caller() { helper(1); }\n");
        let helper = ("src/billing/util.rs", "fn helper(x: i32) { save(x); }\n");
        let test = ("tests/billing.rs", "fn helper() { assert!(true); }\n");
        let files = [caller, helper, test];
        assert!(moves(&files, "fn caller", ("save(x)", "save(x + 1)")));
        assert!(!moves(
            &files,
            "fn caller",
            ("assert!(true)", "assert!(false)")
        ));
        let from_test = [("tests/other.rs", "fn caller() { helper(1); }\n"), test];
        assert!(moves(
            &from_test,
            "fn caller",
            ("assert!(true)", "assert!(false)")
        ));
    }

    /// A file a language's convention names test code is test code: a homonym it declares
    /// leaves the declaration of the code under test the one a caller follows.
    #[test]
    fn a_file_named_as_its_language_names_tests_is_test_code() {
        let caller = ("app/pay.py", "def caller():\n    helper(1)\n");
        let helper = ("app/util.py", "def helper(x):\n    save(x)\n");
        let edit = ("save(x)", "save(x + 1)");
        for test in ["app/test_util.py", "app/util_test.py"] {
            let homonym = (test, "def helper(x):\n    assert x\n");
            assert!(
                moves(&[caller, helper, homonym], "def caller", edit),
                "{test}"
            );
        }
        let homonym = ("app/other.py", "def helper(x):\n    assert x\n");
        assert!(!moves(&[caller, helper, homonym], "def caller", edit));
    }

    /// The cone: a call follows a declaration whose file sits in the directory of the caller's
    /// file or below it. A `functional` declaration or a `follow` call pulls in one outside.
    #[test]
    fn a_declaration_outside_the_cone_is_followed_only_when_marked() {
        let caller = ("src/billing/invoice.rs", "fn caller() { helper(1); }\n");
        let edit = ("save(x)", "save(x + 1)");
        let outside = ("src/util.rs", "fn helper(x: i32) { save(x); }\n");
        assert!(
            !moves(&[caller, outside], "fn caller", edit),
            "a parent directory"
        );
        let sibling = ("src/shop/util.rs", outside.1);
        assert!(
            !moves(&[caller, sibling], "fn caller", edit),
            "a sibling directory"
        );
        let below = ("src/billing/tax/util.rs", outside.1);
        assert!(
            moves(&[caller, below], "fn caller", edit),
            "a child directory"
        );
        let beside = ("src/billing/util.rs", outside.1);
        assert!(
            moves(&[caller, beside], "fn caller", edit),
            "the same directory"
        );
        let functional = (
            "src/util.rs",
            "// silcrow:functional\nfn helper(x: i32) { save(x); }\n",
        );
        assert!(
            moves(&[caller, functional], "fn caller", edit),
            "functional"
        );
        let follow = (
            "src/billing/invoice.rs",
            "fn caller() {\n    // silcrow:follow\n    helper(1);\n}\n",
        );
        assert!(moves(&[follow, outside], "fn caller", edit), "follow");
        // Its name stays as text: renaming the call moves the pin, the body does not.
        assert!(moves(
            &[caller, outside],
            "fn caller",
            ("helper(1)", "helper(2)")
        ));
    }

    /// A name the narrowings leave with more than one candidate denotes nothing, whatever the
    /// cone, and keeps its text; Rust `cfg` twins count as one.
    #[test]
    fn an_ambiguous_name_follows_nothing_and_keeps_its_text() {
        let caller = ("src/billing/invoice.rs", "fn caller() { helper(1); }\n");
        let a = ("src/billing/a.rs", "pub fn helper(x: i32) { save(x); }\n");
        let b = ("src/billing/b.rs", "pub fn helper(x: i32) { drop(x); }\n");
        let files = [caller, a, b];
        assert!(!moves(&files, "fn caller", ("save(x)", "save(x + 1)")));
        assert!(!moves(&files, "fn caller", ("drop(x)", "drop(x + 1)")));
        assert!(moves(&files, "fn caller", ("helper(1)", "helper(2)")));
        assert!(moves(&[caller, a], "fn caller", ("save(x)", "save(x + 1)")));
        let far = ("lib/b.rs", b.1);
        assert!(
            !moves(&[caller, a, far], "fn caller", ("save(x)", "save(x + 1)")),
            "a homonym outside the cone still makes the name ambiguous"
        );
        let py = [
            (
                "app/main.py",
                "from app.rates import fee\n\ndef caller(x):\n    return fee(x)\n",
            ),
            ("app/rates.py", "def fee(x):\n    return x * 2\n"),
            ("app/legacy.py", "def fee(x):\n    return x * 3\n"),
        ];
        assert!(!moves(&py, "def caller", ("x * 2", "x * 4")));
        assert!(!moves(&py, "def caller", ("x * 3", "x * 4")));
        assert!(moves(
            &py,
            "def caller",
            (".rates import", ".legacy import")
        ));
        let twins = [
            ("src/main.rs", "mod sys;\nfn caller() -> u32 { sys::g() }\n"),
            (
                "src/sys/mod.rs",
                "#[cfg(unix)]\nmod unix;\n#[cfg(windows)]\nmod windows;\n",
            ),
            ("src/sys/unix.rs", "pub fn g() -> u32 { 1 }\n"),
            ("src/sys/windows.rs", "pub fn g() -> u32 { 2 }\n"),
        ];
        assert!(moves(&twins, "fn caller", ("{ 1 }", "{ 3 }")), "cfg twins");
        assert!(moves(&twins, "fn caller", ("{ 2 }", "{ 3 }")), "cfg twins");
        let inline = [(
            "src/main.rs",
            "#[cfg(unix)]\nfn g() -> u32 { 1 }\n#[cfg(not(unix))]\nfn g() -> u32 { 2 }\nfn caller() -> u32 { g() }\n",
        )];
        assert!(
            moves(&inline, "fn caller", ("{ 2 }", "{ 3 }")),
            "inline twins"
        );
        let half = [
            twins[0],
            ("src/sys/mod.rs", "#[cfg(unix)]\nmod unix;\nmod windows;\n"),
            twins[2],
            twins[3],
        ];
        assert!(
            !moves(&half, "fn caller", ("{ 1 }", "{ 3 }")),
            "a homonym under no cfg is no twin"
        );
    }

    /// A bare name a relative import binds denotes the declaration of the file the import
    /// names, whatever homonym another file declares, inside the cone or outside it.
    #[test]
    fn a_relative_import_narrows_a_name_to_the_file_it_names() {
        let route = "import { Hono } from \"hono\";\nimport { f } from \"./f.ts\";\n\nexport const routes = new Hono().post(\"/x\", async (c) => {\n  // § abcdefgh1.b\n  if (!await f(1, c.req.param(\"id\"))) {\n    return c.json({ error: \"no\" }, 404);\n  }\n  return c.json({ ok: true });\n});\n";
        let ts = [
            ("api/trust/routes.ts", route),
            (
                "api/trust/f.ts",
                "export async function f(a: number, id: string) {\n  return a > 0;\n}\n",
            ),
            (
                "client/lib/f.ts",
                "export async function f(slug: string, id: string) {\n  return slug === id;\n}\n",
            ),
        ];
        assert!(moves(&ts, "// § abcdefgh1.b", ("a > 0", "a > 1")));
        assert!(!moves(
            &ts,
            "// § abcdefgh1.b",
            ("slug === id", "slug !== id")
        ));
        for spec in ["./f", "./f.js", "../trust/f.ts"] {
            let other = edited(&ts, ("./f.ts", spec));
            let other: Vec<(&str, &str)> = other
                .iter()
                .map(|(p, s)| (p.as_str(), s.as_str()))
                .collect();
            assert!(
                moves(&other, "// § abcdefgh1.b", ("a > 0", "a > 1")),
                "{spec}"
            );
        }
        let index = [
            ts[0],
            ("api/trust/f/index.ts", ts[1].1),
            ("api/trust/g.ts", ts[2].1),
        ];
        let index = edited(&index, ("./f.ts", "./f"));
        let index: Vec<(&str, &str)> = index
            .iter()
            .map(|(p, s)| (p.as_str(), s.as_str()))
            .collect();
        assert!(moves(&index, "// § abcdefgh1.b", ("a > 0", "a > 1")));
        let py = [
            (
                "app/main.py",
                "from .rates import fee\n\ndef caller(x):\n    return fee(x)\n",
            ),
            ("app/rates.py", "def fee(x):\n    return x * 2\n"),
            ("app/legacy.py", "def fee(x):\n    return x * 3\n"),
        ];
        assert!(moves(&py, "def caller", ("x * 2", "x * 4")));
        assert!(!moves(&py, "def caller", ("x * 3", "x * 4")));
        let package = [
            (
                "app/main.py",
                "from ..app.rates import fee\n\ndef caller(x):\n    return fee(x)\n",
            ),
            ("app/rates/__init__.py", py[1].1),
            ("app/legacy.py", py[2].1),
        ];
        assert!(moves(&package, "def caller", ("x * 2", "x * 4")));
        assert!(!moves(&package, "def caller", ("x * 3", "x * 4")));
    }

    /// A span in a callback of a module-level chain reads the call that receives the callback,
    /// from its name, and not the rest of the chain or the bodies the chain names.
    #[test]
    fn a_span_in_a_callback_of_a_chain_reads_its_receiving_call_alone() {
        let app = "import { Hono } from \"hono\";\nimport { auth } from \"./auth\";\nimport { other } from \"./other\";\n\nexport const app = new Hono()\n  .route(\"/auth\", auth)\n  .use(\"/api/*\", async (c, next) => {\n    const token = c.req.header(\"Authorization\");\n    // § one abcdefgh1\n    if (!mayReach(token)) {\n      return c.json({ error: \"no\" }, 403);\n    }\n    return await next();\n  }, 5)\n  .route(\"/other\", other);\n\nfunction mayReach(token) {\n  return token === \"ok\";\n}\n";
        let files = [
            ("src/main.ts", app),
            (
                "src/auth.ts",
                "export const auth = new Hono().get(\"/\", (c) => c.json({ a: 1 }));\n",
            ),
            (
                "src/other.ts",
                "export const other = new Hono().get(\"/\", (c) => c.json({ b: 2 }));\n",
            ),
        ];
        let span =
            "    if (!mayReach(token)) {\n      return c.json({ error: \"no\" }, 403);\n    }\n";
        assert!(
            !moves_span(&files, span, ("a: 1", "a: 3")),
            "the chain before"
        );
        assert!(
            !moves_span(&files, span, ("b: 2", "b: 3")),
            "the chain after"
        );
        assert!(!moves_span(&files, span, ("\"/auth\"", "\"/login\"")));
        assert!(moves_span(&files, span, ("\"ok\"", "\"yes\"")), "a callee");
        assert!(
            moves_span(&files, span, ("\"/api/*\"", "\"/*\"")),
            "the route"
        );
        assert!(moves_span(&files, span, (".use(", ".all(")), "the method");
        assert!(
            moves_span(&files, span, ("\"Authorization\"", "\"X\"")),
            "the prefix"
        );
        assert!(
            moves_span(&files, span, ("}, 5)", "}, 6)")),
            "the arguments after"
        );
    }

    /// A span in a closure an object entry of a module-level config holds reads that entry from
    /// its key, not the rest of the config after it nor the entries before it.
    #[test]
    fn a_span_in_a_closure_of_an_object_entry_reads_its_entry_alone() {
        let auth = "import { betterAuth } from \"better-auth\";\nimport { blocked } from \"./gate\";\n\nexport const auth = betterAuth({\n  session: { age: 1 },\n  hooks: {\n    before: async (user) => {\n      if (await blocked(user.email)) {\n        throw new Error(\"no\");\n      }\n    },\n  },\n  trustedOrigins: [\"a\"],\n});\n";
        let files = [
            ("src/auth.ts", auth),
            (
                "src/gate.ts",
                "export async function blocked(email) {\n  return email.endsWith(\"x\");\n}\n",
            ),
        ];
        let span =
            "      if (await blocked(user.email)) {\n        throw new Error(\"no\");\n      }\n";
        assert!(
            !moves_span(&files, span, ("[\"a\"]", "[\"b\"]")),
            "after the span"
        );
        assert!(
            !moves_span(&files, span, ("age: 1", "age: 2")),
            "an entry before"
        );
        assert!(
            moves_span(&files, span, ("before: async", "after: async")),
            "its key"
        );
        assert!(
            moves_span(&files, span, ("endsWith(\"x\")", "endsWith(\"y\")")),
            "a callee"
        );
    }

    /// A span in a later arm reads the patterns and guards of the arms before it, not their
    /// bodies, which never run before it; inside a loop, and after a `switch` case that falls
    /// through, those bodies are read.
    #[test]
    fn a_span_in_a_later_arm_reads_no_earlier_arm_body() {
        let rs = "pub fn f(x: u32) -> u32 {\n    match x {\n        1 => {\n            log(1);\n            10\n        }\n        2 if x > 1 => {\n            let y = x * 20;\n            y\n        }\n        _ => 0,\n    }\n}\n";
        let span = "            let y = x * 20;\n            y\n";
        let files = |text: &'static str| [("src/f.rs", text)];
        assert!(!moves_span(&files(rs), span, ("log(1)", "log(2)")));
        assert!(moves_span(&files(rs), span, ("1 => {", "3 => {")));
        assert!(moves_span(&files(rs), span, ("if x > 1", "if x > 2")));
        let looped = "pub fn f(x: u32) -> u32 {\n    for _ in 0..2 {\n        match x {\n            1 => {\n                log(1);\n            }\n            _ => {\n                let y = x * 20;\n                log(y);\n            }\n        }\n    }\n    0\n}\n";
        let in_loop = "                let y = x * 20;\n                log(y);\n";
        assert!(moves_span(&files(looped), in_loop, ("log(1)", "log(2)")));
        let js = "export function f(x) {\n  switch (x) {\n    case 1:\n      a(1);\n      break;\n    case 2:\n      b(2);\n    case 3:\n      return x * 20;\n  }\n}\n";
        let ts = |text: &'static str| [("src/f.ts", text)];
        let ret = "      return x * 20;\n";
        assert!(!moves_span(&ts(js), ret, ("a(1)", "a(9)")));
        assert!(moves_span(&ts(js), ret, ("b(2)", "b(9)")), "a fall-through");
        assert!(moves_span(&ts(js), ret, ("case 1:", "case 7:")));
        let blocks = "export function f(x) {\n  switch (x) {\n    case 1: {\n      a(1);\n      return 1;\n    }\n    case 2: {\n      return x * 20;\n    }\n  }\n}\n";
        let block_ret = "      return x * 20;\n";
        assert!(
            !moves_span(&ts(blocks), block_ret, ("a(1)", "a(9)")),
            "a block case"
        );
        let py = "def f(x):\n    match x:\n        case 1:\n            a(1)\n        case 2:\n            return x * 20\n";
        let pys = |text: &'static str| [("app/f.py", text)];
        let pret = "            return x * 20\n";
        assert!(!moves_span(&pys(py), pret, ("a(1)", "a(9)")));
        assert!(moves_span(&pys(py), pret, ("case 1:", "case 7:")));
    }

    #[test]
    fn a_call_resolves_only_in_its_own_language() {
        let files = [
            ("src/main.rs", "fn caller() { helper(1); }\n"),
            ("app/helper.py", "def helper(x):\n    return x\n"),
        ];
        assert!(blob_from(&files, "fn caller").is_empty());
        let bash = [
            ("bin/run.sh", "caller() {\n  helper 1\n}\n"),
            ("src/lib.rs", "fn helper(x: i32) { save(x); }\n"),
        ];
        assert!(blob_from(&bash, "caller()").is_empty());
    }

    #[test]
    fn renaming_a_followed_function_or_constant_with_its_calls_moves_no_pin() {
        let rs = [(
            RS,
            "const LIMIT: u32 = 5;\nfn helper(x: u32) -> bool { x <= LIMIT }\nfn caller() { helper(1); }\n",
        )];
        assert!(!moves(&rs, "fn caller", ("helper", "check")));
        assert!(!moves(&rs, "fn caller", ("LIMIT", "CAP")));
        let py = [(
            "app/a.py",
            "LIMIT = 5\nLIMIT += 1\n\ndef helper(x):\n    return x <= LIMIT\n\ndef caller(x):\n    return helper(x)\n",
        )];
        assert!(!moves(&py, "def caller", ("helper", "check")));
        assert!(!moves(&py, "def caller", ("LIMIT", "CAP")));
        let js = [(
            "src/a.ts",
            "export const LIMIT = 5;\nfunction helper(x) { return x <= LIMIT; }\nexport function caller(x) { return helper(x); }\n",
        )];
        assert!(!moves(&js, "export function caller", ("helper", "check")));
        assert!(!moves(&js, "export function caller", ("LIMIT", "CAP")));
    }

    #[test]
    fn a_swap_of_two_calls_moves_the_pin() {
        let rs = [(
            RS,
            "fn first(x: u32) { save(x); }\nfn second(x: u32) { drop(x); }\nfn caller() { first(1); second(2); }\n",
        )];
        assert!(moves(
            &rs,
            "fn caller",
            ("first(1); second(2)", "second(1); first(2)")
        ));
        let py = [(
            "app/a.py",
            "def first(x):\n    return x + 1\n\ndef second(x):\n    return x * 2\n\ndef caller(x):\n    return first(second(x))\n",
        )];
        assert!(moves(
            &py,
            "def caller",
            ("first(second(x))", "second(first(x))")
        ));
        // Two members of one cycle share its hash and are told apart by their names.
        let cycle = [(
            RS,
            "fn ping(n: u32) { if n > 0 { pong(n - 1); } }\nfn pong(n: u32) { if n > 1 { ping(n - 2); } }\nfn caller() { ping(1); pong(2); }\n",
        )];
        assert!(moves(
            &cycle,
            "fn caller",
            ("ping(1); pong(2)", "pong(1); ping(2)")
        ));
    }

    #[test]
    fn a_dataclass_field_annotation_moves_a_span_that_constructs_it_and_not_one_that_reads_it() {
        let models = (
            "app/models.py",
            "from dataclasses import dataclass\n\n@dataclass\nclass Refund:\n    amount: int\n",
        );
        let edit = ("amount: int", "amount: str");
        let built = [
            (
                "app/a.py",
                "from app.models import Refund\n\ndef caller(x):\n    return Refund(amount=x)\n",
            ),
            models,
        ];
        assert!(moves(&built, "def caller", edit), "a constructed dataclass");
        let read = [
            (
                "app/a.py",
                "from app.models import Refund\n\ndef caller(r: Refund):\n    return r.amount\n",
            ),
            models,
        ];
        // A stated limit: a class named without a call and a field read through an instance.
        assert!(
            !moves(&read, "def caller", edit),
            "a dataclass read through an instance"
        );
    }

    #[test]
    fn an_import_formatter_rewrite_stays_and_another_import_moves() {
        // § kv22y3ap6.h@9hkhw
        type Case<'a> = (
            &'a str,
            &'a str,
            &'a str,
            &'a [&'a str],
            &'a [(&'a str, &'a str)],
        );
        let cases: [Case; 3] = [
            (
                RS,
                "use crate::m::{pick, Other};\nuse std::fmt;\nfn caller(a: u32) -> u32 { pick(a, 5) }\n",
                "fn caller",
                &[
                    "use crate::m::{\n    Other,\n    pick,\n};\nuse std::fmt;\nfn caller(a: u32) -> u32 { pick(a, 5) }\n",
                    "use std::fmt;\nuse crate::m::Other;\nuse crate::m::pick;\nfn caller(a: u32) -> u32 { pick(a, 5) }\n",
                    "use crate::m::{pick, Third};\nuse std::fmt;\nfn caller(a: u32) -> u32 { pick(a, 5) }\n",
                ],
                &[("crate::m::{pick", "crate::n::{pick"), ("{pick,", "{pick as p, pick,")],
            ),
            (
                "app/a.py",
                "import sys, os\nfrom app.m import pick, Other\n\ndef caller(a):\n    return pick(a, os.sep)\n",
                "def caller",
                &[
                    "import os\nimport sys\nfrom app.m import (\n    Other,\n    pick,\n)\n\ndef caller(a):\n    return pick(a, os.sep)\n",
                    "import os\nfrom app.m import Other\nfrom app.m import pick\n\ndef caller(a):\n    return pick(a, os.sep)\n",
                ],
                &[("app.m import pick", "app.n import pick"), ("sys, os", "sys, os.path as os")],
            ),
            (
                "src/a.ts",
                "import {pick, Other} from './m'\nexport function caller(a) { return pick(a, 5); }\n",
                "export function caller",
                &[
                    "import { Other, pick } from \"./m\";\nexport function caller(a) { return pick(a, 5); }\n",
                    "import {\n  Other,\n  pick,\n} from './m';\nexport function caller(a) { return pick(a, 5); }\n",
                    "import { Other } from './m';\nimport { pick } from './m';\nexport function caller(a) { return pick(a, 5); }\n",
                ],
                &[("'./m'", "'./n'"), ("{pick,", "{pick as p, other as pick,")],
            ),
        ];
        for (path, src, from, kept, moved) in cases {
            let base = stream_from(&[(path, src)], from);
            for other in kept {
                assert_eq!(base, stream_from(&[(path, other)], from), "{other}");
            }
            for &edit in moved {
                assert!(moves(&[(path, src)], from, edit), "{edit:?}");
            }
        }
    }

    #[test]
    fn a_rebind_through_an_import_of_a_name_not_followed_moves_the_pin() {
        let rs = [(
            RS,
            "use std::cmp::max as pick;\nfn caller(a: u32) -> u32 { pick(a, 5) }\n",
        )];
        assert!(moves(&rs, "fn caller", ("std::cmp::max", "std::cmp::min")));
        assert!(blob_from(&rs, "fn caller").ends_with("\n§import use std :: cmp :: max as pick"));
        let py = [(
            "app/a.py",
            "from builtins import max as pick\n\ndef caller(a):\n    return pick(a, 5)\n",
        )];
        assert!(moves(&py, "def caller", ("max as", "min as")));
        let js = [(
            "src/a.ts",
            "import { max as pick } from 'lodash';\nexport function caller(a) { return pick(a, 5); }\n",
        )];
        assert!(moves(&js, "export function caller", ("max as", "min as")));
        // Two technical functions of one name: the `use` that picks one is read.
        let technical = [
            (RS, "use crate::fast::pay;\nfn caller(a: u32) { pay(a); }\n"),
            (
                "src/fast.rs",
                "// silcrow:technical\npub fn pay(a: u32) { save(a); }\n",
            ),
            (
                "src/slow.rs",
                "// silcrow:technical\npub fn pay(a: u32) { drop(a); }\n",
            ),
        ];
        assert!(moves(
            &technical,
            "fn caller",
            ("crate::fast::pay", "crate::slow::pay")
        ));
        assert!(!moves(&technical, "fn caller", ("save(a)", "save(a + 1)")));
    }

    #[test]
    fn a_qualifier_restricts_a_call_to_the_members_its_text_names() {
        let rs = [(
            RS,
            "struct Gate;\nimpl Gate {\n    pub fn check(a: u32) -> bool { a <= 500 }\n    fn run(&self, a: u32) -> bool { self.check2(a) }\n    fn check2(&self, a: u32) -> bool { a <= 7 }\n}\nstruct Other;\nimpl Other {\n    pub fn check(a: u32) -> bool { a <= 9 }\n}\npub fn check(a: u32) -> bool { a <= 3 }\nmod util;\nfn caller(a: u32) -> bool { Gate::check(a) && Gate.run(a) && util::check(a) }\n",
        )];
        let from = "fn caller";
        assert!(moves(&rs, from, ("a <= 500", "a <= 501")), "Type::f");
        assert!(!moves(&rs, from, ("a <= 9", "a <= 10")), "another impl");
        assert!(
            moves(&rs, from, ("a <= 3", "a <= 4")),
            "m::f of a module no file names reads every free function"
        );
        assert!(
            !moves(&rs, from, ("a <= 7", "a <= 8")),
            "a method call on a value"
        );
        let in_impl = "    fn run(&self";
        assert!(moves(&rs, in_impl, ("a <= 7", "a <= 8")), "self.f()");
        let py = [(
            "app/a.py",
            "class Gate:\n    LIMIT = 5\n\n    def check(self, a):\n        return a <= self.LIMIT and self.extra(a)\n\n    def extra(self, a):\n        return a > 1\n\nclass Other:\n    def extra(self, a):\n        return a > 2\n\ndef caller(g, a):\n    return Gate.check(g, a) and g.extra(a)\n",
        )];
        assert!(moves(&py, "def caller", ("a > 1", "a > 0")), "through Gate");
        assert!(
            !moves(&py, "def caller", ("a > 2", "a > 0")),
            "a method on a value"
        );
        assert!(
            moves(&py, "def caller", ("LIMIT = 5", "LIMIT = 6")),
            "self.NAME"
        );
    }

    #[test]
    fn a_constant_is_read_with_every_top_level_statement_of_its_file_that_names_it() {
        let py = [
            (
                "app/main.py",
                "from .cfg import TABLE, Cfg\n\ndef caller(k):\n    return TABLE[k] + Cfg.LIM\n",
            ),
            (
                "app/cfg.py",
                "TABLE = {}\nTABLE['a'] = 1\nTABLE.update(b=2)\nif True:\n    TABLE['c'] = 3\n\nclass Cfg:\n    LIM = 5\n\nsetattr(Cfg, 'LIM', 6)\n\ndef later():\n    TABLE['d'] = 4\n",
            ),
        ];
        let from = "def caller";
        for edit in [
            ("'a'] = 1", "'a'] = 9"),
            ("b=2", "b=9"),
            ("'c'] = 3", "'c'] = 9"),
            ("'LIM', 6", "'LIM', 9"),
            ("LIM = 5", "LIM = 9"),
        ] {
            assert!(moves(&py, from, edit), "{edit:?}");
        }
        assert!(
            !moves(&py, from, ("'d'] = 4", "'d'] = 9")),
            "inside a function, a stated limit"
        );
        let js = [(
            "src/a.ts",
            "export const TABLE = [1];\nTABLE.push(2);\nObject.defineProperty(TABLE, 'x', { value: 3 });\nexport function caller(k) { return TABLE[k]; }\n",
        )];
        assert!(moves(&js, "export function caller", ("push(2)", "push(9)")));
        assert!(moves(
            &js,
            "export function caller",
            ("value: 3", "value: 9")
        ));
        let rs = [(
            RS,
            "const BASE: u32 = 5;\nconst LIMIT: u32 = BASE * 2;\nstatic TABLE: [u32; 2] = [LIMIT, 1];\nfn caller(a: u32) -> bool { a <= LIMIT }\n",
        )];
        assert!(moves(&rs, "fn caller", ("BASE: u32 = 5", "BASE: u32 = 6")));
        // A Rust item that names a constant declares, and never changes, it.
        assert!(!moves(&rs, "fn caller", ("[LIMIT, 1]", "[LIMIT, 2]")));
        // A call in a statement that only names the constant is read as its text.
        let py = [(
            "app/a.py",
            "TABLE = {}\nTABLE['k'] = build()\n\ndef build():\n    return 1\n\ndef caller():\n    return TABLE\n",
        )];
        assert!(moves(&py, "def caller", ("build()\n\n", "rebuild()\n\n")));
        assert!(!moves(&py, "def caller", ("return 1", "return 2")));
    }

    /// An enum and its variants are not read: their names stay as text in the span, and an edit
    /// of the enum moves no pin, where a constant beside it is still read.
    #[test]
    fn an_enum_is_not_read_and_its_names_stay_as_text() {
        let rs = [(
            RS,
            "const CAP: u32 = 5;\nenum Level { Low, High }\nfn caller(a: u32) -> Level { if a > CAP { Level::High } else { Level::Low } }\n",
        )];
        assert!(!moves(&rs, "fn caller", ("Low, High", "Low, Mid, High")));
        assert!(!moves(
            &rs,
            "fn caller",
            ("enum Level", "#[repr(u8)]\nenum Level")
        ));
        assert!(moves(&rs, "fn caller", ("CAP: u32 = 5", "CAP: u32 = 6")));
        assert!(moves(&rs, "fn caller", ("Level::High }", "Level::Low }")));
        let bare = [(
            RS,
            "use Level::*;\nenum Level { Low, High }\nfn caller(a: u32) -> bool { matches!(a, 1) && is(High) }\n",
        )];
        assert!(!moves(&bare, "fn caller", ("Low, High", "Low = 3, High")));
        assert!(moves(&bare, "fn caller", ("is(High)", "is(Low)")));
        let ts = [(
            "src/a.ts",
            "enum Color { Red, Green }\nexport function caller() { return Color.Red; }\n",
        )];
        assert!(!moves(
            &ts,
            "export function caller",
            ("Red, Green", "Red = 2, Green")
        ));
        assert!(moves(
            &ts,
            "export function caller",
            ("Color.Red", "Color.Green")
        ));
    }

    #[test]
    fn a_function_named_without_a_call_and_a_call_in_a_macro_are_followed() {
        let rs = [(
            RS,
            "fn helper(x: u32) -> u32 { x + 1 }\nfn caller(v: Vec<u32>) { v.into_iter().map(helper); println!(\"{}\", helper(2)); }\n",
        )];
        assert!(moves(&rs, "fn caller", ("x + 1", "x + 2")));
        let js = [(
            "src/a.ts",
            "const helper = () => save(1);\nexport function caller() { [1].map(helper); }\n",
        )];
        assert!(moves(&js, "export function caller", ("save(1)", "save(2)")));
    }

    /// A bare name that a function around it declares in its body denotes that declaration,
    /// before a homonym at the top level of another file or of its own: what the nested function
    /// calls is read, and the homonym is not.
    #[test]
    fn a_nested_function_shadows_its_homonyms() {
        let py = [
            (
                "pkg/executor.py",
                "class Executor:\n    def run(self):\n        def step():\n            self._run()\n\n        call_soon(step)\n\n    def _run(self):\n        return self.ready > 1\n\n    def close(self):\n        self.run()\n",
            ),
            ("pkg/step.py", "def step(name):\n    return name + 1\n"),
        ];
        assert!(moves(&py, "    def close", ("ready > 1", "ready > 2")));
        assert!(!moves(&py, "    def close", ("name + 1", "name + 2")));
        let rs = [(
            RS,
            "fn helper() -> u32 { 2 }\nfn work() -> u32 { 7 }\nfn caller() -> u32 {\n    fn helper() -> u32 { work() }\n    helper()\n}\n",
        )];
        assert!(moves(&rs, "fn caller", ("{ 7 }", "{ 8 }")));
        assert!(!moves(&rs, "fn caller", ("{ 2 }", "{ 3 }")));
        let js = [(
            "src/a.ts",
            "function helper() { return 2; }\nfunction work() { return 7; }\nexport function caller() {\n  function helper() { return work(); }\n  return helper();\n}\n",
        )];
        assert!(moves(
            &js,
            "export function caller",
            ("return 7", "return 8")
        ));
        assert!(!moves(
            &js,
            "export function caller",
            ("return 2", "return 3")
        ));
    }

    #[test]
    fn a_local_binding_shadows_a_project_function() {
        let rs = [(
            RS,
            "fn helper(x: u32) -> u32 { x + 1 }\nfn caller(helper: fn(u32) -> u32) { helper(2); }\n",
        )];
        assert!(blob_from(&rs, "fn caller").is_empty());
    }

    #[test]
    fn a_call_of_a_class_reads_its_header_its_body_statements_and_its_constructors() {
        let py = [(
            "pkg/a.py",
            "class Validator(Base):\n    LIMIT = 5\n\n    def __init__(self, x):\n        self.ok = x > 5\n\n    def check(self):\n        return save(self.ok)\n\ndef caller(x):\n    return Validator(x)\n",
        )];
        let from = "def caller";
        assert!(moves(&py, from, ("x > 5", "x > 50")), "__init__");
        assert!(
            moves(&py, from, ("LIMIT = 5", "LIMIT = 6")),
            "a class attribute"
        );
        assert!(moves(&py, from, ("(Base)", "(Other)")), "the header");
        assert!(
            !moves(&py, from, ("save(self.ok)", "drop(self.ok)")),
            "another method"
        );
        let tsx = [(
            "src/a.tsx",
            "class Gate {\n  limit = 5;\n  constructor(x) { this.x = x > 1; }\n  render() { return save(1); }\n}\nexport function caller() { return <Gate amount={1} />; }\n",
        )];
        let from = "export function caller";
        assert!(moves(&tsx, from, ("x > 1", "x > 2")));
        assert!(moves(&tsx, from, ("limit = 5", "limit = 6")));
        assert!(!moves(&tsx, from, ("save(1)", "save(2)")));
    }

    #[test]
    fn marks_stop_or_pierce_a_call() {
        let tech = [(
            RS,
            "// silcrow:technical\nfn helper(x: i32) { save(x); }\nfn caller() { helper(1); }\n",
        )];
        assert!(blob_from(&tech, "fn caller").is_empty());
        let in_string = [(
            RS,
            "const DOC: &str = r\"\n// silcrow:technical\n\"; fn helper(x: i32) { save(x); }\nfn caller() { helper(1); }\n",
        )];
        assert!(!blob_from(&in_string, "fn caller").is_empty());
        let skip = [(
            RS,
            "fn helper(x: i32) { save(x); }\nfn caller() {\n    // silcrow:skip\n    helper(1);\n}\n",
        )];
        assert!(blob_from(&skip, "fn caller").is_empty());
    }

    fn caller_blob(helper: &str) -> String {
        let src = format!("{helper}fn caller() {{ helper(1); }}\n");
        blob_from(&[(RS, &src)], "fn caller")
    }

    #[test]
    fn a_pinned_callee_is_a_boundary_unless_its_span_is_an_explicit_stretch() {
        let boundary = "fn helper(x: i32) {\n    // § abcdefgh1@aaaaa\n    save(x);\n}\n";
        assert!(caller_blob(boundary).is_empty());
        let stretch = "fn helper(x: i32) {\n    // § abcdefgh1@aaaaa\n    save(x);\n    // § end abcdefgh1\n    log(x);\n}\n";
        assert!(!caller_blob(stretch).is_empty());
        assert!(!caller_blob("fn helper(x: i32) {\n    save(x);\n}\n").is_empty());
    }

    #[test]
    fn a_boundary_is_pierced_by_functional_or_follow_and_never_past_technical_or_skip() {
        let pin = "    // § abcdefgh1@aaaaa\n";
        let blob = |decl: &str, call: &str| {
            let src = format!(
                "{decl}fn helper(x: i32) {{\n{pin}    save(x);\n}}\nfn caller() {{\n    {call}helper(1);\n}}\n"
            );
            blob_from(&[(RS, &src)], "fn caller")
        };
        assert!(blob("", "").is_empty(), "a boundary is not followed");
        assert!(!blob("// silcrow:functional\n", "").is_empty());
        assert!(!blob("", "// silcrow:follow\n    ").is_empty());
        assert!(blob("// silcrow:technical\n", "// silcrow:follow\n    ").is_empty());
        assert!(blob("// silcrow:functional\n", "// silcrow:skip\n    ").is_empty());
    }

    #[test]
    fn a_call_a_boundary_stops_keeps_its_name_text() {
        let src = "fn vat(x: u32) -> u32 {\n    // § abcdefgh1@aaaaa\n    x * 7\n}\nfn tax(x: u32) -> u32 {\n    // § abcdefgh2@aaaaa\n    x * 2\n}\nfn caller() { vat(1); }\n";
        let files = [(RS, src)];
        assert!(
            moves(&files, "fn caller", ("{ vat(1)", "{ tax(1)")),
            "a rebind"
        );
        assert!(
            !moves(&files, "fn caller", ("x * 7", "x * 8")),
            "its pin reviews it"
        );
        let tokens =
            FollowIndex::from_sources(&sources(&files), &crate::policy::TestPaths::conventions())
                .name_tokens(
                    Path::new(RS),
                    src.find("fn caller").unwrap(),
                    src.len(),
                    &[],
                    &[],
                );
        assert!(tokens.is_empty(), "{tokens:?}");
    }

    #[test]
    fn boundary_drift_names_only_the_callers_that_do_not_follow_it() {
        let file = |name: &str, body: &str| {
            (
                PathBuf::from(format!("src/billing/{name}.rs")),
                body.to_string(),
            )
        };
        let notice = |vat_decl: &str| {
            FollowIndex::from_sources(&[
                file(
                    "tax",
                    &format!("{vat_decl}fn vat(x: i32) {{\n    // § abcdefgh1@aaaaa\n    save(x);\n}}\n"),
                ),
                file(
                    "plain",
                    "fn total() {\n    // § abcdefgh2@aaaaa\n    vat(1);\n}\n",
                ),
                file(
                    "pierce",
                    "fn audit() {\n    // § abcdefgh3@aaaaa\n    // silcrow:follow\n    vat(2);\n}\n",
                ),
                file(
                    "relay",
                    "fn relay() {\n    // silcrow:follow\n    vat(3);\n}\nfn quote() {\n    // § abcdefgh4@aaaaa\n    relay();\n}\n",
                ),
                file(
                    "gate",
                    "fn gate() {\n    // § abcdefgh5@aaaaa\n    vat(4);\n}\nfn order() {\n    // § abcdefgh6@aaaaa\n    // silcrow:follow\n    gate();\n}\n",
                ),
            ], &crate::policy::TestPaths::conventions())
            .drift_notice(Path::new("src/billing/tax.rs"), 2, "abcdefgh1")
        };
        assert_eq!(
            notice("").as_deref(),
            Some(
                "src/billing/tax.rs:2: § abcdefgh1 drifted; callers carry \
                 § abcdefgh5 (src/billing/gate.rs:2), § abcdefgh6 (src/billing/gate.rs:6), \
                 § abcdefgh2 (src/billing/plain.rs:2). Re-read them."
            ),
            "a caller that follows the boundary, itself or through a relay, is not named"
        );
        assert_eq!(
            notice("// silcrow:functional\n"),
            None,
            "every caller follows it"
        );
    }

    #[test]
    fn a_cycle_is_one_supernode_wherever_its_members_live() {
        let src = |h: &str, out: &str| {
            format!("fn f() {{ g(); }}\nfn g() {{ h(); }}\nfn h() {{ {h} f(); }}\nfn out() {{ {out} }}\nfn k() {{ out(); }}\n")
        };
        let blob = |text: &str| {
            let start = text.find("fn f").unwrap();
            let end = text.find("\nfn g").unwrap();
            index_src(text).pin_blob(Path::new(RS), start, end, &[], &[])
        };
        let base = blob(&src("save(1);", "log(1);"));
        assert_ne!(
            base,
            blob(&src("save(2);", "log(1);")),
            "a member the span does not call"
        );
        let with_out = |o: &str| blob(&src("save(1); out();", o));
        assert_ne!(
            with_out("log(1);"),
            with_out("log(2);"),
            "a callee of another member"
        );
        assert!(index_src("fn walker() { walker(); }\n")
            .pin_blob(Path::new(RS), 0, 25, &[], &[])
            .is_empty());
        let caller = ("src/billing/invoice.rs", "fn caller() { ping(1); }\n");
        let ping = "fn ping(n: u32) { pong(n); }\n";
        let pong = "fn pong(n: u32) { if n > 0 { ping(n - 1); } }\n";
        let apart = blob_from(
            &[caller, ("src/a.rs", ping), ("src/b.rs", pong)],
            "fn caller",
        );
        let together = format!("{ping}{pong}");
        assert_eq!(
            apart,
            blob_from(&[caller, ("src/c/d.rs", &together)], "fn caller")
        );
    }

    fn index_src(src: &str) -> FollowIndex {
        FollowIndex::from_sources(
            &sources(&[(RS, src)]),
            &crate::policy::TestPaths::conventions(),
        )
    }

    #[test]
    fn marks_that_attach_to_nothing_or_follow_nothing_fail() {
        let errors = |src: &str| index_src(src).mark_errors().to_vec();
        assert!(
            errors("fn caller() {\n    // silcrow:follow\n    external(1);\n}\n")[0]
                .contains("names no single function, class or constant of the project")
        );
        let ambiguous = [
            (
                RS,
                "mod a;
mod b;
fn caller() {
    // silcrow:follow
    helper(1);
}
",
            ),
            (
                "src/billing/a.rs",
                "pub fn helper(x: u32) {}
",
            ),
            (
                "src/billing/b.rs",
                "pub fn helper(x: u32) {}
",
            ),
        ];
        assert!(
            FollowIndex::from_sources(
                &sources(&ambiguous),
                &crate::policy::TestPaths::conventions()
            )
            .mark_errors()[0]
                .contains("names no single function"),
            "a follow mark on an ambiguous name"
        );
        let forms = mark_errors_of(&ambiguous);
        assert!(
            forms[0].contains("`crate::billing::a::helper(..)` for src/billing/a.rs; `crate::billing::b::helper(..)` for src/billing/b.rs."),
            "{forms:?}"
        );
        assert!(
            errors("fn caller() {\n    // silcrow:sikp\n    helper(1);\n}\n")[0]
                .contains("is not a follow mark")
        );
        assert!(errors("// silcrow:skip\n\nfn caller() {}\n")[0].contains("attaches to nothing"));
        let documented = "// silcrow:technical\n/// Doc.\n#[inline]\nfn helper() { save(1); }\nfn caller() { helper(); }\n";
        assert!(errors(documented).is_empty());
        assert!(blob_from(&[(RS, documented)], "fn caller").is_empty());
    }

    fn mark_errors_of(files: &[(&str, &str)]) -> Vec<String> {
        FollowIndex::from_sources(&sources(files), &crate::policy::TestPaths::conventions())
            .mark_errors()
            .to_vec()
    }

    /// A `silcrow:follow` mark on a library call or a call on a value passes to the project names
    /// the chain holds, as a path argument or a closure call, past the cone. Unmarked, they follow
    /// as any bare name does, in the cone only.
    #[test]
    fn a_follow_mark_passes_through_a_library_chain_to_the_project_names_it_holds() {
        let rs = (
            "src/util.rs",
            "pub fn fee(x: u32) -> u32 { x + 1 }\npub fn tax(x: u32) -> u32 { x * 2 }\npub fn pending() -> Option<u32> { None }\npub fn other(x: u32) -> u32 { x + 1 }\n",
        );
        let rs_head = "use std::iter::{self, once};\nfn caller(x: u32, a: Vec<u32>) -> u32 {\n    // silcrow:follow\n    let n: u32 = ";
        let ts = (
            "src/util.ts",
            "export function fee(x: number) { return x + 1; }\nexport function tax(x: number) { return x * 2; }\nexport function other(x: number) { return x + 1; }\n",
        );
        let ts_head = "export function caller(x: number) {\n  // silcrow:follow\n  return ";
        let py = (
            "app/util.py",
            "def fee(x, y=0):\n    return x + 1\n\ndef tax(x, y=0):\n    return x * 2\n\ndef other(x, y=0):\n    return x + 1\n",
        );
        let py_head = "import functools\n\ndef caller(xs):\n    # silcrow:follow\n    return ";
        let rs_tail = ";\n    n\n}\n";
        let cases = [
            (
                "src/billing/a.rs",
                rs_head,
                "once(x).chain(a).map(fee).map(tax).sum()",
                rs,
                "fn caller",
                "fn ",
            ),
            (
                "src/billing/a.rs",
                rs_head,
                "iter::from_fn(pending).map(fee).map(tax).sum()",
                rs,
                "fn caller",
                "fn ",
            ),
            (
                "src/billing/a.rs",
                rs_head,
                "Some(x).map(fee).map(tax).unwrap_or(0)",
                rs,
                "fn caller",
                "fn ",
            ),
            (
                "src/billing/a.rs",
                rs_head,
                "once(x)\n        .map(|v| fee(v))\n        .map(|v| tax(v))\n        .sum()",
                rs,
                "fn caller",
                "fn ",
            ),
            (
                "src/billing/a.ts",
                ts_head,
                "Promise.resolve(x).then(fee).then(tax);\n}\n",
                ts,
                "export function caller",
                "function ",
            ),
            (
                "src/billing/a.ts",
                ts_head,
                "[x].map((v) => fee(v)).map((v) => tax(v));\n}\n",
                ts,
                "export function caller",
                "function ",
            ),
            (
                "app/billing/a.py",
                py_head,
                "list(map(tax, map(fee, xs)))\n",
                py,
                "def caller",
                "def ",
            ),
            (
                "app/billing/a.py",
                py_head,
                "functools.reduce(tax, functools.reduce(fee, xs))\n",
                py,
                "def caller",
                "def ",
            ),
        ];
        for (path, head, chain, helpers, from, decl) in cases {
            let tail = if path.ends_with(".rs") { rs_tail } else { "" };
            let caller = format!("{head}{chain}{tail}");
            let marked = [(path, caller.as_str()), helpers];
            assert!(mark_errors_of(&marked).is_empty(), "{chain}");
            assert!(moves(&marked, from, ("x + 1", "x + 3")), "{chain}");
            assert!(moves(&marked, from, ("x * 2", "x * 3")), "{chain}");
            assert!(
                !moves(&marked, from, ("fee", "charge")),
                "a rename: {chain}"
            );
            let swapped = caller
                .replace("fee", "§")
                .replace("tax", "fee")
                .replace('§', "tax");
            assert_ne!(
                stream_from(&marked, from),
                stream_from(&[(path, &swapped), helpers], from),
                "a swap: {chain}"
            );
            let rebind = (&*format!("{decl}other"), &*format!("{decl}fee"));
            assert!(moves(&marked, from, rebind), "a homonym: {chain}");
            let plain = caller
                .replace("// silcrow:follow\n", "")
                .replace("# silcrow:follow\n", "");
            let edit = ("x + 1", "x + 3");
            assert!(
                !moves(&[(path, &plain), helpers], from, edit),
                "unmarked, outside the cone: {chain}"
            );
            let near = path.replace("billing/", "");
            assert!(
                moves(&[(&near, &plain), helpers], from, edit),
                "unmarked, in the cone: {chain}"
            );
        }
        let from_fn = format!("{rs_head}{}{rs_tail}", cases[1].2);
        let marked = [("src/billing/a.rs", from_fn.as_str()), rs];
        assert!(moves(&marked, "fn caller", ("None", "Some(2)")), "from_fn");
        let nothing = format!("{rs_head}once(x).count() as u32{rs_tail}");
        let errors = mark_errors_of(&[("src/billing/a.rs", &nothing), rs]);
        assert_eq!(errors.len(), 1, "{errors:?}");
        assert!(
            errors[0].contains("marks `once(x).count()`") && errors[0].contains("jncrstyg1.h"),
            "{errors:?}"
        );
    }

    /// In Rust, a path or a `use` line that starts at a crate of the workspace, or at `crate`,
    /// narrows a name two crates declare to the files of that crate. A follow mark on a name that
    /// stays ambiguous fails with the forms that resolve it.
    #[test]
    fn a_crate_a_rust_path_starts_at_narrows_to_its_files() {
        let workspace = [
            ("Cargo.toml", "[workspace]\nmembers = [\"crates/*\"]\n"),
            ("crates/app/Cargo.toml", "[package]\nname = \"app\"\n"),
            (
                "crates/crate_a/Cargo.toml",
                "[package]\nname = \"crate-a\"\n",
            ),
            (
                "crates/crate_a/src/lib.rs",
                "pub fn ensure(x: u32) -> bool { x > 1 }\n",
            ),
            (
                "crates/crate_b/Cargo.toml",
                "[package]\nname = \"crate_b\"\n",
            ),
            (
                "crates/crate_b/src/lib.rs",
                "pub fn ensure(x: u32) -> bool { x > 2 }\n",
            ),
        ];
        let with = |caller: &'static str| -> Vec<(&'static str, &'static str)> {
            std::iter::once(("crates/app/src/main.rs", caller))
                .chain(workspace)
                .collect()
        };
        let (a, b) = (("x > 1", "x > 5"), ("x > 2", "x > 5"));
        let imported = with("use crate_a::ensure;\nfn caller(x: u32) -> bool {\n    // silcrow:follow\n    ensure(x)\n}\n");
        assert!(mark_errors_of(&imported).is_empty());
        assert!(moves(&imported, "fn caller", a));
        assert!(!moves(&imported, "fn caller", b));
        assert!(
            moves(&imported, "fn caller", ("crate_a::", "crate_b::")),
            "a rebind"
        );
        let local = ("(x: u32) -> bool { x > 1 }", "(y: u32) -> bool { y > 1 }");
        assert!(!moves(&imported, "fn caller", local), "a rename of a local");
        let qualified =
            with("fn caller(x: u32) -> bool {\n    // silcrow:follow\n    crate_a::ensure(x)\n}\n");
        assert!(mark_errors_of(&qualified).is_empty());
        assert!(moves(&qualified, "fn caller", a));
        assert!(!moves(&qualified, "fn caller", b));
        let renamed: Vec<(&str, String)> = qualified
            .iter()
            .map(|&(p, s)| {
                let s = if p.contains("crate_a/") || p.contains("app/") {
                    s.replace("ensure", "verify")
                } else {
                    s.to_string()
                };
                (p, s)
            })
            .collect();
        let renamed: Vec<(&str, &str)> = renamed.iter().map(|(p, s)| (*p, s.as_str())).collect();
        assert_eq!(
            stream_from(&qualified, "fn caller"),
            stream_from(&renamed, "fn caller"),
            "a rename of the followed function and its call"
        );
        let both = with("fn caller(x: u32) -> bool {\n    // silcrow:follow\n    crate_a::ensure(x) && crate_b::ensure(x + 1)\n}\n");
        assert!(
            moves(
                &both,
                "fn caller",
                (
                    "crate_a::ensure(x) && crate_b::ensure(x + 1)",
                    "crate_b::ensure(x) && crate_a::ensure(x + 1)"
                )
            ),
            "a swap"
        );
        let own = [(
            "crates/crate_b/src/pay.rs",
            "use crate::ensure;\nfn caller(x: u32) -> bool { ensure(x) }\n",
        )];
        let own: Vec<(&str, &str)> = own.into_iter().chain(workspace).collect();
        assert!(
            moves(&own, "fn caller", b),
            "`crate` names the caller's crate"
        );
        assert!(!moves(&own, "fn caller", a));
        let bare = with("fn caller(x: u32) -> bool {\n    // silcrow:follow\n    ensure(x)\n}\n");
        let errors = mark_errors_of(&bare);
        assert_eq!(errors.len(), 1, "{errors:?}");
        for form in [
            "`crate_a::ensure(..)` or `use crate_a::ensure;` for crates/crate_a/src/lib.rs",
            "`crate_b::ensure(..)` or `use crate_b::ensure;` for crates/crate_b/src/lib.rs",
        ] {
            assert!(errors[0].contains(form), "{form}: {errors:?}");
        }
        assert!(
            !moves(&bare, "fn caller", a),
            "an ambiguous name follows nothing"
        );
    }

    /// A refused follow mark names the rule that refuses it, by id, and the form that passes.
    #[test]
    fn a_refused_follow_mark_names_its_rule_and_the_form_that_passes() {
        let rs = |src: &str| mark_errors_of(&[(RS, src)]);
        let expect = |errors: Vec<String>, parts: &[&str]| {
            assert_eq!(errors.len(), 1, "{errors:?}");
            for part in parts {
                assert!(errors[0].contains(part), "{part}: {errors:?}");
            }
        };
        expect(
            rs("fn caller() {\n    // silcrow:follow\n    external(1);\n}\n"),
            &["declares no function, class or constant `external` in this language (pyw49tg9j). Remove the mark"],
        );
        expect(
            rs("fn helper() {}\nfn caller() {\n    // silcrow:folow\n    helper();\n}\n"),
            &["is not a follow mark (jncrstyg1.e). Write `silcrow:follow`."],
        );
        expect(
            rs("// silcrow:skip\n\nfn caller() {}\n"),
            &[
                "attaches to nothing (jncrstyg1.e)",
                "move it there, or remove it",
            ],
        );
        expect(
            rs("fn helper() {}\nfn caller(helper: fn()) {\n    // silcrow:follow\n    helper();\n}\n"),
            &["`helper` is a local of the function around it, which denotes no declaration (pyw49tg9j.a)"],
        );
        expect(
            rs("fn caller(n: u32) -> u32 {\n    // silcrow:follow\n    let m = n.pow(2);\n    m\n}\n"),
            &["marks `n.pow(2)`", "a call on a value names no declaration, so the mark passes to what it holds (jncrstyg1.h)"],
        );
        let outside = [
            (
                "src/pay.rs",
                "use other::fee;\nfn caller() {\n    // silcrow:follow\n    fee(1);\n}\n",
            ),
            ("src/rates.rs", "pub fn fee(x: u32) {}\n"),
        ];
        expect(
            mark_errors_of(&outside),
            &["`fee` lies outside the project by its text, a standard or library path or an import from outside (pyw49tg9j.h). To follow the project's, write `crate::rates::fee(..)` or `use crate::rates::fee;` for src/rates.rs."],
        );
        let py_outside = [
            (
                "app/pay.py",
                "from lib import fee\n\ndef caller():\n    # silcrow:follow\n    return fee(1)\n",
            ),
            ("app/rates.py", "def fee(x):\n    return x\n"),
        ];
        expect(
            mark_errors_of(&py_outside),
            &["(pyw49tg9j.h). To follow the project's, write `rates.fee(..)` for app/rates.py."],
        );
        let methods = [(
            "app/a.py",
            "class A:\n    def check(self):\n        return 1\n\nclass B:\n    def check(self):\n        return 2\n\ndef caller(a):\n    # silcrow:follow\n    return a.check()\n",
        )];
        expect(
            mark_errors_of(&methods),
            &["a method called on a value denotes the one method of its name, and the project declares 2, `A.check`, `B.check` (jncrstyg1.d). Call it through its type: `A.check(..)` for app/a.py; `B.check(..)` for app/a.py."],
        );
        let ts_methods = [(
            "src/a.ts",
            "class A { check() { return 1; } }\nclass B { check() { return 2; } }\nexport function caller(a) {\n  // silcrow:follow\n  return a.check();\n}\n",
        )];
        expect(
            mark_errors_of(&ts_methods),
            &["(jncrstyg1.d). Give the method a name no other method of the project has, or remove the mark."],
        );
        let tests = [
            (
                "src/lib.rs",
                "fn caller() {\n    // silcrow:follow\n    helper(1);\n}\n",
            ),
            ("tests/util.rs", "pub fn helper(x: u32) {}\n"),
        ];
        expect(
            mark_errors_of(&tests),
            &["only test code of another kind than the call declares `helper`, which the call does not reach (pyw49tg9j)"],
        );
        expect(
            rs("fn caller() {\n    // silcrow:follow\n    let n = external(1) + other(2);\n}\n"),
            &[
                "marks `external`, `other`",
                "for `external`, the project declares no",
                "for `other`, the project declares no",
            ],
        );
        // The form a message proposes passes.
        let fixed = [
            (
                "src/pay.rs",
                "use crate::rates::fee;\nfn caller() {\n    // silcrow:follow\n    fee(1);\n}\n",
            ),
            outside[1],
        ];
        assert!(mark_errors_of(&fixed).is_empty());
        let fixed = [(
            "app/a.py",
            "class A:\n    def check(self):\n        return 1\n\nclass B:\n    def check(self):\n        return 2\n\ndef caller(a):\n    # silcrow:follow\n    return A.check(a)\n",
        )];
        assert!(mark_errors_of(&fixed).is_empty());
        assert!(moves(&fixed, "def caller", ("return 1", "return 3")));
        assert!(!moves(&fixed, "def caller", ("return 2", "return 3")));
    }

    #[test]
    fn a_bash_command_follows_the_functions_of_its_name() {
        let caller = ("bin/run.sh", "caller() {\n  helper 1\n}\n");
        let files = [caller, ("bin/lib.sh", "helper() {\n  echo \"$1\"\n}\n")];
        assert!(moves(&files, "caller()", ("echo", "printf")));
        let technical = [
            caller,
            (
                "bin/lib.sh",
                "# silcrow:technical\nhelper() {\n  echo \"$1\"\n}\n",
            ),
        ];
        assert!(blob_from(&technical, "caller()").is_empty());
    }

    #[test]
    fn a_followed_body_that_does_not_parse_fails_closed() {
        let src = "fn helper(x: i32) { save(x; }\nfn caller() { helper(1); }\n";
        let start = src.find("fn caller").unwrap();
        assert!(index_src(src)
            .broken_callee(Path::new(RS), start, src.len(), &[], &[])
            .is_some());
    }

    /// The parse error of a third file, neither the span's nor a followed body's, may swallow
    /// the declaration a name of the span denotes, which then reads as text: the pin fails while
    /// a file in the cone of that name may hide it, and only then.
    #[test]
    fn a_name_whose_declaration_a_parse_error_may_swallow_fails_closed() {
        let broken = |files: &[(&str, &str)], from: &str| {
            let sources = sources(files);
            let (start, end) = span_of(&sources[0].1, from);
            let prefix =
                CodeFile::new(sources[0].0.clone(), sources[0].1.clone()).prefix(start, end);
            FollowIndex::from_sources(&sources, &crate::policy::TestPaths::conventions())
                .broken_callee(&sources[0].0, start, end, &[], &prefix)
        };
        let refund = (
            "src/refund.py",
            "from src.helpers import cap\n\n\ndef refund(charge):\n    return cap(charge)\n",
        );
        for (path, helpers, line) in [
            (
                "src/helpers.py",
                "def other(x):\n    return [x,\n\n\ndef cap(charge):\n    return charge\n",
                2,
            ),
            (
                "src/helpers.py",
                "Z = [1,\n\n\ndef cap(charge):\n    return charge\n",
                1,
            ),
        ] {
            assert_eq!(
                broken(&[refund, (path, helpers)], "def refund"),
                Some(Broken {
                    path: PathBuf::from(path),
                    line,
                    name: Some("cap".into()),
                }),
                "{helpers}"
            );
            let fine = helpers.replace("[x,", "[x]").replace("[1,", "[1]");
            assert_eq!(broken(&[refund, (path, &fine)], "def refund"), None);
        }
        let caller = (
            "src/lib.rs",
            "pub fn refund(c: i32) -> i32 {\n    cap(c)\n}\n",
        );
        for helpers in [
            "fn other() {\n    let a = (1,\n}\n\npub fn cap(c: i32) -> i32 {\n    c\n}\n",
            "/* open\n\npub fn cap(c: i32) -> i32 {\n    c\n}\n",
        ] {
            assert!(
                broken(&[caller, ("src/helpers.rs", helpers)], "pub fn refund")
                    .is_some_and(|b| b.name.as_deref() == Some("cap")),
                "{helpers}"
            );
        }
        let bash = ("bin/run.sh", "refund() {\n  cap \"$1\"\n}\n");
        let lib = "other() {\n  echo 'x\n}\n\ncap() {\n  echo \"$1\"\n}\n";
        assert!(broken(&[bash, ("bin/lib.sh", lib)], "refund()").is_some());
        // Outside the cone, or spelling no such token, the error hides nothing the span reads.
        assert_eq!(broken(&[bash, ("lib.sh", lib)], "refund()"), None);
        let other = lib.replace("cap", "top");
        assert_eq!(broken(&[bash, ("bin/lib.sh", &other)], "refund()"), None);
        // A swallowed constant the span reads denotes nothing too.
        let read = (
            "src/refund.py",
            "from src.consts import LIMIT\n\n\ndef refund(charge):\n    return LIMIT\n",
        );
        let consts = ("src/consts.py", "Z = [1,\n\nLIMIT = 3\n");
        assert!(broken(&[read, consts], "def refund").is_some());
        let read = (
            "src/lib.rs",
            "pub fn refund() -> i32 {\n    consts::LIMIT\n}\n",
        );
        let consts = ("src/consts.rs", "/* open\n\npub const LIMIT: i32 = 3;\n");
        assert!(broken(&[read, consts], "pub fn refund")
            .is_some_and(|b| b.name.as_deref() == Some("LIMIT")));
    }

    /// Audit 9, U2 and U9 to U12: an edit through any top-level statement that names the
    /// constant moves the pin, whatever its form.
    #[test]
    fn audit_nine_constant_forms_move_the_pin() {
        let py = |src: &str| format!("{src}\n\ndef caller():\n    return R\n");
        let cases = [
            ("R = 1\nR = R + 5", ("R = 1", "R = 2")),
            (
                "S = {'k': 1}\nS = {**S, 'j': 2}\nR = S",
                ("'k': 1", "'k': 9"),
            ),
            ("R, B0 = 5, 0", ("5, 0", "6, 0")),
            ("X0 = R = 5", ("= 5", "= 6")),
            ("for R in [5]:\n    pass", ("[5]", "[6]")),
            ("import math as R", ("math", "cmath")),
            ("(R := 5)", ("5)", "6)")),
        ];
        for (src, edit) in cases {
            let text = py(src);
            assert!(moves(&[("app/a.py", &text)], "def caller", edit), "{src}");
        }
        let js = |src: &str| format!("{src}\nexport function caller() {{ return LA; }}\n");
        let cases = [
            ("let LA = 1; LA = LA + 5;", ("= 1;", "= 2;")),
            ("let LA = 1; LA++;", ("LA++", "LA--")),
            ("let LA; [LA] = [5];", ("[5]", "[6]")),
            ("let LA; tmp = LA = 5;", ("= 5", "= 6")),
            ("let LA; for (LA of [5]) {}", ("[5]", "[6]")),
            ("let LA = {}; LA.k++;", ("k++", "k--")),
        ];
        for (src, edit) in cases {
            let text = js(src);
            assert!(
                moves(&[("src/a.js", &text)], "export function caller", edit),
                "{src}"
            );
        }
        let classes = "class CA { static LIM = 1; }\nObject.assign(CA, { \"LIM\": 5 });\nCA[\"LIM\"] = 6;\nObject.assign(CA, {}, { LIM: 7 });\nexport function caller() { return CA.LIM; }\n";
        for edit in [
            ("\"LIM\": 5", "\"LIM\": 9"),
            ("= 6", "= 9"),
            ("LIM: 7", "LIM: 9"),
        ] {
            assert!(
                moves(&[("src/a.js", classes)], "export function caller", edit),
                "{edit:?}"
            );
        }
        // Stated limits: a change that does not spell the name, inside a class body or a
        // function, or through another name.
        let quiet = "class CA { static LIM = 1; static { CA.LIM = 2; } }\nObject.assign(CA, { ...over });\nfunction later() { CA.LIM = 3; }\nexport function caller() { return CA.LIM; }\n";
        for edit in [
            ("LIM = 2", "LIM = 9"),
            ("...over", "...under"),
            ("LIM = 3", "LIM = 9"),
        ] {
            assert!(
                !moves(&[("src/a.js", quiet)], "export function caller", edit),
                "{edit:?}"
            );
        }
        let alias = "TBL = {}\nT2 = TBL\nT2['k'] = 5\n\ndef caller():\n    return TBL\n";
        assert!(
            !moves(&[("app/a.py", alias)], "def caller", ("= 5", "= 6")),
            "U30"
        );
        // Bash variables are not followed.
        let bash = "LIM1=5\nLIM1+=1\ncaller() {\n  echo \"$LIM1\"\n}\n";
        assert!(
            !moves(&[("bin/a.sh", bash)], "caller()", ("LIM1=5", "LIM1=6")),
            "U10"
        );
    }

    /// Audit 9, U4: an import rebinds a call the pin does not follow, and the pin reads it.
    #[test]
    fn audit_nine_import_rebinds_move_the_pin() {
        let rs = [(RS, "use a::f;\nfn caller() -> u32 { f(1) }\n")];
        assert!(
            moves(&rs, "fn caller", ("use a::f", "use b::f")),
            "an external path"
        );
        let boundary = |n: u32| {
            format!("pub fn pay(a: u32) -> u32 {{\n    // § hazvf8z5a@aaaaa\n    a * {n}\n}}\n")
        };
        let (fast, slow) = (boundary(2), boundary(1000));
        let files = [
            (
                RS,
                "use crate::fast::pay;\nfn caller(a: u32) -> u32 { pay(a) + 1 }\n",
            ),
            ("src/fast.rs", fast.as_str()),
            ("src/slow.rs", slow.as_str()),
        ];
        assert!(
            moves(&files, "fn caller", ("crate::fast", "crate::slow")),
            "two boundaries"
        );
        // An import that picks one of two homonyms moves the pin by its line, and the name,
        // ambiguous, reads neither.
        let homonyms = [
            (
                RS,
                "use crate::a::helper;\nfn caller(n: u32) -> u32 { helper(n) }\n",
            ),
            ("src/a.rs", "pub fn helper(n: u32) -> u32 { n + 7 }\n"),
            ("src/b.rs", "pub fn helper(n: u32) -> u32 { n + 9 }\n"),
        ];
        assert!(moves(
            &homonyms,
            "fn caller",
            ("crate::a::helper", "crate::b::helper")
        ));
        assert!(!moves(&homonyms, "fn caller", ("n + 7", "n + 8")));
        assert!(!moves(&homonyms, "fn caller", ("n + 9", "n + 8")));
    }

    /// Audit 9, U5 to U8, U19 to U29: no import, scope, module or export model. A name with
    /// one candidate reads it, one with several reads none, but `cfg` twins.
    #[test]
    fn audit_nine_resolution_items_read_a_single_candidate() {
        let u5 = "rate = 10\n\nclass Fee:\n    rate = 1\n    def charge(self, amount):\n        return amount * rate\n";
        assert!(
            moves(
                &[("app/a.py", u5)],
                "        return",
                ("rate = 10", "rate = 50")
            ),
            "U5"
        );
        let u6 = [
            ("app/a.py", "def fee(x):\n    return x * 2\nfrom app.rates import fee\n\ndef charge(a):\n    return fee(a) + 1\n"),
            ("app/rates.py", "def fee(x):\n    return x * 3\n"),
        ];
        assert!(!moves(&u6, "def charge", ("x * 3", "x * 30")), "U6");
        let u7 = [
            ("app/a.py", "def f():\n    return 'main'\n\ndef a():\n    from other import f\n    return f()\n"),
            ("app/other.py", "def f():\n    return 'other'\n"),
        ];
        assert!(!moves(&u7, "def a", ("'other'", "'x'")), "U7");
        let u8 = [
            ("src/deep.rs", "use crate::fast::*;\npub fn caller() -> u32 { g() }\nfn other() { use crate::slow::g; }\n"),
            ("src/fast.rs", "pub fn g() -> u32 { 1 }\n"),
            ("src/slow.rs", "pub fn g() -> u32 { 2 }\n"),
        ];
        assert!(!moves(&u8, "pub fn caller", ("{ 1 }", "{ 3 }")), "U8");
        let u19 = [(
            "src/a.ts",
            "enum Level { Low = 1 }\nenum Level { High = 5 }\nexport function caller() { return Level.Low; }\n",
        )];
        assert!(
            !moves(&u19, "export function caller", ("Low = 1", "Low = 3")),
            "U19, an enum"
        );
        let u20 = [
            ("src/main.rs", "mod outer {\n    #[path = \"other.rs\"]\n    pub mod inner;\n}\nfn caller() -> u32 { outer::inner::f() }\n"),
            ("src/outer/other.rs", "pub fn f() -> u32 { 2 }\n"),
            ("src/other.rs", "pub fn f() -> u32 { 1 }\n"),
        ];
        assert!(!moves(&u20, "fn caller", ("{ 2 }", "{ 4 }")), "U20 to U23");
        let u24 = [
            ("src/main.rs", "use crate::sys::*;\nfn caller() -> u32 { g() + sys::g() }\n"),
            ("src/sys/mod.rs", "#[cfg(unix)]\nmod unix;\n#[cfg(windows)]\nmod windows;\n#[cfg(unix)]\npub use self::unix::*;\n#[cfg(windows)]\npub use self::windows::*;\n"),
            ("src/sys/unix.rs", "pub fn g() -> u32 { 1 }\n"),
            ("src/sys/windows.rs", "pub fn g() -> u32 { 2 }\n"),
        ];
        assert!(moves(&u24, "fn caller", ("{ 1 }", "{ 3 }")), "U24");
        assert!(moves(&u24, "fn caller", ("{ 2 }", "{ 3 }")), "U24");
        // U25 and U26: a renaming import is read as text. A type it renames declares no member
        // under the alias, so the call names every homonym, here the one body it renames.
        let u25 = [
            (
                "src/main.rs",
                "use crate::gate::Gate as Tier;\nfn caller(a: u32) -> bool { Tier::check(a) }\n",
            ),
            (
                "src/gate.rs",
                "pub struct Gate;\nimpl Gate {\n    pub fn check(a: u32) -> bool { a <= 5 }\n}\n",
            ),
        ];
        assert!(moves(
            &u25,
            "fn caller",
            ("gate::Gate as", "gate::Other as")
        ));
        assert!(
            moves(&u25, "fn caller", ("a <= 5", "a <= 6")),
            "audit 10, U1"
        );
        let u27 = [
            (
                "src/main.js",
                "import { f } from './index.js';\nexport function caller() { return f(); }\n",
            ),
            (
                "src/index.js",
                "export * from './impl.js';\nfunction f() { return 'index'; }\n",
            ),
            ("src/impl.mjs", "export function f() { return 'impl'; }\n"),
        ];
        // An import line never narrows, so the body its `export *` brings in makes two.
        assert!(!moves(&u27, "export function caller", ("'index'", "'x'")));
        assert!(
            !moves(&u27, "export function caller", ("'impl'", "'x'")),
            "U27, U29"
        );
        let u27_bare = [
            (
                "src/main.js",
                "import { f } from './index.js';\nexport function caller() { return f(); }\n",
            ),
            ("src/index.js", "export * from './impl.js';\n"),
            ("src/impl.mjs", "export function f() { return 'impl'; }\n"),
        ];
        assert!(
            moves(&u27_bare, "export function caller", ("'impl'", "'x'")),
            "a module that only re-exports declares none: the one homonym"
        );
        let u28 = [
            (
                "pkg/main.py",
                "from pkg import f\n\ndef caller():\n    return f()\n",
            ),
            ("pkg/one.py", "def f():\n    return 'one'\n"),
            (
                "pkg/two.py",
                "__all__ = ['other']\n\ndef f():\n    return 'two'\n",
            ),
        ];
        assert!(!moves(&u28, "def caller", ("'one'", "'x'")), "U28");
    }

    #[test]
    fn a_name_its_own_file_declares_is_followed_alone_unless_an_import_line_spells_it() {
        let cases: [(&[(&str, &str)], &str); 3] = [
            (
                &[
                    (RS, "fn helper(n: u32) -> u32 { n + 7 }\nfn caller(n: u32) -> u32 { helper(n) }\n"),
                    ("src/b.rs", "pub fn helper(n: u32) -> u32 { n + 9 }\n"),
                ],
                "fn caller",
            ),
            (
                &[
                    ("app/a.py", "def helper(n):\n    return n + 7\n\ndef caller(n):\n    return helper(n)\n"),
                    ("app/b.py", "def helper(n):\n    return n + 9\n"),
                ],
                "def caller",
            ),
            (
                &[
                    ("src/a.js", "function helper(n) { return n + 7; }\nexport function caller(n) { return helper(n); }\n"),
                    ("src/b.js", "export function helper(n) { return n + 9; }\n"),
                ],
                "export function caller",
            ),
        ];
        for (files, from) in cases {
            assert!(moves(files, from, ("n + 7", "n + 8")), "{from}");
            assert!(
                !moves(files, from, ("n + 9", "n + 8")),
                "{from}: the other file"
            );
        }
        // A Rust item of a `mod` block of the same file is its own too.
        let nested = [
            (RS, "mod inner {\n    pub fn helper(n: u32) -> u32 { n + 7 }\n}\nfn caller(n: u32) -> u32 { helper(n) }\n"),
            ("src/b.rs", "pub fn helper(n: u32) -> u32 { n + 9 }\n"),
        ];
        assert!(!moves(&nested, "fn caller", ("n + 9", "n + 8")));
        // An import line that spells the name restores every homonym: two here, so the name
        // reads neither.
        let imported = [
            ("app/a.py", "def helper(n):\n    return n + 7\n\nfrom app.b import helper\n\ndef caller(n):\n    return helper(n)\n"),
            ("app/b.py", "def helper(n):\n    return n + 9\n"),
        ];
        assert!(!moves(&imported, "def caller", ("n + 9", "n + 8")));
        assert!(!moves(&imported, "def caller", ("n + 7", "n + 8")));
        // A Rust attribute is text: a field its string captures follows nothing.
        let attribute = [
            (RS, "#[error(\"ended, {status}\")]\nfn ended() -> u32 { 1 }\nfn caller() -> u32 { ended() }\n"),
            ("src/b.rs", "pub fn status(n: u32) -> u32 { n + 9 }\n"),
        ];
        assert!(!moves(&attribute, "fn caller", ("n + 9", "n + 8")));
        assert!(moves(
            &attribute,
            "fn caller",
            ("ended, {status}", "over, {status}")
        ));
        // A declaration inside a function is not the file's: the name has two candidates and
        // reads neither.
        let inner = [
            ("app/a.py", "def outer():\n    def helper(n):\n        return n + 7\n    return helper\n\ndef caller(n):\n    return helper(n)\n"),
            ("app/b.py", "def helper(n):\n    return n + 9\n"),
        ];
        assert!(!moves(&inner, "def caller", ("n + 9", "n + 8")));
    }

    #[test]
    fn a_rebind_through_an_import_line_moves_the_pin_followed_or_not() {
        let py = [
            (
                "app/a.py",
                "from app.b import helper\n\ndef caller(n):\n    return helper(n)\n",
            ),
            ("app/b.py", "def helper(n):\n    return n + 9\n"),
            ("app/c.py", "def helper(n):\n    return n * 9\n"),
        ];
        assert!(moves(&py, "def caller", ("from app.b", "from app.c")));
        let swapped = [
            ("src/a.js", "import { fast as pay, slow as charge } from './b.js';\nexport function caller(n) { return pay(n) + charge(n); }\n"),
            ("src/b.js", "export function fast(n) { return n; }\nexport function slow(n) { return n * 9; }\n"),
        ];
        assert!(moves(
            &swapped,
            "export function caller",
            ("fast as pay, slow as charge", "slow as pay, fast as charge")
        ));
    }

    #[test]
    fn a_name_two_other_files_declare_reads_neither() {
        let files = [
            ("app/a.py", "def caller(n):\n    return helper(n)\n"),
            ("app/b.py", "def helper(n):\n    return n + 7\n"),
            ("app/c.py", "def helper(n):\n    return n + 9\n"),
        ];
        assert!(!moves(&files, "def caller", ("n + 7", "n + 8")));
        assert!(!moves(&files, "def caller", ("n + 9", "n + 8")));
        assert!(moves(&files[..2], "def caller", ("n + 7", "n + 8")));
    }

    #[test]
    fn a_call_outside_the_project_by_its_text_follows_nothing_and_reads_its_import_line() {
        let helper = ("src/b.rs", "pub fn write(n: u32) -> u32 { n + 9 }\npub fn take(n: u32) -> u32 { n + 9 }\npub fn to_string(n: u32) -> u32 { n + 9 }\n");
        let cargo = ("Cargo.toml", "[package]\nname = \"shop\"\n");
        let cases = [
            "use std::fs;\nfn caller() { fs::write(\"a\", \"b\"); }\n",
            "use std::{fs::{self}, io};\nfn caller() { fs::write(\"a\", \"b\"); }\n",
            "fn caller() { std::fs::write(\"a\", \"b\"); core::mem::take(&mut 1); }\n",
            "use serde_json::to_string;\nfn caller() { to_string(&1); }\n",
            "fn caller() { serde_json::to_string(&1); }\n",
        ];
        for main in cases {
            let files = [(RS, main), helper, cargo];
            assert!(!moves(&files, "fn caller", ("n + 9", "n + 8")), "{main}");
        }
        let files = [(RS, cases[0]), helper, cargo];
        assert!(moves(
            &files,
            "fn caller",
            ("use std::fs;", "use std::io as fs;")
        ));
        let py = [
            (
                "app/a.py",
                "import os\n\ndef caller():\n    return os.getcwd()\n",
            ),
            ("app/b.py", "def getcwd():\n    return 9\n"),
        ];
        assert!(!moves(&py, "def caller", ("return 9", "return 8")));
        assert!(moves(
            &py,
            "def caller",
            ("import os", "import posix as os")
        ));
        let js = [
            ("src/a.js", "import path from 'node:path';\nexport function caller() { return path.join('a'); }\n"),
            ("src/b.js", "export function join(n) { return n + 9; }\n"),
        ];
        assert!(!moves(&js, "export function caller", ("n + 9", "n + 8")));
        // A workspace member is the project's, whatever its path, so a `follow` mark reaches it
        // outside the cone.
        let member = [
            (
                RS,
                "use shop_macros::expand;\nfn caller() -> u32 {\n    // silcrow:follow\n    expand(1)\n}\n",
            ),
            (
                "macros/src/lib.rs",
                "pub fn expand(n: u32) -> u32 { n + 9 }\n",
            ),
            ("macros/Cargo.toml", "[package]\nname = \"shop-macros\"\n"),
        ];
        assert!(moves(&member, "fn caller", ("n + 9", "n + 8")));
    }

    #[test]
    fn a_project_module_named_like_a_standard_one_is_followed() {
        let rs = [
            (
                RS,
                "mod core;\nuse crate::core;\nfn caller() -> u32 { core::f(1) }\n",
            ),
            ("src/core.rs", "pub fn f(n: u32) -> u32 { n + 9 }\n"),
        ];
        assert!(moves(&rs, "fn caller", ("n + 9", "n + 8")));
        let py = [
            (
                "app/a.py",
                "import os\n\ndef caller():\n    return os.getcwd()\n",
            ),
            ("app/os.py", "def getcwd():\n    return 9\n"),
        ];
        assert!(moves(&py, "def caller", ("return 9", "return 8")));
        let js = [
            (
                "src/a.js",
                "import fs from 'fs';\nexport function caller() { return fs.read(1); }\n",
            ),
            ("src/fs.js", "export function read(n) { return n + 9; }\n"),
        ];
        assert!(moves(&js, "export function caller", ("n + 9", "n + 8")));
    }

    #[test]
    fn a_lowercase_qualifier_follows_the_homonyms_of_the_files_its_text_names() {
        let charge = |n: u32| format!("pub fn charge(n: u32) -> u32 {{ n + {n} }}\n");
        let (payments, other) = (charge(9), charge(7));
        let plain = [
            (
                RS,
                "mod payments;\nfn caller() -> u32 { payments::charge(1) }\n",
            ),
            ("src/payments.rs", payments.as_str()),
            ("src/other.rs", other.as_str()),
        ];
        assert!(moves(&plain, "fn caller", ("n + 9", "n + 8")));
        assert!(
            !moves(&plain, "fn caller", ("n + 7", "n + 8")),
            "another file"
        );
        // A qualifier narrows by its own text, never by the path an import line spells for it:
        // `pay` names no file, so every homonym is read, and the line itself is read.
        let alias = [
            (
                RS,
                "use crate::payments as pay;\nfn caller() -> u32 { pay::charge(1) }\n",
            ),
            ("src/payments.rs", payments.as_str()),
            ("src/other.rs", other.as_str()),
        ];
        assert!(!moves(&alias, "fn caller", ("n + 9", "n + 8")));
        assert!(!moves(&alias, "fn caller", ("n + 7", "n + 8")));
        assert!(moves(
            &alias,
            "fn caller",
            ("crate::payments as", "crate::other as")
        ));
        // Audit 10, N4: `use crate::payments;` then `payments::charge()` narrows by the text of
        // the qualifier alone.
        let used = [
            (
                RS,
                "use crate::payments;\nfn caller() -> u32 { payments::charge(1) }\n",
            ),
            ("src/payments.rs", payments.as_str()),
            ("src/other.rs", other.as_str()),
        ];
        assert!(moves(&used, "fn caller", ("n + 9", "n + 8")), "N4");
        assert!(!moves(&used, "fn caller", ("n + 7", "n + 8")), "N4");
        let py = [
            (
                "app/a.py",
                "from app import payments\n\ndef caller():\n    return payments.charge(1)\n",
            ),
            ("app/payments.py", "def charge(n):\n    return n + 9\n"),
            ("app/other.py", "def charge(n):\n    return n + 7\n"),
        ];
        assert!(moves(&py, "def caller", ("n + 9", "n + 8")), "N4");
        assert!(!moves(&py, "def caller", ("n + 7", "n + 8")), "N4");
        // A module file that declares no such name hands it on: every homonym.
        let handed = [
            (
                RS,
                "use crate::payments;\nfn caller() -> u32 { payments::charge(1) }\n",
            ),
            ("src/payments/mod.rs", "mod card;\npub use card::charge;\n"),
            ("src/payments/card.rs", payments.as_str()),
            ("src/other.rs", other.as_str()),
        ];
        assert!(!moves(&handed, "fn caller", ("n + 9", "n + 8")), "U5");
        assert!(!moves(&handed, "fn caller", ("n + 7", "n + 8")), "U5");
    }

    #[test]
    fn moving_a_file_changes_no_digest() {
        let caller = "fn caller() { helper(1); }\n";
        let helper = "fn helper(x: i32) { save(x); }\n";
        let at = |dir: &str| {
            blob_from(
                &[
                    ("src/billing/invoice.rs", caller),
                    (&format!("{dir}/util.rs"), helper),
                ],
                "fn caller",
            )
        };
        assert_eq!(at("src/billing"), at("src/billing/deep/er"));
        assert_ne!(at("src/billing"), at("src"), "out of the cone");
    }

    #[test]
    fn a_bare_name_an_import_binds_reads_its_homonyms_only_when_one() {
        let names = ("app/names.py", "def check_key(k):\n    return k > 1\n");
        let legacy = ("app/legacy.py", "def check_key(k):\n    return k > 2\n");
        let caller = |head: &str| format!("{head}\n\ndef caller(k):\n    return check_key(k)\n");
        // A relative import of the name under its own name narrows to the module it names.
        let plain = caller("from .names import check_key");
        let files = [("app/run.py", plain.as_str()), names, legacy];
        assert!(moves(&files, "def caller", ("k > 1", "k > 7")));
        assert!(
            !moves(&files, "def caller", ("k > 2", "k > 7")),
            "a homonym of another module"
        );
        assert!(
            moves(&files, "def caller", ("from .names", "from .legacy")),
            "a rebind through the import line"
        );
        let dotted = caller("from app.names import check_key");
        let files = [("app/run.py", dotted.as_str()), names, legacy];
        assert!(!moves(&files, "def caller", ("k > 2", "k > 7")));
        // A module that re-exports the name declares none: every homonym is read.
        let api = ("app/api.py", "from .names import check_key\n");
        let through = caller("from .api import check_key");
        let files = [("app/run.py", through.as_str()), api, names, legacy];
        assert!(!moves(&files, "def caller", ("k > 1", "k > 7")));
        assert!(!moves(&files, "def caller", ("k > 2", "k > 7")));
        // A line that names no module binds the name from any file.
        let bare = caller("from . import check_key");
        let files = [("app/run.py", bare.as_str()), names, legacy];
        assert!(!moves(&files, "def caller", ("k > 2", "k > 7")));
        // An alias binds a name the import line reads as text, and every homonym of it is read.
        let aliased = "from .names import check_key as ck\n\ndef caller(k):\n    return ck(k)\n";
        let files = [
            ("app/run.py", aliased),
            ("app/names.py", "def ck(k):\n    return k > 1\n"),
            ("app/legacy.py", "def ck(k):\n    return k > 2\n"),
        ];
        assert!(!moves(&files, "def caller", ("k > 1", "k > 7")));
        assert!(!moves(&files, "def caller", ("k > 2", "k > 7")));
        assert!(moves(&files, "def caller", ("from .names", "from .legacy")));
        // Its own declaration stays read beside every homonym, whichever binds last.
        let both = "from .names import check_key\n\ndef check_key(k):\n    return k > 3\n\ndef caller(k):\n    return check_key(k)\n";
        let files = [("app/run.py", both), names, legacy];
        assert!(!moves(&files, "def caller", ("k > 1", "k > 7")));
        assert!(!moves(&files, "def caller", ("k > 3", "k > 7")));
        assert!(!moves(&files, "def caller", ("k > 2", "k > 7")));
        let js = [
            (
                "src/run.ts",
                "import { checkKey } from './names.js';\nexport function caller(k) { return checkKey(k); }\n",
            ),
            ("src/names.ts", "export function checkKey(k) { return k > 1; }\n"),
            ("src/legacy.ts", "export function checkKey(k) { return k > 2; }\n"),
        ];
        assert!(moves(&js, "export function caller", ("k > 1", "k > 7")));
        assert!(!moves(&js, "export function caller", ("k > 2", "k > 7")));
        let rs = [
            (
                RS,
                "use crate::names::check_key;\nfn caller(k: u32) -> bool { check_key(k) }\n",
            ),
            (
                "src/names.rs",
                "pub fn check_key(k: u32) -> bool { k > 1 }\n",
            ),
            (
                "src/legacy.rs",
                "pub fn check_key(k: u32) -> bool { k > 2 }\n",
            ),
        ];
        assert!(!moves(&rs, "fn caller", ("k > 1", "k > 7")));
        assert!(!moves(&rs, "fn caller", ("k > 2", "k > 7")));
        assert!(moves(&rs, "fn caller", ("crate::names", "crate::legacy")));
        let grouped = [
            (
                RS,
                "use crate::{names::{check_key}};\nfn caller(k: u32) -> bool { check_key(k) }\n",
            ),
            rs[1],
            rs[2],
        ];
        assert!(!moves(&grouped, "fn caller", ("k > 2", "k > 7")));
        let parent = [
            (
                RS,
                "use super::check_key;\nfn caller(k: u32) -> bool { check_key(k) }\n",
            ),
            rs[1],
            rs[2],
        ];
        assert!(!moves(&parent, "fn caller", ("k > 2", "k > 7")));
    }

    /// Audit 10, U1: a capitalised qualifier that no type of its name answers follows every
    /// homonym, whatever module its import line spells.
    #[test]
    fn a_capitalised_qualifier_that_names_no_member_follows_every_homonym() {
        let ts = |head: &str| {
            [
                (
                    "src/pay.ts",
                    format!("{head}\nexport function canPay(amount: number): boolean {{\n  return Rules.underLimit(amount);\n}}\n"),
                ),
                (
                    "src/rules.ts",
                    "export function underLimit(amount: number): boolean {\n  return amount <= 500;\n}\n".to_string(),
                ),
                (
                    "src/legacy.ts",
                    "export function underLimit(amount: number): boolean {\n  return amount <= 9;\n}\n".to_string(),
                ),
            ]
        };
        for head in [
            "import * as Rules from \"./rules\";",
            "import Rules from \"./rules\";",
            "const Rules = require(\"./rules\");",
        ] {
            let files = ts(head);
            let files: Vec<(&str, &str)> = files.iter().map(|(p, s)| (*p, s.as_str())).collect();
            let from = "export function canPay";
            assert!(!moves(&files, from, ("<= 500", "<= 5000000")), "{head}");
            assert!(
                !moves(&files, from, ("<= 9", "<= 10")),
                "{head}: a homonym of another module"
            );
        }
        let rs = [
            (
                RS,
                "mod gate;\nuse crate::gate::Gate;\npub type Policy = Gate;\nfn caller(a: u32) -> bool { Policy::check(a) }\nfn other(a: u32) -> usize { String::new().len() + Vec::<u8>::new().len() }\n",
            ),
            (
                "src/gate.rs",
                "pub struct Gate;\nimpl Gate {\n    pub fn check(a: u32) -> bool { a <= 500 }\n    pub fn new() -> u32 { 7 }\n}\n",
            ),
        ];
        assert!(
            moves(&rs, "fn caller", ("a <= 500", "a <= 5000000")),
            "a type alias"
        );
        assert!(
            !moves(&rs, "fn other", ("{ 7 }", "{ 8 }")),
            "a capitalised qualifier the project declares nothing under lies outside it"
        );
        let found = [(
            RS,
            "struct Gate;\nimpl Gate {\n    fn check(a: u32) -> bool { a <= 5 }\n}\nfn check(a: u32) -> bool { a <= 9 }\nfn caller(a: u32) -> bool { Gate::check(a) }\n",
        )];
        assert!(
            !moves(&found, "fn caller", ("a <= 9", "a <= 10")),
            "a type that declares the member keeps the restriction"
        );
    }

    /// Audit 10, U3, U7 and U8: a receiver reads the members of the class or `impl` around it,
    /// `Self::NAME` and a field that holds a function among them, and the one homonym when that
    /// class declares none of the name.
    #[test]
    fn a_receiver_reads_its_class_and_a_single_homonym_where_its_class_declares_none() {
        let u3 = [(
            RS,
            "impl Other {\n    pub const MAX: u32 = 9;\n}\npub struct Gate;\nimpl Gate {\n    pub const MAX: u32 = 500;\n    pub fn run(&self, amount: u32) -> bool {\n        amount <= Self::MAX\n    }\n}\n",
        )];
        let from = "        amount <=";
        assert!(moves(&u3, from, ("= 500", "= 5_000_000")), "U3");
        assert!(!moves(&u3, from, ("= 9", "= 10")), "another impl");
        let u7 = [(
            "app/views.py",
            "class BaseView:\n    def allowed(self, amount):\n        return amount <= 500\n\n\nclass RefundView(BaseView):\n    def post(self, amount):\n        return self.allowed(amount)\n\n\nclass Own:\n    def allowed(self, amount):\n        return amount <= 7\n\n    def post(self, amount):\n        return self.allowed(amount)\n",
        )];
        assert!(
            !moves(&u7, "        return self.allowed", ("<= 500", "<= 5000000")),
            "U7: two classes declare it, so the name is ambiguous"
        );
        let own = |text: &str| {
            let at = text.rfind("        return self.allowed").expect("the span");
            (at, text.len())
        };
        let after = edited(&u7, ("<= 500", "<= 5000000"));
        let after: Vec<(&str, &str)> = after
            .iter()
            .map(|(p, s)| (p.as_str(), s.as_str()))
            .collect();
        assert_eq!(
            stream_at(&u7, &own),
            stream_at(&after, &own),
            "a class that declares the member reads its own"
        );
        let ts = [(
            "src/svc.ts",
            "export class Base {\n  allowed(amount: number): boolean {\n    return amount <= 500;\n  }\n}\n\nexport class Refunds extends Base {\n  check = (amount: number): boolean => {\n    return amount <= 400;\n  };\n\n  pay(amount: number): boolean {\n    return this.allowed(amount);\n  }\n\n  pay2(amount: number): boolean {\n    return this.check(amount);\n  }\n}\n\nexport class Other {\n  check = (amount: number): boolean => amount <= 9;\n}\n",
        )];
        let (pay, pay2) = ("return this.allowed(amount);", "return this.check(amount);");
        assert!(moves_span(&ts, pay, ("<= 500", "<= 5000000")), "U7");
        assert!(moves_span(&ts, pay2, ("<= 400", "<= 5000000")), "U8");
        assert!(
            !moves_span(&ts, pay2, ("<= 9", "<= 10")),
            "the field of another class"
        );
        let renamed = edited(&ts, ("check", "verify"));
        let renamed: Vec<(&str, &str)> = renamed
            .iter()
            .map(|(p, s)| (p.as_str(), s.as_str()))
            .collect();
        let at = |span: &'static str| {
            move |text: &str| {
                let start = text.find(span).expect("the span");
                (start, start + span.len())
            }
        };
        assert_eq!(
            stream_at(&ts, &at(pay2)),
            stream_at(&renamed, &at("return this.verify(amount);")),
            "renaming the field with its call"
        );
    }

    /// Audit 10, U4 and U5: a `require` line is an import line read as text, and neither it
    /// nor a package file narrows a bare name.
    #[test]
    fn a_require_line_and_a_package_file_do_not_narrow() {
        let rules = (
            "src/rules.js",
            "function underLimit(amount) {\n  return amount <= 500;\n}\n\nmodule.exports = { underLimit };\n",
        );
        let legacy = (
            "src/legacy.js",
            "function underLimit(amount) {\n  return amount <= 9;\n}\n",
        );
        let u4 = [
            (
                "src/pay.js",
                "const { underLimit } = require(\"./rules\");\n\nfunction canPay(amount) {\n  return underLimit(amount);\n}\n",
            ),
            rules,
            legacy,
        ];
        let from = "function canPay";
        assert!(!moves(&u4, from, ("<= 500", "<= 5000000")), "U4");
        assert!(
            !moves(&u4, from, ("<= 9", "<= 10")),
            "a homonym of another module"
        );
        // The line declares the name in its own file too, so one module still makes two.
        assert!(!moves(&u4[..2], from, ("<= 500", "<= 5000000")));
        assert!(
            moves(&u4, from, ("require(\"./rules\")", "require(\"./legacy\")")),
            "a rebind through the line"
        );
        let external = [
            (
                "src/pay.js",
                "const { join } = require(\"path\");\n\nfunction canPay(amount) {\n  return join(amount);\n}\n",
            ),
            ("src/b.js", "function join(n) { return n + 9; }\n"),
        ];
        assert!(!moves(&external, from, ("n + 9", "n + 8")), "a dependency");
        let u5 = [
            (
                "main.py",
                "from app import check_key\n\n\ndef admit(key):\n    return check_key(key)\n",
            ),
            (
                "app/__init__.py",
                "from core.keys import check_key\n\n__all__ = [\"check_key\"]\n",
            ),
            ("app/legacy.py", "def check_key(key):\n    return False\n"),
            (
                "core/keys.py",
                "def check_key(key):\n    return key == \"ok\"\n",
            ),
        ];
        assert!(!moves(&u5, "def admit", ("key == \"ok\"", "True")), "U5");
        let declared = [
            (
                "main.py",
                "from app import check_key\n\n\ndef admit(key):\n    return check_key(key)\n",
            ),
            (
                "app/__init__.py",
                "def check_key(key):\n    return key == \"ok\"\n",
            ),
            ("app/legacy.py", "def check_key(key):\n    return False\n"),
        ];
        assert!(!moves(&declared, "def admit", ("key == \"ok\"", "True")));
        assert!(
            !moves(&declared, "def admit", ("return False", "return True")),
            "a package file that declares the name narrows nothing"
        );
        assert!(moves(
            &declared[..2],
            "def admit",
            ("key == \"ok\"", "True")
        ));
    }

    /// Audit 10, I4 and N2: a name of a refutable Rust pattern reads a constant or a `static`
    /// of its name, never a function.
    #[test]
    fn a_pattern_name_reads_only_constants() {
        let files = [
            (
                RS,
                "mod util;\npub fn read(r: Result<String, ()>) -> Option<String> {\n    match r {\n        Ok(text) => Some(text),\n        Err(_) => None,\n    }\n}\nfn guard(r: Option<u32>) -> bool {\n    match r {\n        Some(n) if n > limit => true,\n        _ => false,\n    }\n}\n",
            ),
            (
                "src/util.rs",
                "pub fn text(n: u32) -> u32 { n + 2 }\npub const limit: u32 = 3;\n",
            ),
        ];
        assert!(!moves(&files, "pub fn read", ("n + 2", "n + 3")), "I4");
        let constant = [
            (RS, files[0].1),
            (
                "src/util.rs",
                "pub const text: u32 = 2;\npub const limit: u32 = 3;\n",
            ),
        ];
        assert!(
            moves(&constant, "pub fn read", ("= 2", "= 3")),
            "a constant"
        );
        assert!(
            moves(&files, "fn guard", ("= 3", "= 4")),
            "a guard reads as any code"
        );
        let local = [
            (
                RS,
                "mod util;\nfn guard(r: Option<u32>) -> bool {\n    match r {\n        Some(text) if text > 1 => true,\n        _ => false,\n    }\n}\n",
            ),
            files[1],
        ];
        assert!(
            !moves(&local, "fn guard", ("n + 2", "n + 3")),
            "a guard reads the local its pattern binds"
        );
    }

    #[test]
    fn a_prefix_follows_the_constants_it_names_and_keeps_its_calls_as_text() {
        let guarded = (
            RS,
            "const LIMIT: u32 = 3;\nfn run(amount: u32) {\n    if amount < LIMIT {\n        go(amount);\n    }\n}\n",
        );
        assert!(
            moves_span(&[guarded], "go(amount);", ("= 3", "= 4")),
            "a constant a control header names"
        );
        let elsewhere = [
            (
                RS,
                "use crate::limits::LIMIT;\nfn run(amount: u32) {\n    if amount < LIMIT {\n        go(amount);\n    }\n}\n",
            ),
            ("src/limits.rs", "pub const LIMIT: u32 = 3;\n"),
        ];
        assert!(
            moves_span(&elsewhere, "go(amount);", ("= 3", "= 4")),
            "a constant of another file"
        );
        for src in [
            "LIMIT = 3\n\n@policy(LIMIT)\ndef run(x):\n    go(x)\n",
            "LIMIT = 3\n\ndef run(x, limit=LIMIT):\n    go(x)\n",
        ] {
            let files = [("src/run.py", src)];
            assert!(moves_span(&files, "go(x)", ("= 3", "= 4")), "{src}");
        }
        let js = [(
            "src/run.js",
            "const LIMIT = 3;\nexport function run(x, limit = LIMIT) {\n    go(x);\n}\n",
        )];
        assert!(moves_span(&js, "go(x);", ("= 3", "= 4")));
        assert!(
            !moves_span(&[guarded], "go(amount);", ("LIMIT", "CAP")),
            "a rename of the constant with its every read, as in the span"
        );
        assert!(
            !moves_span(
                &[guarded],
                "go(amount);",
                ("go(amount);\n    }", "go(amount);\n    }\n    done();")
            ),
            "an edit after the span outside any loop"
        );
        // A call in the prefix is text: an edit of its body moves no pin, a rename does.
        let called = [(
            RS,
            "fn limit() -> u32 { 3 }\nfn run(amount: u32) {\n    if amount < limit() {\n        go(amount);\n    }\n}\n",
        )];
        assert!(!moves_span(&called, "go(amount);", ("{ 3 }", "{ 4 }")));
        assert!(moves_span(&called, "go(amount);", ("limit", "cap")));
        // Audit 10, /tmp/sx10i1: a call bound to a local before the span is text, a constant
        // there is followed. A marker in the block instead spans the block, the call in it.
        let i1 = [(
            "m.py",
            "LIMIT = 3\n\ndef helper10():\n    return 7\n\ndef check12(amount):\n    base = helper10()\n    if amount > LIMIT:\n        pass\n    return amount <= 3\n",
        )];
        let span = "return amount <= 3";
        assert!(!moves_span(&i1, span, ("return 7", "return 8")));
        assert!(moves_span(&i1, span, ("LIMIT = 3", "LIMIT = 4")));
        assert!(moves(&i1, "    base", ("return 7", "return 8")));
        let py_called = [(
            "src/run.py",
            "def limit():\n    return 3\n\ndef run(x, cap=limit()):\n    go(x)\n",
        )];
        assert!(!moves_span(&py_called, "go(x)", ("return 3", "return 4")));
        let valued = [(
            "src/run.py",
            "def key(x):\n    return x\n\ndef run(xs, by=key):\n    go(xs)\n",
        )];
        assert!(
            !moves_span(&valued, "go(xs)", ("return x\n", "return -x\n")),
            "a function the prefix names as a value is text"
        );
        let whole = [(
            "src/run.py",
            "LIMIT = 3\n\n@policy(LIMIT)\ndef run(x):\n    go(x)\n",
        )];
        assert!(
            moves(&whole, "@policy", ("= 3", "= 4")),
            "a span that covers a function reads its decorators"
        );
        let callee = [(
            "src/run.py",
            "LIMIT = 3\n\n@policy(LIMIT)\ndef helper(x):\n    go(x)\n\ndef caller():\n    helper(1)\n",
        )];
        assert!(
            moves(&callee, "def caller", ("= 3", "= 4")),
            "a followed callee reads its decorators"
        );
    }

    /// A stated limit: data a program reads at run time is outside the closure.
    #[test]
    fn a_data_file_a_program_reads_is_not_read() {
        let rs = [
            (
                RS,
                "fn caller() -> &'static str { include_str!(\"limits.json\") }\n",
            ),
            ("src/billing/limits.json", "{\"max\": 5}\n"),
        ];
        assert!(!moves(&rs, "fn caller", ("5", "6")));
        let py = [
            (
                "app/a.py",
                "def caller():\n    return open(\"limits.json\").read()\n",
            ),
            ("app/limits.json", "{\"max\": 5}\n"),
        ];
        assert!(!moves(&py, "def caller", ("5", "6")));
    }

    /// A call that stays inside its own cycle keeps its name text, so renaming a recursive
    /// function with its every call moves its callers.
    #[test]
    fn renaming_a_recursive_function_with_its_calls_moves_the_pin() {
        let files = [(
            RS,
            "fn walk(n: u32) -> u32 { if n == 0 { 0 } else { walk(n - 1) } }\nfn caller(n: u32) -> u32 { walk(n) }\n",
        )];
        assert!(moves(&files, "fn caller", ("walk", "stride")));
        let plain = [(
            RS,
            "fn walk(n: u32) -> u32 { n + 1 }\nfn caller(n: u32) -> u32 { walk(n) }\n",
        )];
        assert!(!moves(&plain, "fn caller", ("walk", "stride")));
    }

    /// A method called on a local denotes nothing, whatever class declares a method of its name.
    #[test]
    fn a_method_called_on_a_local_follows_no_method() {
        let files = [(
            "app/a.py",
            "class Gate:\n    def check(self, amount):\n        return amount <= 5\n\n\ndef caller(g):\n    return g.check(1)\n",
        )];
        assert!(!moves(&files, "def caller", ("<= 5", "<= 6")));
    }

    /// An import line that binds a name from outside the project does not widen a name its own
    /// file declares: that declaration alone is read.
    #[test]
    fn an_outside_import_of_a_name_its_own_file_declares_reads_that_declaration() {
        let files = [
            (
                "app/a.py",
                "from os import path\n\ndef path():\n    return 1\n\ndef caller():\n    return path()\n",
            ),
            ("app/b.py", "def path():\n    return 2\n"),
        ];
        assert!(moves(&files, "def caller", ("return 1", "return 3")));
        assert!(!moves(&files, "def caller", ("return 2", "return 3")));
    }

    /// A class declared inside a function is a local: a call rebound to another such class
    /// moves the pin and a consistent rename of one holds, in every JavaScript family grammar.
    /// A class at the top level stays a declaration of the project, which a call follows.
    #[test]
    fn a_class_declared_in_a_function_is_a_local() {
        let body = "function f() {\n  class A { v() { return 1; } }\n  class B { v() { return 2; } }\n  return new A().v();\n}\n";
        for path in ["src/a.js", "src/a.ts", "src/a.tsx"] {
            let files = [(path, body)];
            assert!(
                moves(&files, "function f", ("new A()", "new B()")),
                "{path}: the rebind"
            );
            assert!(
                moves(
                    &files,
                    "function f",
                    (
                        "class A { v() { return 1; } }\n  class B { v() { return 2; } }",
                        "class B { v() { return 1; } }\n  class A { v() { return 2; } }"
                    )
                ),
                "{path}: the swap"
            );
            assert!(
                !moves(&files, "function f", ("A", "Z")),
                "{path}: the rename"
            );
        }
        let top = [(
            "src/a.ts",
            "class A {\n  constructor() { go(1); }\n}\nfunction go(n: number) {}\nfunction f() {\n  return new A();\n}\n",
        )];
        assert!(moves(&top, "function f", ("go(1)", "go(2)")));
    }
}