silcrow 0.1.0

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
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::path::{Path, PathBuf};

use anyhow::Result;
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)]
pub enum DeclMark {
    Technical,
    Functional,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
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@dcn8g
    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:")
}

/// A body a span may follow: a function, a class, a constant or an enum of the project.
#[derive(Debug, Clone)]
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,
    lang: &'static str,
    /// 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,
    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)]
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)]
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,
    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)]
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>,
    lang: &'static str,
    /// 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, its text with whitespace collapsed, and the
/// names it spells.
#[derive(Debug, Clone)]
struct ImportLine {
    text: String,
    /// The bytes of the statement in its file.
    bytes: (usize, usize),
    names: BTreeSet<String>,
    binds: Vec<Bind>,
}

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

/// Where an import line says a name comes from, by its text.
#[derive(Debug, Clone)]
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),
}

/// 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@080dj
    // 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>,
    /// 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>,
}

/// 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@hd692
        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 {
        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 parts = crate::par::map(
            files.iter().collect(),
            |f| f.text.len(),
            |f| {
                FileNodes::of(
                    f,
                    rows(&test_rows, f),
                    rows(&cfg_rows, f),
                    tests.holds(&f.rel),
                )
            },
        );
        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();
        for (file, part) in files.iter().zip(parts) {
            let Some(mut part) = part else {
                continue;
            };
            if let (Some(tree), Some(lang)) = (&file.tree, file.lang) {
                swallowed.extend(
                    span_lang::swallowing_items(&file.text, tree)
                        .into_iter()
                        .map(|(start, end, line)| Swallowed {
                            path: file.rel.clone(),
                            lang: family(lang),
                            line,
                            text: file.text[start..end].to_string(),
                        }),
                );
            }
            if let Some(tree) = &file.tree {
                for rec in &mut part.functions {
                    rec.broken = rec
                        .reads
                        .iter()
                        .find_map(|&(s, e)| span_lang::hiding_error_line(&file.text, tree, 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 {
                rec.top = !rec.member
                    && !spans_of.iter().any(|&(s, e)| {
                        s <= rec.start && rec.end <= e && (s, e) != (rec.start, rec.end)
                    });
            }
            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)));
            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 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);
        }
        resolve_aliases(files, &mut imports);
        let outside = Outside::of(files, &imports, &functions);
        let lookup = Lookup {
            functions: &functions,
            by_name: &by_name,
            imports: &imports,
            outside: &outside,
        };
        for call in &mut calls {
            call.callees = callees_of(&lookup, call);
        }
        mark_errors.extend(unresolved_marks(files, &calls));

        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@jxctd
        // 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@4zfqz
        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]);
                }
            }
        }

        let mut index = Self {
            functions,
            calls,
            spans,
            callers,
            adj,
            followers,
            scc_of,
            members,
            scc_adj,
            supernode: vec![String::new(); scc_count],
            mark_errors,
            fns_in,
            calls_in,
            imports,
            swallowed,
            unbound,
        };
        index.hash_supernodes(files);
        index
    }

    /// Hashes every body's shape and every supernode, callees first: a followed call names
    /// its callee by the supernode hash it enters by, so a callee is hashed before its callers.
    fn hash_supernodes(&mut self, files: &[CodeFile]) {
        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 sccs in by_level {
            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 {
        let (Some(lang), Some(tree)) = (file.lang, &file.tree) 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@pvq3g
        if rec.lang != "bash" {
            for &at in &rec.names_at {
                tokens.insert(at, "declared".to_string());
            }
        }
        // § end k6rfj5k37.c
        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@j2qty
        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 import lines 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@za90m
        let mut out: Vec<String> = self
            .imports
            .get(&call.path)
            .into_iter()
            .flatten()
            .filter(|line| spells(line, call))
            .map(|line| line.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, 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> {
        // § gx7m90jhm.d@29p79
        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@mvgn9
        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@nchwn
        let Some(boundary) = self
            .spans
            .iter()
            .find(|z| z.path == path && 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(|(z, sees)| !(*sees || (z.path == path && z.line == line)))
            .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, each with whether it also follows it.
    fn reaching(&self, boundary: usize) -> Vec<(&SpanRec, 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]);
        self.spans
            .iter()
            .filter_map(|z| {
                let punch: Vec<(usize, usize)> = self
                    .spans
                    .iter()
                    .filter(|inner| inner.path == z.path && inner.pinned)
                    .map(|inner| (inner.start, inner.end))
                    .filter(|&inner| crate::span::nests_in(inner, (z.start, z.end)))
                    .collect();
                let (mut reach, mut see) = (false, false);
                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];
                        let follows = rec.follows(call.mark);
                        reach |= (callee == boundary && rec.would_follow(call.mark))
                            || (follows && reaches.contains(&callee));
                        see |= follows && sees.contains(&callee);
                    }
                }
                reach.then_some((z, see))
            })
            .collect()
    }

    /// 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@6n22f
        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)| c.path == at && within(c, stretch))
        }));
        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)
        })
    }

    /// 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@36hpc
        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@1yn3x
        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@es616
    // 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 = lookup
            .by_name
            .get(call.name.as_str())
            .into_iter()
            .flatten()
            .copied()
            .filter(|&i| {
                let rec = &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();
        if out.len() > 1 {
            out.clear();
        }
    }
    // § end jncrstyg1.d
    // § pyw49tg9j.f@6225n
    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@mzepb
    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.b@b6cda
    // 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.d@yry5q
    // 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@gffq6
    // 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>,
}

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 mut paths: Vec<Vec<String>> = Vec::new();
        for file in files {
            let segments: Vec<String> = path_segments(&file.rel).map(str::to_string).collect();
            known.extend(segments.iter().cloned());
            paths.push(segments);
            if file.rel.file_name().is_some_and(|n| n == "Cargo.toml") {
                known.extend(cargo_names(&file.text));
            }
            if let (Some(lang), Some(tree)) = (file.lang, &file.tree) {
                if family(lang) == "rust" {
                    let root = tree.root_node();
                    known.extend(rust_item_names(root, &file.text, &["mod_item"]));
                    declared.extend(rust_item_names(
                        root,
                        &file.text,
                        &["struct_item", "union_item", "trait_item", "type_item"],
                    ));
                }
            }
        }
        let provided = |module: &[String]| {
            module.is_empty()
                || paths
                    .iter()
                    .any(|p| p.windows(module.len()).any(|w| w == 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),
                };
                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
    }

    /// 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)))
    }
}

/// 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 name of every Rust item of the `kinds` of a file, at any depth.
fn rust_item_names(root: Node<'_>, source: &str, kinds: &[&str]) -> Vec<String> {
    let mut out = Vec::new();
    let mut stack = vec![root];
    while let Some(node) = stack.pop() {
        if kinds.contains(&node.kind()) {
            out.extend(name_field(node, source));
        }
        let mut cursor = node.walk();
        stack.extend(node.named_children(&mut cursor));
    }
    out
}

/// 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@5mxc6
    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(),
                start: z.start,
                end: z.end,
                boundary_of,
                pinned: z.addr.digest.is_some(),
                prefix,
            }
        })
        .collect()
}

/// Each call or read a call-site `silcrow:follow` marks that names no body of the project:
/// the mark would follow nothing.
fn unresolved_marks(files: &[CodeFile], calls: &[CallRec]) -> Vec<String> {
    // § jncrstyg1.d@v0qkg
    let texts: HashMap<&Path, &str> = files
        .iter()
        .map(|f| (f.rel.as_path(), f.text.as_str()))
        .collect();
    let line = |path: &Path, at: usize| {
        let text = texts.get(path).copied().unwrap_or_default();
        text[..at.min(text.len())].matches('\n').count() + 1
    };
    let mut out: Vec<String> = calls
        .iter()
        .filter(|c| c.mark == Some(CallMark::Follow) && c.callees.is_empty())
        .map(|call| {
            let sep = if call.lang == "rust" { "::" } else { "." };
            let mut named = call.scope.join(sep);
            if !named.is_empty() {
                named.push_str(sep);
            }
            named.push_str(&call.name);
            format!(
                "{}:{}: `silcrow:follow` marks `{named}`, which names no single function, class or constant of the project, so nothing is followed: by the closed rules of pyw49tg9j, and as a method, by the one method of its name, it denotes none or several. Remove the mark, or call the helper through its type or class.",
                call.path.display(),
                line(&call.path, call.start)
            )
        })
        .collect();
    out.sort();
    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.
struct FileNodes {
    functions: Vec<FnRec>,
    calls: Vec<CallRec>,
    imports: Vec<ImportLine>,
    mark_errors: Vec<String>,
    spans: Vec<(SpanMarker, Vec<span_lang::Stretch>)>,
}

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,
    /// 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@4vcaq
        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@qbhzn
        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;
            };
            let known = matches!(payload, "technical" | "functional" | "skip" | "follow");
            if !known {
                out.push(format!(
                    "{}:{line}: `silcrow:{payload}` is not a follow mark. A declaration takes `silcrow:technical` or `silcrow:functional`, a call `silcrow:skip` or `silcrow:follow`.",
                    self.path.display()
                ));
            } else if !self.used.borrow().contains(&line) {
                out.push(format!(
                    "{}:{line}: `silcrow:{payload}` attaches to nothing. 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.",
                    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,
            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.
    fn of(
        file: &CodeFile,
        test_rows: Vec<(usize, usize)>,
        cfg_rows: Vec<(usize, usize)>,
        in_tests: 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();
        let literal = crate::span::lines_opening_in(source, &span_lang::literal_ranges(lang, tree));
        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 = span_lang::free_names(lang, source, tree);
        let src = SourceTree {
            path,
            source,
            lines: &lines,
            literal: &literal,
            lang,
            used: Default::default(),
            classes,
            free_at: free.iter().map(|&(_, start, _)| start).collect(),
            free,
            // § pyw49tg9j@pcx6h
            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(),
        };
        collect_nodes(&src, root, &None, &mut out);
        top_level_values(&src, root, &mut out);
        value_reads(&src, root, &mut out.functions);
        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();
        outermost_marks(&mut out.calls, |at| newlines.partition_point(|&n| n < at));
        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@7w4kx
    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@kzgpz
        ("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@6t28v
    if let Some((name, scope, head, name_at, method)) = jsx_component(file.lang, node, source)
        .or_else(|| {
            (span_lang::is_call_kind(kind) && kind != "macro_invocation")
                .then(|| callee_ident(node, source))
                .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);
    }
    // § 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@ca7r2
    // 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@9thjp
    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@akqax
    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@3g54k
    // 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@94fk9
        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@g826f
    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@ya13j
    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 text = node.utf8_text(source.as_bytes()).unwrap_or("");
        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 {
            text: text.split_whitespace().collect::<Vec<_>>().join(" "),
            bytes: (node.start_byte(), node.end_byte()),
            names,
            binds,
        });
    }
    out
}

/// Whether `line` spells a name `call` writes, the call's own or one of its scope.
fn spells(line: &ImportLine, call: &CallRec) -> bool {
    line.names.contains(&call.name) || call.scope.iter().any(|s| line.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 {
            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@j3nse
    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@2hz90
    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);
            }
        }
    }
}

/// The segments of a JavaScript or TypeScript specifier, and whether it is relative.
fn js_specifier(text: &str) -> (Vec<String>, bool) {
    let spec = text.trim_matches(|c| c == '"' || c == '\'' || c == '`');
    let relative = spec.starts_with('.') || spec.starts_with('/');
    let segments = spec
        .trim_start_matches("node:")
        .split('/')
        .filter(|s| !s.is_empty() && *s != "." && *s != "..")
        .map(str::to_string)
        .collect();
    (segments, relative)
}

/// A name a JavaScript or TypeScript line binds from the module of `segments`.
fn js_bind(name: String, (segments, relative): &(Vec<String>, bool)) -> Bind {
    bind(name, Origin::Module(segments.clone(), *relative))
}

/// 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 = js_specifier(&text(spec));
        let mut names = Vec::new();
        binding_names(target, source, &mut names);
        out.extend(names.into_iter().map(|name| js_bind(name, &spec)));
    }
    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(text),
            "namespace_import" => n.named_child(0).map(text),
            "import_specifier" => n
                .child_by_field_name("alias")
                .or_else(|| n.child_by_field_name("name"))
                .map(text),
            _ => None,
        };
        if let Some(bound) = bound {
            out.push(js_bind(bound, &spec));
        }
        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@v7m64
    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,
    }
}

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@0vcm9
    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::*;

    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.as_ref().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 .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"
        );
    }

    #[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_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)")));
    }

    #[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"
        );
        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());
    }

    #[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");
        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)")));
    }
}