ty_module_resolver 0.0.10

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

* [`file_to_module`][]: resolves the module `.<self>` (often as the first step in resolving `.`)
* [`resolve_module`][]: resolves an absolute module name

You may notice that we actually provide `resolve_(real)_(shadowable)_module_(confident)`.
You almost certainly just want [`resolve_module`][]. The other variations represent
restrictions to answer specific kinds of questions, usually to empower IDE features.

* The `real` variation disallows all stub files, including the vendored typeshed.
  This enables the goto-definition ("real") vs goto-declaration ("stub or real") distinction.

* The `confident` variation disallows "desperate resolution", which is a fallback
  mode where we start trying to use ancestor directories of the importing file
  as search-paths, but only if we failed to resolve it with the normal search-paths.
  This is mostly just a convenience for cases where we don't want to try to define
  the importing file (resolving a `KnownModule` and tests).

* The `shadowable` variation disables some guards that prevents third-party code
  from shadowing any vendored non-stdlib `KnownModule`. In particular `typing_extensions`,
  which we vendor and heavily assume the contents of (and so don't ever want to shadow).
  This enables checking if the user *actually* has `typing_extensions` installed,
  in which case it's ok to suggest it in features like auto-imports.

There is some awkwardness to the structure of the code to specifically enable caching
of queries, as module resolution happens a lot and involves a lot of disk access.

For implementors, see `import-resolution-diagram.svg` for a flow diagram that
specifies ty's implementation of Python's import resolution algorithm.
*/

use std::borrow::Cow;
use std::iter::FusedIterator;

use rustc_hash::{FxBuildHasher, FxHashSet};

use ruff_db::PythonFile;
use ruff_db::files::{File, FilePath, FileRootKind, directory_listing, system_path_to_file};
use ruff_db::source::source_text;
use ruff_db::system::{System, SystemPath, SystemPathBuf};
use ruff_db::vendored::VendoredFileSystem;
use ruff_python_ast::{
    self as ast, PySourceType,
    visitor::{Visitor, walk_body},
};

use crate::db::Db;
use crate::module::{Module, ModuleKind};
use crate::module_name::{ImportingFile, ModuleName};
use crate::path::{ModulePath, SearchPath, SystemOrVendoredPathRef};
use crate::strategy::MisconfigurationStrategy;
use crate::typeshed::{TypeshedVersions, vendored_typeshed_versions};
use crate::{ResolverEnvironment, ResolverFile, SearchPathSettings, SearchPathSettingsError};

/// Resolves a module name to a module.
pub fn resolve_module<'db>(
    db: &'db dyn Db,
    importing_file: ImportingFile<'db>,
    module_name: &ModuleName,
) -> Option<Module<'db>> {
    let resolver_environment = importing_file.resolver_environment(db);
    let interned_name = ModuleNameIngredient::new(
        db,
        module_name,
        ModuleResolveMode::Typing,
        resolver_environment,
    );

    resolve_module_query(db, interned_name)
        .or_else(|| desperately_resolve_module(db, importing_file.file(db), interned_name))
}

/// Resolves the module referenced by a `from` import statement.
///
/// Returns `None` if the statement does not name a valid module or the module cannot be resolved.
pub fn resolve_module_for_import_from<'db>(
    db: &'db dyn Db,
    importing_file: ImportingFile<'db>,
    import: &ast::StmtImportFrom,
) -> Option<Module<'db>> {
    let module_name = ModuleName::from_import_statement(db, importing_file, import).ok()?;
    resolve_module(db, importing_file, &module_name)
}

/// Resolves a module name to a module, without desperate resolution available.
///
/// This is appropriate for resolving a `KnownModule`, or cases where for whatever reason
/// we don't have a well-defined importing file.
pub fn resolve_module_confident<'db>(
    db: &'db dyn Db,
    resolver_environment: ResolverEnvironment<'db>,
    module_name: &ModuleName,
) -> Option<Module<'db>> {
    let interned_name = ModuleNameIngredient::new(
        db,
        module_name,
        ModuleResolveMode::Typing,
        resolver_environment,
    );

    resolve_module_query(db, interned_name)
}

/// Resolves a module name to a module (stubs not allowed).
pub fn resolve_real_module<'db>(
    db: &'db dyn Db,
    importing_file: ImportingFile<'db>,
    module_name: &ModuleName,
) -> Option<Module<'db>> {
    let resolver_environment = importing_file.resolver_environment(db);
    let interned_name = ModuleNameIngredient::new(
        db,
        module_name,
        ModuleResolveMode::Runtime,
        resolver_environment,
    );

    resolve_module_query(db, interned_name)
        .or_else(|| desperately_resolve_module(db, importing_file.file(db), interned_name))
}

/// Resolves a module name to a module, without desperate resolution available (stubs not allowed).
///
/// This is appropriate for resolving a `KnownModule`, or cases where for whatever reason
/// we don't have a well-defined importing file.
pub fn resolve_real_module_confident<'db>(
    db: &'db dyn Db,
    resolver_environment: ResolverEnvironment<'db>,
    module_name: &ModuleName,
) -> Option<Module<'db>> {
    let interned_name = ModuleNameIngredient::new(
        db,
        module_name,
        ModuleResolveMode::Runtime,
        resolver_environment,
    );

    resolve_module_query(db, interned_name)
}

/// Resolves a module name to a module (stubs not allowed, some shadowing is
/// allowed).
///
/// In particular, this allows `typing_extensions` to be shadowed by a
/// non-standard library module. This is useful in the context of the LSP
/// where we don't want to pretend as if these modules are always available at
/// runtime.
///
/// This should generally only be used within the context of the LSP. Using it
/// within ty proper risks being unable to resolve builtin modules since they
/// are involved in an import cycle with `builtins`.
pub fn resolve_real_shadowable_module<'db>(
    db: &'db dyn Db,
    importing_file: ImportingFile<'db>,
    module_name: &ModuleName,
) -> Option<Module<'db>> {
    let resolver_environment = importing_file.resolver_environment(db);
    let interned_name = ModuleNameIngredient::new(
        db,
        module_name,
        ModuleResolveMode::RuntimeSomeShadowingAllowed,
        resolver_environment,
    );

    resolve_module_query(db, interned_name)
        .or_else(|| desperately_resolve_module(db, importing_file.file(db), interned_name))
}

/// Selects typing or runtime module-resolution semantics.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, get_size2::GetSize)]
pub enum ModuleResolveMode {
    /// Resolve modules for type checking, preferring stubs over runtime implementations.
    ///
    /// This is the "normal" mode almost everything uses, as type checkers are in fact supposed
    /// to *prefer* stubs over the actual implementations.
    Typing,

    /// Resolve modules to their runtime implementations without considering stubs.
    ///
    /// This is the "goto definition" mode, where we need to ignore the typing spec and find actual
    /// implementations. When querying searchpaths this also notably replaces typeshed with
    /// the "real" stdlib.
    Runtime,

    /// Like [`ModuleResolveMode::Runtime`], but permits some modules to be shadowed.
    ///
    /// In particular, this allows `typing_extensions` to be shadowed by a
    /// non-standard library module. This is useful in the context of the LSP
    /// where we don't want to pretend as if these modules are always available
    /// at runtime.
    RuntimeSomeShadowingAllowed,
}

#[salsa::interned(heap_size=ruff_memory_usage::heap_size)]
#[derive(Debug)]
pub(crate) struct ModuleResolveModeIngredient<'db> {
    #[returns(copy)]
    resolver_environment: ResolverEnvironment<'db>,
    #[returns(copy)]
    mode: ModuleResolveMode,
}

impl ModuleResolveMode {
    fn is_typing(self) -> bool {
        matches!(self, Self::Typing)
    }

    /// Returns `true` if the module name refers to a standard library module
    /// which can't be shadowed by a first-party module.
    ///
    /// This includes "builtin" modules, which can never be shadowed at runtime
    /// either. Additionally, certain other modules that are involved in an
    /// import cycle with `builtins` (`types`, `typing_extensions`, etc.) are
    /// also considered non-shadowable, unless the module resolution mode
    /// specifically opts into allowing some of them to be shadowed. This
    /// latter set of modules cannot be allowed to be shadowed by first-party
    /// or "extra-path" modules in ty proper, or we risk panics in unexpected
    /// places due to being unable to resolve builtin symbols. This is similar
    /// behaviour to other type checkers such as mypy:
    /// <https://github.com/python/mypy/blob/3807423e9d98e678bf16b13ec8b4f909fe181908/mypy/build.py#L104-L117>
    pub(super) fn is_non_shadowable(self, minor_version: u8, module_name: &str) -> bool {
        // Builtin modules are never shadowable, no matter what.
        if ruff_python_stdlib::sys::is_builtin_module(minor_version, module_name) {
            return true;
        }
        // Similarly for `types`, which is always available at runtime.
        if module_name == "types" {
            return true;
        }

        // Otherwise, some modules should only be conditionally allowed
        // to be shadowed, depending on the module resolution mode.
        match self {
            ModuleResolveMode::Typing | ModuleResolveMode::Runtime => {
                module_name == "typing_extensions"
            }
            ModuleResolveMode::RuntimeSomeShadowingAllowed => false,
        }
    }
}

/// Salsa query that resolves an interned [`ModuleNameIngredient`] to a module.
///
/// This query should not be called directly. Instead, use [`resolve_module`]. It only exists
/// because Salsa requires the module name to be an ingredient.
#[salsa::tracked(returns(copy), heap_size=ruff_memory_usage::heap_size)]
fn resolve_module_query<'db>(
    db: &'db dyn Db,
    module_name: ModuleNameIngredient<'db>,
) -> Option<Module<'db>> {
    let name = module_name.name(db);
    let mode = module_name.mode(db);
    let resolver_environment = module_name.resolver_environment(db);
    let _span = tracing::trace_span!("resolve_module", %name).entered();

    let Some(resolved) = resolve_name(db, resolver_environment, name, mode) else {
        tracing::debug!("Module `{name}` not found in search paths");
        return None;
    };

    resolved
        .into_iter()
        .next()
        .map(|candidate| candidate.into_module(db, resolver_environment, name))
}

/// Like `resolve_module_query` but for cases where it failed to resolve the module
/// and we are now Getting Desperate and willing to try the ancestor directories of
/// the `importing_file` as potential temporary search paths that are private
/// to this import.
///
/// The reason this is split out is because in 99.9% of cases `resolve_module_query`
/// will find the right answer (or no valid answer exists), and we want it to be
/// aggressively cached. Including the `importing_file` as part of that query would
/// trash the caching of import resolution between files.
///
/// Cache desperate resolution because repeated unresolved imports in a project can otherwise
/// re-walk the same importing-file-relative search paths many times.
#[salsa::tracked(returns(copy))]
fn desperately_resolve_module<'db>(
    db: &'db dyn Db,
    importing_file: File,
    module_name: ModuleNameIngredient<'db>,
) -> Option<Module<'db>> {
    let name = module_name.name(db);
    let mode = module_name.mode(db);
    let resolver_environment = module_name.resolver_environment(db);
    let _span = tracing::trace_span!("desperately_resolve_module", %name).entered();

    let Some(resolved) =
        desperately_resolve_name(db, importing_file, resolver_environment, name, mode)
    else {
        let mode = match mode {
            ModuleResolveMode::Typing => "typing mode",
            ModuleResolveMode::Runtime => "runtime mode",
            ModuleResolveMode::RuntimeSomeShadowingAllowed => {
                "runtime mode with some shadowing allowed"
            }
        };
        tracing::debug!("Module `{name}` not found while looking in parent dirs ({mode})");
        return None;
    };

    resolved
        .into_iter()
        .next()
        .map(|candidate| candidate.into_module(db, resolver_environment, name))
}

/// Resolves the module for the given path.
///
/// Returns `None` if the path is not a module locatable via any of the known search paths.
#[allow(unused)]
pub(crate) fn path_to_module<'db>(
    db: &'db dyn Db,
    resolver_environment: ResolverEnvironment<'db>,
    path: &FilePath,
) -> Option<Module<'db>> {
    // It's not entirely clear on first sight why this method calls `file_to_module` instead of
    // it being the other way round, considering that the first thing that `file_to_module` does
    // is to retrieve the file's path.
    //
    // The reason is that `file_to_module` is a tracked Salsa query and salsa queries require that
    // all arguments are Salsa ingredients (something stored in Salsa). `Path`s aren't salsa ingredients but
    // `VfsFile` is. So what we do here is to retrieve the `path`'s `VfsFile` so that we can make
    // use of Salsa's caching and invalidation.
    let file = path.to_file(db)?;
    file_to_module(db, ResolverFile::new(db, file, resolver_environment))
}

/// Resolves the module for the file with the given id.
///
/// Returns `None` if the file is not a module locatable via any of the known search paths.
///
/// This function can be understood as essentially resolving `import .<self>` in the file itself,
/// and indeed, one of its primary jobs is resolving `.<self>` to derive the module name of `.`.
/// This intuition is particularly useful for understanding why it's correct that we pass
/// the file itself as `importing_file` to various subroutines.
#[salsa::tracked(returns(copy), heap_size=ruff_memory_usage::heap_size)]
pub fn file_to_module<'db>(
    db: &'db dyn Db,
    resolver_file: ResolverFile<'db>,
) -> Option<Module<'db>> {
    let resolver_environment = resolver_file.environment(db);
    let file = resolver_file.file(db);
    let _span = tracing::trace_span!("file_to_module", ?file).entered();

    let path = SystemOrVendoredPathRef::try_from_file(db, file)?;

    file_to_module_impl(
        db,
        resolver_file,
        path,
        search_paths(db, resolver_environment, ModuleResolveMode::Typing),
    )
    .or_else(|| {
        file_to_module_impl(
            db,
            resolver_file,
            path,
            relative_desperate_search_paths(db, resolver_file).iter(),
        )
    })
}

fn file_to_module_impl<'db, 'a>(
    db: &'db dyn Db,
    resolver_file: ResolverFile<'db>,
    path: SystemOrVendoredPathRef<'a>,
    mut search_paths: impl Iterator<Item = &'a SearchPath>,
) -> Option<Module<'db>> {
    let module_name = search_paths.find_map(|candidate: &SearchPath| {
        let relative_path = match path {
            SystemOrVendoredPathRef::System(path) => candidate.relativize_system_path(path),
            SystemOrVendoredPathRef::Vendored(path) => candidate.relativize_vendored_path(path),
        }?;
        relative_path.to_module_name()
    })?;

    // Resolve the module name to see if Python would resolve the name to the same path.
    // If it doesn't, then that means that multiple modules have the same name in different
    // root paths, but that the module corresponding to `path` is in a lower priority search path,
    // in which case we ignore it.
    let module = resolve_module(db, ImportingFile::ResolverFile(resolver_file), &module_name)?;
    let module_file = module.file(db)?;

    let file: File = resolver_file.file(db);
    let file_path = file.path(db);
    if file_path == module_file.path(db) {
        return Some(module);
    } else if file.source_type(db) == PySourceType::Python
        && module_file.source_type(db) == PySourceType::Stub
    {
        // If a .py and .pyi are both defined, the .pyi will be the one returned by `resolve_module().file`,
        // which would make us erroneously believe the `.py` is *not* also this module (breaking things
        // like relative imports). So here we try `resolve_real_module().file` to cover both cases.
        let module =
            resolve_real_module(db, ImportingFile::ResolverFile(resolver_file), &module_name)?;
        let module_file = module.file(db)?;
        if file_path == module_file.path(db) {
            return Some(module);
        }
    }
    // This path is for a module with the same name but with a different precedence. For example:
    // ```
    // src/foo.py
    // src/foo/__init__.py
    // ```
    // The module name of `src/foo.py` is `foo`, but the module loaded by Python is `src/foo/__init__.py`.
    // That means we need to ignore `src/foo.py` even though it resolves to the same module name.
    None
}

pub fn search_paths<'db>(
    db: &'db dyn Db,
    resolver_environment: ResolverEnvironment<'db>,
    resolve_mode: ModuleResolveMode,
) -> SearchPathIterator<'db> {
    let search_paths = resolver_environment.search_paths(db);

    SearchPathIterator {
        db,
        static_paths: search_paths.static_paths.iter(),
        stdlib_path: search_paths.stdlib(resolve_mode),
        dynamic_paths: None,
        mode: ModuleResolveModeIngredient::new(db, resolver_environment, resolve_mode),
    }
}

#[derive(Debug, Clone, Copy, Default)]
struct StubPackagePaths<'a> {
    before_stdlib: &'a [SearchPath],
    after_stdlib: &'a [SearchPath],
}

impl StubPackagePaths<'_> {
    fn is_empty(self) -> bool {
        self.before_stdlib.is_empty() && self.after_stdlib.is_empty()
    }
}

#[derive(Clone, Debug, Eq, PartialEq, get_size2::GetSize)]
struct StubPackageIndex {
    paths: Box<[SearchPath]>,
    stdlib_offset: usize,
}

impl StubPackageIndex {
    /// Indexes search paths that may contain a stub package, preserving their position relative to
    /// the standard library.
    fn from_search_paths<'a>(
        db: &dyn Db,
        search_paths: impl Iterator<Item = &'a SearchPath>,
    ) -> Self {
        let mut paths = Vec::new();
        let mut stdlib_offset = None;

        for search_path in search_paths {
            if search_path.is_standard_library() {
                stdlib_offset = Some(paths.len());
            } else if search_path_may_contain_stub_package(db, search_path) {
                paths.push(search_path.clone());
            }
        }

        let stdlib_offset = stdlib_offset.unwrap_or(paths.len());
        Self {
            paths: paths.into_boxed_slice(),
            stdlib_offset,
        }
    }

    /// Returns all indexed paths in normal typing-resolution order.
    fn all(&self) -> StubPackagePaths<'_> {
        StubPackagePaths {
            before_stdlib: self.before_stdlib(),
            after_stdlib: self.after_stdlib(),
        }
    }

    /// Splits the indexed paths between the stub-overlay pass and its normal fallback.
    ///
    /// The overlay contains only extra paths, which all precede stdlib. The fallback retains the
    /// remaining paths' positions relative to stdlib.
    fn split_overlay(&self) -> (StubPackagePaths<'_>, StubPackagePaths<'_>) {
        let before_stdlib = self.before_stdlib();
        let (extra, remaining) =
            before_stdlib.split_at(before_stdlib.partition_point(SearchPath::is_extra));

        (
            StubPackagePaths {
                before_stdlib: extra,
                after_stdlib: &[],
            },
            StubPackagePaths {
                before_stdlib: remaining,
                after_stdlib: self.after_stdlib(),
            },
        )
    }

    /// Returns indexed paths that precede stdlib in normal typing resolution.
    fn before_stdlib(&self) -> &[SearchPath] {
        &self.paths[..self.stdlib_offset]
    }

    /// Returns indexed paths that follow stdlib in normal typing resolution.
    fn after_stdlib(&self) -> &[SearchPath] {
        &self.paths[self.stdlib_offset..]
    }
}

/// Returns an index of search paths that may contain a top-level stub package, preserving their
/// resolution order relative to stdlib.
#[salsa::tracked(returns(ref), heap_size=ruff_memory_usage::heap_size)]
fn stub_package_index(
    db: &dyn Db,
    resolver_environment: ResolverEnvironment<'_>,
) -> StubPackageIndex {
    StubPackageIndex::from_search_paths(
        db,
        search_paths(db, resolver_environment, ModuleResolveMode::Typing),
    )
}

fn search_path_may_contain_stub_package(db: &dyn Db, search_path: &SearchPath) -> bool {
    let Some(path) = search_path.as_system_path() else {
        return false;
    };

    directory_listing(db, path)
        .is_ok_and(|listing| listing.iter().any(|(name, _)| name.ends_with("-stubs")))
}

/// Get the search-paths for desperate resolution of absolute imports in this file.
///
/// Currently this is "all ancestor directories that don't contain an `__init__.py(i)`"
/// (from closest-to-importing-file to farthest).
///
/// (For paranoia purposes, all relative desperate search-paths are also absolute
/// valid desperate search-paths, but don't worry about that.)
///
/// We exclude `__init__.py(i)` dirs to avoid truncating packages.
#[salsa::tracked(returns(as_deref), heap_size=ruff_memory_usage::heap_size)]
fn absolute_desperate_search_paths(
    db: &dyn Db,
    importing_file: ResolverFile<'_>,
) -> Option<Box<[SearchPath]>> {
    let resolver_environment = importing_file.environment(db);
    let importing_file = importing_file.file(db);
    let system = db.system();
    let importing_path = importing_file.path(db).as_system_path()?;

    // Only allow this if the importing_file is under the first-party search path
    let (base_path, rel_path) = search_paths(db, resolver_environment, ModuleResolveMode::Typing)
        .find_map(|search_path| {
        if !search_path.is_first_party() {
            return None;
        }
        Some((
            search_path.as_system_path()?,
            search_path.relativize_system_path_only(importing_path)?,
        ))
    })?;

    // Only allow searching up to the first-party path's root
    let mut search_paths = Vec::new();
    for rel_dir in rel_path.ancestors() {
        let candidate_path = base_path.join(rel_dir);
        let Ok(listing) = directory_listing(db, &candidate_path) else {
            continue;
        };
        // Any dir that isn't a proper package is plausibly some test/script dir that could be
        // added as a search-path at runtime. Notably this reflects pytest's default mode where
        // it adds every dir with a .py to the search-paths (making all test files root modules),
        // unless they see an `__init__.py`, in which case they assume you don't want that.
        let isnt_regular_package = !listing.entry_is_file(db, &candidate_path, "__init__.py")
            && !listing.entry_is_file(db, &candidate_path, "__init__.pyi");
        // Any dir with a pyproject.toml or ty.toml is a valid relative desperate search-path and
        // we want all of those to also be valid absolute desperate search-paths. It doesn't
        // make any sense for a folder to have `pyproject.toml` and `__init__.py` but let's
        // not let something cursed and spooky happen, ok? d
        if isnt_regular_package
            || listing.entry_is_file(db, &candidate_path, "pyproject.toml")
            || listing.entry_is_file(db, &candidate_path, "ty.toml")
        {
            let search_path = SearchPath::first_party(system, candidate_path).ok()?;
            search_paths.push(search_path);
        }
    }

    if search_paths.is_empty() {
        None
    } else {
        Some(search_paths.into_boxed_slice())
    }
}

/// Get the search-paths for desperate resolution of relative imports in this file.
///
/// Currently this is "the closest ancestor dir that contains a pyproject.toml (or ty.toml)",
/// which is a completely arbitrary decision. However it's fairly important that relative
/// desperate search-paths pick a single "best" answer because every one is *valid* but one
/// that's too long or too short may cause problems.
///
/// For now this works well in common cases where we have some larger workspace that contains
/// one or more python projects in sub-directories, and those python projects assume that
/// absolute imports resolve relative to the pyproject.toml they live under.
///
/// Being so strict minimizes concerns about this going off a lot and doing random
/// chaotic things. In particular, all files under a given pyproject.toml will currently
/// agree on this being their desperate search-path, which is really nice.
#[salsa::tracked(returns(clone), heap_size=ruff_memory_usage::heap_size)]
fn relative_desperate_search_paths(
    db: &dyn Db,
    importing_file: ResolverFile<'_>,
) -> Option<SearchPath> {
    let resolver_environment = importing_file.environment(db);
    let importing_file = importing_file.file(db);
    let system = db.system();
    let importing_path = importing_file.path(db).as_system_path()?;

    // Only allow this if the importing_file is under the first-party search path
    let (base_path, rel_path) = search_paths(db, resolver_environment, ModuleResolveMode::Typing)
        .find_map(|search_path| {
        if !search_path.is_first_party() {
            return None;
        }
        Some((
            search_path.as_system_path()?,
            search_path.relativize_system_path_only(importing_path)?,
        ))
    })?;

    // Only allow searching up to the first-party path's root
    for rel_dir in rel_path.ancestors() {
        let candidate_path = base_path.join(rel_dir);
        let Ok(listing) = directory_listing(db, &candidate_path) else {
            continue;
        };
        // Any dir with a pyproject.toml or ty.toml might be a project root
        if listing.entry_is_file(db, &candidate_path, "pyproject.toml")
            || listing.entry_is_file(db, &candidate_path, "ty.toml")
        {
            let search_path = SearchPath::first_party(system, candidate_path).ok()?;
            return Some(search_path);
        }
    }

    None
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, get_size2::GetSize)]
pub struct SearchPaths {
    /// Search paths that have been statically determined purely from reading
    /// ty's configuration settings. These shouldn't ever change unless the
    /// config settings themselves change.
    static_paths: Vec<SearchPath>,

    /// Path to typeshed, which should come immediately after static paths.
    ///
    /// This can currently only be None if the `SystemPath` this points to is already in `static_paths`.
    stdlib_path: Option<SearchPath>,

    /// Path to the real stdlib, this replaces typeshed (`stdlib_path`) for goto-definition searches
    /// ([`ModuleResolveMode::Runtime`]).
    real_stdlib_path: Option<SearchPath>,

    /// site-packages paths are not included in the above fields:
    /// if there are multiple site-packages paths, editable installations can appear
    /// *between* the site-packages paths on `sys.path` at runtime.
    /// That means we can't know where a second or third `site-packages` path should sit
    /// in terms of module-resolution priority until we've discovered the editable installs
    /// for the first `site-packages` path
    site_packages: Vec<SearchPath>,

    typeshed_versions: TypeshedVersions,
}

impl SearchPaths {
    /// Validate and normalize the raw settings given by the user
    /// into settings we can use for module resolution
    ///
    /// This method also implements the typing spec's [module resolution order].
    ///
    /// [module resolution order]: https://typing.python.org/en/latest/spec/distributing.html#import-resolution-ordering
    pub(crate) fn from_settings<Strategy: MisconfigurationStrategy>(
        settings: &SearchPathSettings,
        system: &dyn System,
        vendored: &VendoredFileSystem,
        strategy: &Strategy,
    ) -> Result<Self, Strategy::Error<SearchPathSettingsError>> {
        fn canonicalize(path: &SystemPath, system: &dyn System) -> SystemPathBuf {
            system
                .canonicalize_path(path)
                .unwrap_or_else(|_| path.to_path_buf())
        }

        let SearchPathSettings {
            extra_paths,
            src_roots,
            custom_typeshed: typeshed,
            site_packages_paths,
            real_stdlib_path,
        } = settings;

        let mut static_paths = vec![];

        for path in extra_paths {
            let path = canonicalize(path, system);
            tracing::debug!("Adding extra search-path `{path}`");

            let path = strategy.fallback_opt(
                SearchPath::extra(system, path).map_err(SearchPathSettingsError::from),
                |err| {
                    tracing::debug!("Skipping invalid extra search-path: {err}");
                },
            )?;
            static_paths.extend(path);
        }

        for src_root in src_roots {
            tracing::debug!("Adding first-party search path `{src_root}`");
            let path = strategy.fallback_opt(
                SearchPath::first_party(system, src_root.to_path_buf())
                    .map_err(SearchPathSettingsError::from),
                |err| {
                    tracing::debug!("Skipping invalid first-party search-path: {err}");
                },
            )?;
            static_paths.extend(path);
        }

        let (typeshed_versions, stdlib_path) = if let Some(typeshed) = typeshed {
            let typeshed = canonicalize(typeshed, system);
            tracing::debug!("Adding custom-stdlib search path `{typeshed}`");

            let versions_path = typeshed.join("stdlib/VERSIONS");

            let results = system
                .read_to_string(&versions_path)
                .map_err(|error| SearchPathSettingsError::FailedToReadVersionsFile {
                    path: versions_path,
                    error,
                })
                .and_then(|versions_content| Ok(versions_content.parse()?))
                .and_then(|parsed| Ok((parsed, SearchPath::custom_stdlib(system, &typeshed)?)));

            strategy.fallback(results, |err| {
                tracing::debug!("Skipping custom-stdlib search-path: {err}");
                (
                    vendored_typeshed_versions(vendored),
                    SearchPath::vendored_stdlib(),
                )
            })?
        } else {
            tracing::debug!("Using vendored stdlib");
            (
                vendored_typeshed_versions(vendored),
                SearchPath::vendored_stdlib(),
            )
        };

        let real_stdlib_path = if let Some(path) = real_stdlib_path {
            strategy.fallback_opt(
                SearchPath::real_stdlib(system, path.clone())
                    .map_err(SearchPathSettingsError::from),
                |err| {
                    tracing::debug!("Skipping invalid real-stdlib search-path: {err}");
                },
            )?
        } else {
            None
        };

        let mut site_packages: Vec<_> = Vec::with_capacity(site_packages_paths.len());

        for path in site_packages_paths {
            tracing::debug!("Adding site-packages search path `{path}`");
            let path = strategy.fallback_opt(
                SearchPath::site_packages(system, path.clone())
                    .map_err(SearchPathSettingsError::from),
                |err| {
                    tracing::debug!("Skipping invalid site-packages search-path: {err}");
                },
            )?;
            site_packages.extend(path);
        }

        // TODO vendor typeshed's third-party stubs as well as the stdlib and
        // fallback to them as a final step?
        //
        // See: <https://github.com/astral-sh/ruff/pull/19620#discussion_r2240609135>

        // Filter out module resolution paths that point to the same directory
        // on disk (the same invariant maintained by [`sys.path` at runtime]).
        // (Paths may, however, *overlap* -- e.g. you could have both `src/`
        // and `src/foo` as module resolution paths simultaneously.)
        //
        // This code doesn't use an `IndexSet` because the key is the system
        // path and not the search root.
        //
        // [`sys.path` at runtime]: https://docs.python.org/3/library/site.html#module-site
        let mut seen_paths = FxHashSet::with_capacity_and_hasher(static_paths.len(), FxBuildHasher);

        static_paths.retain(|path| {
            if let Some(path) = path.as_system_path() {
                seen_paths.insert(path.to_path_buf())
            } else {
                true
            }
        });

        // Users probably shouldn't do this but... if they've shadowed their stdlib we should deduplicate it away.
        // This notably will mess up anything that checks if a search path "is the standard library" as we won't
        // "remember" that fact for static paths.
        //
        // (We used to shove these into static_paths, so the above retain implicitly did this. I am opting to
        // preserve this behaviour to avoid getting into the weeds of corner cases.)
        let stdlib_path_is_shadowed = stdlib_path
            .as_system_path()
            .is_some_and(|path| seen_paths.contains(path));
        let real_stdlib_path_is_shadowed = real_stdlib_path
            .as_ref()
            .and_then(SearchPath::as_system_path)
            .is_some_and(|path| seen_paths.contains(path));

        let stdlib_path = if stdlib_path_is_shadowed {
            None
        } else {
            Some(stdlib_path)
        };
        let real_stdlib_path = if real_stdlib_path_is_shadowed {
            None
        } else {
            real_stdlib_path
        };

        Ok(SearchPaths {
            static_paths,
            stdlib_path,
            real_stdlib_path,
            site_packages,
            typeshed_versions,
        })
    }

    /// Returns a new `SearchPaths` with no search paths configured.
    ///
    /// The vendored standard library remains available.
    pub fn empty(vendored: &VendoredFileSystem) -> Self {
        Self {
            static_paths: vec![],
            stdlib_path: Some(SearchPath::vendored_stdlib()),
            real_stdlib_path: None,
            site_packages: vec![],
            typeshed_versions: vendored_typeshed_versions(vendored),
        }
    }

    /// Registers file roots for all non-dynamically discovered search paths.
    pub fn try_register_static_roots(&self, db: &dyn Db) {
        let files = db.files();
        for path in self
            .static_paths
            .iter()
            .chain(self.site_packages.iter())
            .chain(&self.stdlib_path)
        {
            if let Some(system_path) = path.as_system_path() {
                // Nested first-party paths reuse the project root. Other nested paths, such as
                // site-packages inside `.venv`, need their own search-path root.
                if !path.is_first_party() || files.root(db, system_path).is_none() {
                    files.try_add_root(db, system_path, FileRootKind::SearchPath);
                }
            }
        }
    }

    fn stdlib(&self, mode: ModuleResolveMode) -> Option<&SearchPath> {
        match mode {
            ModuleResolveMode::Typing => self.stdlib_path.as_ref(),
            ModuleResolveMode::Runtime | ModuleResolveMode::RuntimeSomeShadowingAllowed => {
                self.real_stdlib_path.as_ref()
            }
        }
    }

    pub fn custom_stdlib(&self) -> Option<&SystemPath> {
        self.stdlib_path
            .as_ref()
            .and_then(SearchPath::as_system_path)
    }

    pub fn typeshed_versions(&self) -> &TypeshedVersions {
        &self.typeshed_versions
    }
}

/// Collect all dynamic search paths. For each `site-packages` path:
/// - Collect that `site-packages` path
/// - Collect any search paths listed in `.pth` files in that `site-packages` directory
///   due to editable installations of third-party packages.
///
/// The editable-install search paths for the first `site-packages` directory
/// should come between the two `site-packages` directories when it comes to
/// module-resolution priority.
#[salsa::tracked(returns(deref), heap_size=ruff_memory_usage::heap_size)]
pub(crate) fn dynamic_resolution_paths<'db>(
    db: &'db dyn Db,
    mode: ModuleResolveModeIngredient<'db>,
) -> Vec<SearchPath> {
    tracing::debug!("Resolving dynamic module resolution paths");

    let SearchPaths {
        static_paths,
        stdlib_path,
        site_packages,
        typeshed_versions: _,
        real_stdlib_path,
    } = mode.resolver_environment(db).search_paths(db);

    let mut dynamic_paths = Vec::new();

    if site_packages.is_empty() {
        return dynamic_paths;
    }

    let mut existing_paths: FxHashSet<_> = static_paths
        .iter()
        .filter_map(|path| path.as_system_path())
        .map(Cow::Borrowed)
        .collect();

    // Use the `ModuleResolveMode` to determine which stdlib (if any) to mark as existing
    let stdlib = match mode.mode(db) {
        ModuleResolveMode::Typing => stdlib_path,
        ModuleResolveMode::Runtime | ModuleResolveMode::RuntimeSomeShadowingAllowed => {
            real_stdlib_path
        }
    };
    if let Some(path) = stdlib.as_ref().and_then(SearchPath::as_system_path) {
        existing_paths.insert(Cow::Borrowed(path));
    }

    let files = db.files();
    let system = db.system();

    for site_packages_search_path in site_packages {
        let site_packages_dir = site_packages_search_path
            .as_system_path()
            .expect("Expected site package path to be a system path");

        if !existing_paths.insert(Cow::Borrowed(site_packages_dir)) {
            continue;
        }

        dynamic_paths.push(site_packages_search_path.clone());

        // As well as modules installed directly into `site-packages`,
        // the directory may also contain `.pth` files.
        // Each `.pth` file in `site-packages` may contain one or more lines
        // containing a (relative or absolute) path.
        // Each of these paths may point to an editable install of a package,
        // so should be considered an additional search path.
        let listing = match directory_listing(db, site_packages_dir) {
            Ok(listing) => listing,
            Err(error) => {
                tracing::warn!(
                    "Failed to search for editable installation in {site_packages_dir}: {error}"
                );
                continue;
            }
        };

        // The Python documentation specifies that `.pth` files in `site-packages`
        // are processed in alphabetical order. `DirectoryListing` is already sorted.
        // https://docs.python.org/3/library/site.html#module-site
        let pth_files = listing.iter().filter(|(name, file_type)| {
            !file_type.is_directory() && SystemPath::new(name).extension() == Some("pth")
        });

        for (name, _) in pth_files {
            let path = site_packages_dir.join(name);
            // Track each `.pth` file independently so content changes invalidate this query.
            let Ok(file) = system_path_to_file(db, &path).inspect_err(|error| {
                tracing::warn!("Failed to open .pth file `{path}`: {error}");
            }) else {
                continue;
            };
            let contents = source_text(db, file);
            if let Some(error) = contents.read_error() {
                tracing::warn!("Failed to read .pth file `{path}`: {error}");
                continue;
            }

            let installations = contents.lines().filter_map(|line| {
                let line = line.trim_end();
                if line.is_empty()
                    || line.starts_with('#')
                    || line.starts_with("import ")
                    || line.starts_with("import\t")
                {
                    return None;
                }

                Some(SystemPath::absolute(line, site_packages_dir))
            });

            for installation in installations {
                let installation = system
                    .canonicalize_path(&installation)
                    .unwrap_or(installation);

                if existing_paths.insert(Cow::Owned(installation.clone())) {
                    match SearchPath::editable(system, installation.clone()) {
                        Ok(search_path) => {
                            tracing::debug!(
                                "Adding editable installation to module resolution path {path}",
                                path = installation
                            );

                            // Register a file root for editable installs that are outside any other root
                            // (Most importantly, don't register a root for editable installations from the project
                            // directory as that would change the durability of files within those folders).
                            // Not having an exact file root for editable installs just means that
                            // some queries (like `list_modules_in`) will run slightly more frequently
                            // than they would otherwise.
                            if let Some(dynamic_path) = search_path.as_system_path() {
                                if files.root(db, dynamic_path).is_none() {
                                    files.try_add_root(db, dynamic_path, FileRootKind::SearchPath);
                                }
                            }

                            dynamic_paths.push(search_path);
                        }

                        Err(error) => {
                            tracing::debug!("Skipping editable installation: {error}");
                        }
                    }
                }
            }
        }
    }

    dynamic_paths
}

/// Iterate over the available module-resolution search paths,
/// following the invariants maintained by [`sys.path` at runtime]:
/// "No item is added to `sys.path` more than once."
/// Dynamic search paths (required for editable installs into `site-packages`)
/// are only calculated lazily.
///
/// [`sys.path` at runtime]: https://docs.python.org/3/library/site.html#module-site
pub struct SearchPathIterator<'db> {
    db: &'db dyn Db,
    static_paths: std::slice::Iter<'db, SearchPath>,
    stdlib_path: Option<&'db SearchPath>,
    dynamic_paths: Option<std::slice::Iter<'db, SearchPath>>,
    mode: ModuleResolveModeIngredient<'db>,
}

impl<'db> Iterator for SearchPathIterator<'db> {
    type Item = &'db SearchPath;

    fn next(&mut self) -> Option<Self::Item> {
        let SearchPathIterator {
            db,
            static_paths,
            stdlib_path,
            mode,
            dynamic_paths,
        } = self;

        static_paths
            .next()
            .or_else(|| stdlib_path.take())
            .or_else(|| {
                dynamic_paths
                    .get_or_insert_with(|| dynamic_resolution_paths(*db, *mode).iter())
                    .next()
            })
    }
}

impl FusedIterator for SearchPathIterator<'_> {}

/// A thin wrapper around a module name, resolution mode, and resolver environment to make them a Salsa
/// ingredient.
///
/// This is needed because Salsa requires that all query arguments are salsa ingredients.
#[salsa::interned(debug, heap_size=ruff_memory_usage::heap_size)]
struct ModuleNameIngredient<'db> {
    #[returns(ref)]
    pub(super) name: ModuleName,
    #[returns(copy)]
    pub(super) mode: ModuleResolveMode,
    #[returns(copy)]
    pub(super) resolver_environment: ResolverEnvironment<'db>,
}

/// Given a module name and a list of search paths in which to lookup modules,
/// attempt to resolve the module name
fn resolve_name<'db>(
    db: &'db dyn Db,
    resolver_environment: ResolverEnvironment<'db>,
    name: &ModuleName,
    mode: ModuleResolveMode,
) -> Option<ResolvedNames> {
    let resolver = NameResolver::new(db, resolver_environment, name, mode);

    match mode {
        ModuleResolveMode::Typing => {
            resolver.resolve_typing(stub_package_index(db, resolver_environment))
        }
        ModuleResolveMode::Runtime | ModuleResolveMode::RuntimeSomeShadowingAllowed => {
            resolver.resolve_runtime(search_paths(db, resolver_environment, mode))
        }
    }
}

/// Like `resolve_name` but for cases where it failed to resolve the module
/// and we are now Getting Desperate and willing to try the ancestor directories of
/// the `importing_file` as potential temporary search paths that are private
/// to this import.
fn desperately_resolve_name<'db>(
    db: &'db dyn Db,
    importing_file: File,
    resolver_environment: ResolverEnvironment<'db>,
    name: &ModuleName,
    mode: ModuleResolveMode,
) -> Option<ResolvedNames> {
    let importing_file = ResolverFile::new(db, importing_file, resolver_environment);
    let search_paths = absolute_desperate_search_paths(db, importing_file).unwrap_or_default();
    let resolver = NameResolver::new(db, resolver_environment, name, mode);

    match mode {
        ModuleResolveMode::Typing => resolver.resolve_desperate_typing(search_paths),
        ModuleResolveMode::Runtime | ModuleResolveMode::RuntimeSomeShadowingAllowed => {
            resolver.resolve_runtime(search_paths.iter())
        }
    }
}

#[derive(Debug, Clone, Copy)]
enum ResolvedModule {
    NamespacePackage,
    LegacyNamespacePackage(File),
    RegularPackage(File),
    Module(File),
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum ComponentFileFilter {
    /// Prefer `.pyi` over `.py` in typing mode, or only accept `.py` in runtime mode.
    ByMode,

    /// Only accept a `.pyi` file.
    StubOnly,
}

/// Where a candidate sits in the typing specification's module-resolution order.
///
/// Variants are declared from highest to lowest precedence so that derived ordering can be used
/// when traversing candidates. This is a precedence tier rather than a total ordering: the stable
/// sorts used by the resolver preserve search-path order between candidates in the same tier.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
enum CandidatePrecedence {
    /// A PEP 561 stub-only package named `<package>-stubs`.
    ///
    /// Stub packages take precedence over candidates for `<package>` regardless of where those
    /// candidates appear in the search-path order.
    StubPackage,

    /// A candidate whose precedence is determined by search-path order.
    ///
    /// This includes `.pyi` and `.py` packages and modules from extra paths, first-party code,
    /// editable installs, site-packages, and the standard library.
    SearchPathOrder,
}

#[derive(Debug, Clone)]
struct ModuleResolutionCandidate {
    path: ModulePath,
    module: ResolvedModule,
    py_typed: PyTyped,
    precedence: CandidatePrecedence,
}

impl ModuleResolutionCandidate {
    fn root(search_path: &SearchPath) -> Self {
        Self::with_precedence(search_path, CandidatePrecedence::SearchPathOrder)
    }

    fn stub(search_path: &SearchPath) -> Self {
        Self::with_precedence(search_path, CandidatePrecedence::StubPackage)
    }

    fn with_precedence(search_path: &SearchPath, precedence: CandidatePrecedence) -> Self {
        Self {
            path: search_path.to_module_path(),
            module: ResolvedModule::NamespacePackage,
            py_typed: PyTyped::Untyped,
            precedence,
        }
    }

    // Is this some kind of namespace package?
    fn is_any_namespace_package(&self) -> bool {
        match self.module {
            ResolvedModule::NamespacePackage => true,
            ResolvedModule::LegacyNamespacePackage(_) => true,
            ResolvedModule::RegularPackage(_) => false,
            ResolvedModule::Module(_) => false,
        }
    }

    // This is the module we were actually interested in resolving, complete the resolution
    fn into_module<'db>(
        self,
        db: &'db dyn Db,
        resolver_environment: ResolverEnvironment<'db>,
        name: &ModuleName,
    ) -> Module<'db> {
        match self.module {
            ResolvedModule::NamespacePackage => {
                tracing::trace!("Resolve namespace package `{name}`");
                Module::namespace_package(db, resolver_environment, Cow::Borrowed(name))
            }
            ResolvedModule::LegacyNamespacePackage(file) => {
                // legacy namespace packages behave like regular packages
                // when they're the target of the resolution
                tracing::trace!(
                    "Resolved legacy namespace package `{name}` to `{path}`",
                    path = file.path(db)
                );
                Module::file_module(
                    db,
                    file,
                    resolver_environment,
                    Cow::Borrowed(name),
                    ModuleKind::Package,
                    self.path.into_search_path(),
                )
            }
            ResolvedModule::RegularPackage(file) => {
                tracing::trace!(
                    "Resolved package `{name}` to `{path}`",
                    path = file.path(db)
                );
                Module::file_module(
                    db,
                    file,
                    resolver_environment,
                    Cow::Borrowed(name),
                    ModuleKind::Package,
                    self.path.into_search_path(),
                )
            }
            ResolvedModule::Module(file) => {
                tracing::trace!("Resolved module `{name}` to `{path}`", path = file.path(db));
                Module::file_module(
                    db,
                    file,
                    resolver_environment,
                    Cow::Borrowed(name),
                    ModuleKind::Module,
                    self.path.into_search_path(),
                )
            }
        }
    }

    fn missing_submodule_is_terminal(&self) -> bool {
        if matches!(self.py_typed, PyTyped::Partial) {
            return false;
        }

        // Regular packages and modules are both terminal. A `foo.py`
        // in a higher-priority search path is not shadowed by
        // `foo/__init__.py` in a lower-priority one. Note that both
        // shadow namespace packages.
        matches!(
            self.module,
            ResolvedModule::RegularPackage(_) | ResolvedModule::Module(_)
        )
    }

    fn to_str<'a>(&self, db: &'a dyn Db) -> Cow<'a, str> {
        match self.module {
            ResolvedModule::NamespacePackage => {
                Cow::Owned(self.path.to_system_path().unwrap_or_default().to_string())
            }
            ResolvedModule::LegacyNamespacePackage(file) => Cow::Borrowed(file.path(db).as_str()),
            ResolvedModule::RegularPackage(file) => Cow::Borrowed(file.path(db).as_str()),
            ResolvedModule::Module(file) => Cow::Borrowed(file.path(db).as_str()),
        }
    }
}

struct NameResolver<'db, 'name> {
    context: ResolverContext<'db>,
    name: &'name ModuleName,
    is_non_shadowable: bool,
}

impl<'db, 'name> NameResolver<'db, 'name> {
    fn new(
        db: &'db dyn Db,
        resolver_environment: ResolverEnvironment<'db>,
        name: &'name ModuleName,
        mode: ModuleResolveMode,
    ) -> Self {
        let python_version = resolver_environment.python_version(db);
        Self {
            context: ResolverContext::new(db, resolver_environment, mode),
            name,
            is_non_shadowable: mode.is_non_shadowable(python_version.minor, name.as_str()),
        }
    }

    /// Resolves the name as seen by a type checker.
    ///
    /// This includes PEP 561 stub packages and user-provided stub overlays, with runtime source as
    /// a fallback when no stub provides the requested module. A stub overlay may use runtime
    /// packages as parents, but its final module must come from a stub file.
    fn resolve_typing(&self, stub_packages: &StubPackageIndex) -> Option<ResolvedNames> {
        if self.name.components().nth(1).is_none() {
            let candidates = self.discover_roots(
                search_paths(
                    self.context.db,
                    self.context.resolver_environment,
                    ModuleResolveMode::Typing,
                ),
                stub_packages.all(),
            );
            return self.resolve_remaining(candidates, ComponentFileFilter::ByMode);
        }

        // Only submodules need separate overlay resolution: their extra-path namespace parent can
        // be shadowed before the resolver reaches the requested stub. Reuse those roots for the
        // normal fallback so that each extra path is probed only once.
        let (overlay_stub_packages, remaining_stub_packages) = stub_packages.split_overlay();
        let mut candidates = self.discover_roots(
            search_paths(
                self.context.db,
                self.context.resolver_environment,
                ModuleResolveMode::Typing,
            )
            .take_while(|search_path| search_path.is_extra()),
            overlay_stub_packages,
        );
        if let Some(resolved) =
            self.resolve_remaining(candidates.clone(), ComponentFileFilter::StubOnly)
        {
            return Some(resolved);
        }

        let remaining_candidates = self.discover_roots(
            search_paths(
                self.context.db,
                self.context.resolver_environment,
                ModuleResolveMode::Typing,
            )
            .skip_while(|search_path| search_path.is_extra()),
            remaining_stub_packages,
        );
        candidates.extend(remaining_candidates);

        self.resolve_remaining(candidates, ComponentFileFilter::ByMode)
    }

    /// Resolves the name for type checking against desperate ancestor search paths.
    ///
    /// These paths can contain PEP 561 stub packages, but never user-provided extra paths, so this
    /// indexes them for stub packages without performing a separate stub-overlay pass. Runtime
    /// resolution instead ignores stub packages and `.pyi` files entirely.
    fn resolve_desperate_typing(&self, search_paths: &[SearchPath]) -> Option<ResolvedNames> {
        let stub_packages =
            StubPackageIndex::from_search_paths(self.context.db, search_paths.iter());
        let candidates = self.discover_roots(search_paths.iter(), stub_packages.all());
        self.resolve_remaining(candidates, ComponentFileFilter::ByMode)
    }

    /// Resolves the name to the implementation that is available at runtime.
    ///
    /// The runtime resolver ignores stub packages and `.pyi` files. Its search paths also use the
    /// real standard library instead of typeshed.
    fn resolve_runtime<'a>(
        &self,
        search_paths: impl Iterator<Item = &'a SearchPath>,
    ) -> Option<ResolvedNames> {
        let candidates = self.discover_roots(search_paths, StubPackagePaths::default());
        self.resolve_remaining(candidates, ComponentFileFilter::ByMode)
    }

    fn discover_roots<'a>(
        &self,
        search_paths: impl Iterator<Item = &'a SearchPath>,
        stub_paths: StubPackagePaths<'_>,
    ) -> ResolvedNames {
        let root_component = self.name.first_component();
        let mut cur_candidates = Vec::new();
        let stub_name = (!stub_paths.is_empty() && !self.is_non_shadowable)
            .then(|| format!("{root_component}-stubs"));
        let mut pending_stub_paths = Vec::new();

        if let Some(stub_name) = &stub_name {
            cur_candidates.extend(stub_paths.before_stdlib.iter().filter_map(|search_path| {
                resolve_stub_package_in_search_path(&self.context, search_path, stub_name)
            }));
            // Defer file probes after stdlib until we know that stdlib does not win.
            pending_stub_paths.extend(stub_paths.after_stdlib.iter().filter(|search_path| {
                candidate_may_exist(
                    &self.context,
                    &ModuleResolutionCandidate::stub(search_path),
                    stub_name,
                )
            }));
        }

        for search_path in search_paths {
            // When a builtin module is imported, standard module resolution is bypassed:
            // the module name always resolves to the stdlib module,
            // even if there's a module of the same name in the first-party root
            // (which would normally result in the stdlib module being overridden).
            // TODO: offer a diagnostic if there is a first-party module of the same name
            if self.is_non_shadowable && !search_path.is_standard_library() {
                continue;
            }

            let is_stdlib = search_path.is_standard_library();
            // A terminal candidate can stop the search unless a matching post-stdlib stub package
            // could still override it. A terminal stdlib candidate always stops the search.
            let can_stop = is_stdlib || pending_stub_paths.is_empty();
            let mut candidate = ModuleResolutionCandidate::root(search_path);
            let resolved = resolve_component(
                &self.context,
                &mut candidate,
                root_component,
                ComponentFileFilter::ByMode,
            )
            .is_ok();
            let terminal = candidate.missing_submodule_is_terminal();
            if resolved {
                cur_candidates.push(candidate);
            }
            // A terminal candidate shadows all later search paths. Earlier candidates remain in
            // play because they already shadow this candidate.
            if terminal && can_stop {
                break;
            }

            // Reaching this point for stdlib means that it did not provide a terminal candidate.
            // The deferred post-stdlib stub packages are therefore eligible, so resolve them now.
            if is_stdlib && let Some(stub_name) = &stub_name {
                cur_candidates.extend(pending_stub_paths.drain(..).filter_map(|search_path| {
                    resolve_stub_package_in_search_path(&self.context, search_path, stub_name)
                }));
            }
        }

        cur_candidates
    }

    fn resolve_remaining(
        &self,
        mut cur_candidates: ResolvedNames,
        final_filter: ComponentFileFilter,
    ) -> Option<ResolvedNames> {
        if cur_candidates.is_empty() {
            return None;
        }

        let mut components = self.name.components().skip(1).peekable();

        loop {
            // Keep a partial stub package's namespace while resolving the next part of the module
            // name. Once the complete name is resolved, a concrete package or module shadows that
            // namespace.
            let has_remaining_components = components.peek().is_some();
            cur_candidates =
                normalize_candidates(self.context.db, cur_candidates, has_remaining_components);

            let Some(component) = components.next() else {
                return Some(cur_candidates);
            };
            let file_filter = if components.peek().is_some() {
                ComponentFileFilter::ByMode
            } else {
                final_filter
            };

            let mut remaining_are_shadowed = false;
            cur_candidates.retain_mut(|candidate| {
                if remaining_are_shadowed {
                    return false;
                }

                let resolved =
                    resolve_component(&self.context, candidate, component, file_filter).is_ok();

                // A terminal candidate shadows every lower-priority candidate, even if resolving
                // this component fails. Higher-priority candidates remain in play.
                remaining_are_shadowed = candidate.missing_submodule_is_terminal();

                resolved
            });

            if cur_candidates.is_empty() {
                return None;
            }
        }
    }
}

fn resolve_stub_package_in_search_path(
    context: &ResolverContext,
    search_path: &SearchPath,
    stub_name: &str,
) -> Option<ModuleResolutionCandidate> {
    let mut candidate = ModuleResolutionCandidate::stub(search_path);
    resolve_component(
        context,
        &mut candidate,
        stub_name,
        ComponentFileFilter::ByMode,
    )
    .ok()?;

    // `mypackage-stubs.py(i)` is not a valid result.
    if matches!(candidate.module, ResolvedModule::Module(_)) {
        tracing::debug!(
            "Search path `{search_path}` contains a module named `{stub_name}` but a standalone \
             module isn't a valid stub."
        );
        None
    } else {
        Some(candidate)
    }
}

fn normalize_candidates(
    db: &dyn Db,
    mut candidates: ResolvedNames,
    has_remaining_components: bool,
) -> ResolvedNames {
    let best_concrete_precedence = candidates
        .iter()
        .filter(|candidate| !candidate.is_any_namespace_package())
        .map(|candidate| candidate.precedence)
        .min();

    candidates.sort_by_key(|candidate| candidate.precedence);

    // Note that we intentionally do *not* filter out ordinary search-path candidates when a stub
    // package is found. Even when a non-namespace, non-partial stub package exists, we keep the
    // other candidates as fallbacks because sub-packages within the stubs may override py.typed to
    // partial. The stub-package candidate is ordered first so it takes priority. Other candidates
    // are only used when the stub package fails to find a submodule in a partial sub-package.
    candidates.retain(|candidate| {
        if !candidate.is_any_namespace_package() {
            return true;
        }

        // A higher-precedence partial namespace remains available while resolving its descendants.
        // At the final component, a concrete package or module shadows it.
        let preserved_for_descendants = best_concrete_precedence.is_none_or(|precedence| {
            has_remaining_components
                && candidate.py_typed == PyTyped::Partial
                && candidate.precedence < precedence
        });

        if preserved_for_descendants {
            return true;
        }

        // TODO: It might be useful to warn when a concrete package or module shadows a legacy
        // namespace package. If we only find legacy and non-legacy namespace packages, this logic
        // retains both.

        tracing::trace!(
            "Discarding namespace package `{}` because a non-namespace entry of the same name \
             was found",
            candidate.to_str(db),
        );
        false
    });

    candidates
}

/// Resolves one component relative to the candidate's current package.
fn resolve_component(
    context: &ResolverContext,
    candidate: &mut ModuleResolutionCandidate,
    module_name: &str,
    file_filter: ComponentFileFilter,
) -> Result<(), ()> {
    if matches!(candidate.module, ResolvedModule::Module(_)) {
        tracing::trace!(
            "Non-package module {} cannot have a child",
            candidate.to_str(context.db)
        );
        return Err(());
    }

    if !candidate_may_exist(context, candidate, module_name) {
        return Err(());
    }

    let package_path = &mut candidate.path;
    package_path.push(module_name);

    // Check for a regular package first (highest priority)
    package_path.push("__init__");
    if let Some(init) = resolve_file_module_with_filter(package_path, context, file_filter) {
        // Remove the `__init__` component for any potential next step
        package_path.pop();
        candidate.py_typed = package_path
            .py_typed(context)
            .inherit_parent(candidate.py_typed);
        if is_legacy_namespace_package(package_path, context, init) {
            candidate.module = ResolvedModule::LegacyNamespacePackage(init);
        } else {
            candidate.module = ResolvedModule::RegularPackage(init);
        }
        return Ok(());
    }

    // Check for a file module next
    package_path.pop();

    if let Some(file_module) = resolve_file_module_with_filter(package_path, context, file_filter) {
        candidate.module = ResolvedModule::Module(file_module);
        return Ok(());
    }

    // Last resort, check if a folder with the given name exists. If so,
    // then this is a namespace package. We need to skip this check for
    // typeshed because the `resolve_file_module` can also return `None` if the
    // `__init__.py` exists but isn't available for the current Python version.
    // Let's assume that the `xml` module is only available on Python 3.11+ and
    // we're resolving for Python 3.10:
    //
    // * `resolve_file_module("xml/__init__.pyi")` returns `None` even though
    //   the file exists but the module isn't available for the current Python
    //   version.
    // * The check here would now return `true` because the `xml` directory
    //   exists, resulting in a false positive for a namespace package.
    //
    // Since typeshed doesn't use any namespace packages today (May 2025),
    // simply skip this check which also helps performance. If typeshed
    // ever uses namespace packages, ensure that this check also takes the
    // `VERSIONS` file into consideration.
    // A namespace package is not backed by a file, so it cannot satisfy a stub-only lookup.
    if file_filter != ComponentFileFilter::StubOnly
        && !package_path.search_path().is_standard_library()
        && package_path.is_directory(context)
    {
        candidate.py_typed = package_path
            .py_typed(context)
            .inherit_parent(candidate.py_typed);
        candidate.module = ResolvedModule::NamespacePackage;
        return Ok(());
    }

    Err(())
}

/// Uses the parent directory's entries to reject candidates that cannot exist without performing
/// individual file-system probes for every supported module layout.
fn candidate_may_exist(
    context: &ResolverContext,
    candidate: &ModuleResolutionCandidate,
    module_name: &str,
) -> bool {
    let Some(parent) = candidate.path.to_system_path() else {
        return true;
    };

    let Ok(listing) = directory_listing(context.db, &parent) else {
        return false;
    };

    // Other suffixes are harmless false positives; the normal probes still determine whether the
    // module exists.
    listing.contains_name_with_prefix(module_name)
}

type ResolvedNames = Vec<ModuleResolutionCandidate>;

/// If `module` exists on disk with an extension permitted by the resolver's mode, return its
/// [`File`].
///
/// Typing resolution prefers `.pyi` over `.py`; runtime resolution only considers `.py`.
pub(super) fn resolve_file_module(
    module: &ModulePath,
    resolver_state: &ResolverContext,
) -> Option<File> {
    resolve_file_module_with_filter(module, resolver_state, ComponentFileFilter::ByMode)
}

fn resolve_file_module_with_filter(
    module: &ModulePath,
    resolver_state: &ResolverContext,
    filter: ComponentFileFilter,
) -> Option<File> {
    let stub_file = if resolver_state.mode.is_typing() {
        module.with_pyi_extension().to_file(resolver_state)
    } else {
        None
    };
    if filter == ComponentFileFilter::StubOnly {
        return stub_file;
    }

    stub_file.or_else(|| {
        module
            .with_py_extension()
            .and_then(|path| path.to_file(resolver_state))
    })
}

/// Determines whether a package is a legacy namespace package.
///
/// Before PEP 420 introduced implicit namespace packages, the ecosystem developed
/// its own form of namespace packages. These legacy namespace packages continue to persist
/// in modern codebases because they work with ancient Pythons and if it ain't broke, don't fix it.
///
/// A legacy namespace package is distinguished by having an `__init__.py` that contains an
/// expression to the effect of:
///
/// ```python
/// __path__ = __import__("pkgutil").extend_path(__path__, __name__)
/// ```
///
/// The resulting package simultaneously has properties of both regular packages and namespace ones:
///
/// * Like regular packages, `__init__.py` is defined and can contain items other than submodules
/// * Like implicit namespace packages, multiple copies of the package may exist with different
///   submodules, and they will be merged into one namespace at runtime by the interpreter
///
/// Now, you may rightly wonder: "What if the `__init__.py` files have different contents?"
/// The apparent official answer is: "Don't do that!"
/// And the reality is: "Of course people do that!"
///
/// In practice we think it's fine to, just like with regular packages, use the first one
/// we find on the search paths. To the extent that the different copies "need" to have the same
/// contents, they all "need" to have the legacy namespace idiom (we do nothing to enforce that,
/// we will just get confused if you mess it up).
fn is_legacy_namespace_package(
    package_path: &ModulePath,
    context: &ResolverContext,
    init: File,
) -> bool {
    // Just an optimization, the stdlib and typeshed are never legacy namespace packages
    if package_path.search_path().is_standard_library() {
        return false;
    }

    // This is all syntax-only analysis so it *could* be fooled but it's really unlikely.
    //
    // The benefit of being syntax-only is speed and avoiding circular dependencies
    // between module resolution and semantic analysis.
    //
    // The downside is if you write slightly different syntax we will fail to detect the idiom,
    // but hey, this is better than nothing!
    let parsed = ruff_db::parsed::parsed_module(
        context.db,
        PythonFile::new(
            context.db,
            init,
            context.resolver_environment.python_version(context.db),
        ),
    );
    let mut visitor = LegacyNamespacePackageVisitor::default();
    visitor.visit_body(parsed.load(context.db).suite());

    visitor.is_legacy_namespace_package
}

/// Info about the `py.typed` file for this package
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub(crate) enum PyTyped {
    /// No `py.typed` was found
    Untyped,
    /// A `py.typed` was found containing "partial"
    Partial,
    /// A `py.typed` was found (not partial)
    Full,
}

impl PyTyped {
    /// Inherit py.typed info from the parent package
    ///
    /// > This marker applies recursively: if a top-level package includes it,
    /// > all its sub-packages MUST support type checking as well.
    ///
    /// This implementation implies that once a `py.typed` is specified
    /// all child packages inherit it, so they can never become Untyped.
    /// However they can override whether that's Full or Partial by
    /// redeclaring a `py.typed` file of their own.
    fn inherit_parent(self, parent: Self) -> Self {
        if self == Self::Untyped { parent } else { self }
    }
}

pub(super) struct ResolverContext<'db> {
    pub(super) db: &'db dyn Db,
    pub(super) resolver_environment: ResolverEnvironment<'db>,
    pub(super) mode: ModuleResolveMode,
}

impl<'db> ResolverContext<'db> {
    pub(super) fn new(
        db: &'db dyn Db,
        resolver_environment: ResolverEnvironment<'db>,
        mode: ModuleResolveMode,
    ) -> Self {
        Self {
            db,
            resolver_environment,
            mode,
        }
    }

    pub(super) fn vendored(&self) -> &VendoredFileSystem {
        self.db.vendored()
    }
}

/// Detects if a module contains a statement of the form:
/// ```python
/// __path__ = pkgutil.extend_path(__path__, __name__)
/// ```
/// or
/// ```python
/// __path__ = __import__("pkgutil").extend_path(__path__, __name__)
/// ```
/// or
/// ```python
/// __import__('pkg_resources').declare_namespace(__name__)
/// ```
#[derive(Default)]
struct LegacyNamespacePackageVisitor {
    is_legacy_namespace_package: bool,
    in_body: bool,
}

impl Visitor<'_> for LegacyNamespacePackageVisitor {
    fn visit_body(&mut self, body: &[ruff_python_ast::Stmt]) {
        if self.is_legacy_namespace_package {
            return;
        }

        // Don't traverse into nested bodies.
        if self.in_body {
            return;
        }

        self.in_body = true;

        walk_body(self, body);
    }

    fn visit_stmt(&mut self, stmt: &ast::Stmt) {
        if self.is_legacy_namespace_package {
            return;
        }

        match stmt {
            // __path__ = pkgutil.extend_path(__path__, __name__)
            // __path__ = __import__("pkgutil").extend_path(__path__, __name__)
            ast::Stmt::Assign(ast::StmtAssign { value, targets, .. }) => {
                self.check_pkgutil_extend_path(targets, value);
            }
            // __import__('pkg_resources').declare_namespace(__name__)
            ast::Stmt::Expr(ast::StmtExpr { value, .. }) => {
                self.check_pkg_resources_declare_namespace(value);
            }
            _ => {}
        }
    }
}

impl LegacyNamespacePackageVisitor {
    /// Check for `__path__ = pkgutil.extend_path(__path__, __name__)` or
    /// `__path__ = __import__("pkgutil").extend_path(__path__, __name__)`
    fn check_pkgutil_extend_path(&mut self, targets: &[ast::Expr], value: &ast::Expr) {
        let [ast::Expr::Name(maybe_path)] = targets else {
            return;
        };

        if &*maybe_path.id != "__path__" {
            return;
        }

        let ast::Expr::Call(ast::ExprCall {
            func: extend_func,
            arguments: extend_arguments,
            ..
        }) = value
        else {
            return;
        };

        let ast::Expr::Attribute(ast::ExprAttribute {
            value: maybe_pkg_util,
            attr: maybe_extend_path,
            ..
        }) = &**extend_func
        else {
            return;
        };

        // Match if the left side of the attribute access is either `__import__("pkgutil")` or `pkgutil`
        match &**maybe_pkg_util {
            // __import__("pkgutil").extend_path(__path__, __name__)
            ast::Expr::Call(ruff_python_ast::ExprCall {
                func: maybe_import,
                arguments: import_arguments,
                ..
            }) => {
                let ast::Expr::Name(maybe_import) = &**maybe_import else {
                    return;
                };

                if maybe_import.id() != "__import__" {
                    return;
                }

                let Some(ast::Expr::StringLiteral(name)) =
                    import_arguments.find_argument_value("name", 0)
                else {
                    return;
                };

                if name.value.to_str() != "pkgutil" {
                    return;
                }
            }
            // "pkgutil.extend_path(__path__, __name__)"
            ast::Expr::Name(name) => {
                if name.id() != "pkgutil" {
                    return;
                }
            }
            _ => {
                return;
            }
        }

        // Test that this is an `extend_path(__path__, __name__)` call
        if maybe_extend_path != "extend_path" {
            return;
        }

        let Some(ast::Expr::Name(path)) = extend_arguments.find_argument_value("path", 0) else {
            return;
        };
        let Some(ast::Expr::Name(name)) = extend_arguments.find_argument_value("name", 1) else {
            return;
        };

        self.is_legacy_namespace_package = path.id() == "__path__" && name.id() == "__name__";
    }

    /// Check for `__import__('pkg_resources').declare_namespace(__name__)`
    fn check_pkg_resources_declare_namespace(&mut self, value: &ast::Expr) {
        let ast::Expr::Call(ast::ExprCall {
            func,
            arguments: declare_arguments,
            ..
        }) = value
        else {
            return;
        };

        let ast::Expr::Attribute(ast::ExprAttribute {
            value: maybe_pkg_resources,
            attr: maybe_declare_namespace,
            ..
        }) = &**func
        else {
            return;
        };

        if maybe_declare_namespace != "declare_namespace" {
            return;
        }

        // Match `__import__("pkg_resources")`
        let ast::Expr::Call(ast::ExprCall {
            func: maybe_import,
            arguments: import_arguments,
            ..
        }) = &**maybe_pkg_resources
        else {
            return;
        };

        let ast::Expr::Name(maybe_import) = &**maybe_import else {
            return;
        };

        if maybe_import.id() != "__import__" {
            return;
        }

        let Some(ast::Expr::StringLiteral(name)) = import_arguments.find_argument_value("name", 0)
        else {
            return;
        };

        if name.value.to_str() != "pkg_resources" {
            return;
        }

        // Check that the argument is `__name__`
        let Some(ast::Expr::Name(name_arg)) = declare_arguments.find_argument_value("name", 0)
        else {
            return;
        };

        self.is_legacy_namespace_package = name_arg.id() == "__name__";
    }
}

#[cfg(test)]
mod tests {
    #![expect(
        clippy::disallowed_methods,
        reason = "These are tests, so it's fine to do I/O by-passing System."
    )]
    use ruff_db::Db;
    use ruff_db::files::{File, FilePath, system_path_to_file};
    use ruff_db::system::{DbWithTestSystem as _, DbWithWritableSystem as _};
    use ruff_db::testing::assert_function_query_was_not_run;
    use ruff_python_ast::PythonVersion;

    use crate::db::tests::TestDb;
    use crate::module::ModuleKind;
    use crate::module_name::ModuleName;
    use crate::strategy::FallibleStrategy;
    use crate::testing::{FileSpec, MockedTypeshed, TestCase, TestCaseBuilder};

    use super::*;

    fn resolve_module_confident<'db>(
        db: &'db TestDb,
        module_name: &ModuleName,
    ) -> Option<Module<'db>> {
        super::resolve_module_confident(db, db.resolver_environment(), module_name)
    }

    fn resolve_real_module_confident<'db>(
        db: &'db TestDb,
        module_name: &ModuleName,
    ) -> Option<Module<'db>> {
        super::resolve_real_module_confident(db, db.resolver_environment(), module_name)
    }

    fn path_to_module<'db>(db: &'db TestDb, path: &FilePath) -> Option<Module<'db>> {
        super::path_to_module(db, db.resolver_environment(), path)
    }

    #[test]
    fn first_party_module() {
        let TestCase { db, src, .. } = TestCaseBuilder::new()
            .with_src_files(&[("foo.py", "print('Hello, world!')")])
            .build();

        let foo_module_name = ModuleName::new_static("foo").unwrap();
        let foo_module = resolve_module_confident(&db, &foo_module_name).unwrap();

        assert_eq!(
            Some(&foo_module),
            resolve_module_confident(&db, &foo_module_name).as_ref()
        );

        assert_eq!("foo", foo_module.name(&db));
        assert_eq!(&src, foo_module.search_path(&db).unwrap());
        assert_eq!(ModuleKind::Module, foo_module.kind(&db));

        let expected_foo_path = src.join("foo.py");
        assert_eq!(&expected_foo_path, foo_module.file(&db).unwrap().path(&db));
        assert_eq!(
            Some(foo_module),
            path_to_module(&db, &FilePath::from(expected_foo_path))
        );
    }

    #[test]
    fn site_packages_stub_overrides_first_party_package_when_stdlib_is_missing() {
        let TestCase {
            db, site_packages, ..
        } = TestCaseBuilder::new()
            .with_src_files(&[("foo/__init__.py", "")])
            .with_site_packages_files(&[("foo-stubs/__init__.pyi", "")])
            .build();

        let foo = resolve_module_confident(&db, &ModuleName::new_static("foo").unwrap()).unwrap();
        assert_eq!(
            foo.file(&db).unwrap().path(&db),
            &site_packages.join("foo-stubs/__init__.pyi")
        );
    }

    #[test]
    fn first_party_stub_package_precedes_stdlib() {
        const TYPESHED: MockedTypeshed = MockedTypeshed {
            stdlib_files: &[("foo.pyi", "")],
            versions: "foo: 3.8-",
        };

        let TestCase { db, src, .. } = TestCaseBuilder::new()
            .with_mocked_typeshed(TYPESHED)
            .with_src_files(&[("foo-stubs/__init__.pyi", "")])
            .build();

        let foo = resolve_module_confident(&db, &ModuleName::new_static("foo").unwrap()).unwrap();
        assert_eq!(
            foo.file(&db).unwrap().path(&db),
            &src.join("foo-stubs/__init__.pyi")
        );
    }

    #[test]
    fn desperate_resolution_finds_stub_package() {
        let TestCase { db, src, .. } = TestCaseBuilder::new()
            .with_src_files(&[
                ("nested/main.py", ""),
                ("nested/foo/__init__.py", ""),
                ("nested/foo-stubs/__init__.pyi", ""),
            ])
            .build();
        let importing_file = system_path_to_file(&db, src.join("nested/main.py")).unwrap();

        let foo = resolve_module(
            &db,
            ImportingFile::File(importing_file, db.resolver_environment()),
            &ModuleName::new_static("foo").unwrap(),
        )
        .unwrap();
        assert_eq!(
            foo.file(&db).unwrap().path(&db),
            &src.join("nested/foo-stubs/__init__.pyi")
        );
    }

    #[test]
    fn missing_modules_do_not_create_file_inputs() {
        let TestCase { db, src, .. } = TestCaseBuilder::new()
            .with_src_files(&[("other.py", ""), ("package/__init__.py", "")])
            .build();

        for name in ["missing", "package.missing"] {
            assert!(
                resolve_module_confident(&db, &ModuleName::new_static(name).unwrap()).is_none()
            );
        }

        for relative_path in [
            "missing-stubs/__init__.pyi",
            "missing-stubs/__init__.py",
            "missing/__init__.pyi",
            "missing/__init__.py",
            "missing.pyi",
            "missing.py",
            "package/missing/__init__.pyi",
            "package/missing/__init__.py",
            "package/missing.pyi",
            "package/missing.py",
        ] {
            assert_eq!(
                db.files().try_system(&db, &src.join(relative_path)),
                None,
                "unexpected point probe for {relative_path}"
            );
        }
    }

    #[test]
    fn stdlib_precedes_stub_package_in_site_packages() {
        const TYPESHED: MockedTypeshed = MockedTypeshed {
            stdlib_files: &[("foo.pyi", "")],
            versions: "foo: 3.8-",
        };

        let TestCase { db, stdlib, .. } = TestCaseBuilder::new()
            .with_mocked_typeshed(TYPESHED)
            .with_site_packages_files(&[("foo-stubs/__init__.pyi", "")])
            .build();

        let foo = resolve_module_confident(&db, &ModuleName::new_static("foo").unwrap()).unwrap();
        assert_eq!(foo.file(&db).unwrap().path(&db), &stdlib.join("foo.pyi"));
    }

    #[test]
    fn stubs_over_module_source() {
        let TestCase { db, src, .. } = TestCaseBuilder::new()
            .with_src_files(&[("foo.py", ""), ("foo.pyi", "")])
            .build();

        let foo_module_name = ModuleName::new_static("foo").unwrap();
        let foo_module = resolve_module_confident(&db, &foo_module_name).unwrap();

        assert_eq!(
            Some(&foo_module),
            resolve_module_confident(&db, &foo_module_name).as_ref()
        );

        assert_eq!("foo", foo_module.name(&db));
        assert_eq!(&src, foo_module.search_path(&db).unwrap());
        assert_eq!(ModuleKind::Module, foo_module.kind(&db));

        let expected_foo_path = src.join("foo.pyi");
        assert_eq!(&expected_foo_path, foo_module.file(&db).unwrap().path(&db));
        assert_eq!(
            Some(foo_module),
            path_to_module(&db, &FilePath::from(expected_foo_path))
        );
    }

    /// Tests precedence when there is a package and a sibling stub file.
    ///
    /// NOTE: I am unsure if this is correct. I wrote this test to match
    /// behavior while implementing "list modules." Notably, in this case, the
    /// regular source file gets priority. But in `stubs_over_module_source`
    /// above, the stub file gets priority.
    #[test]
    fn stubs_over_package_source() {
        let TestCase { db, src, .. } = TestCaseBuilder::new()
            .with_src_files(&[("foo/__init__.py", ""), ("foo.pyi", "")])
            .build();

        let foo_module_name = ModuleName::new_static("foo").unwrap();
        let foo_module = resolve_module_confident(&db, &foo_module_name).unwrap();

        assert_eq!(
            Some(&foo_module),
            resolve_module_confident(&db, &foo_module_name).as_ref()
        );

        assert_eq!("foo", foo_module.name(&db));
        assert_eq!(&src, foo_module.search_path(&db).unwrap());
        assert_eq!(ModuleKind::Package, foo_module.kind(&db));

        let expected_foo_path = src.join("foo/__init__.py");
        assert_eq!(&expected_foo_path, foo_module.file(&db).unwrap().path(&db));
        assert_eq!(
            Some(foo_module),
            path_to_module(&db, &FilePath::from(expected_foo_path))
        );
    }

    #[test]
    fn builtins_vendored() {
        let TestCase { db, stdlib, .. } = TestCaseBuilder::new()
            .with_vendored_typeshed()
            .with_src_files(&[("builtins.py", "FOOOO = 42")])
            .build();

        let builtins_module_name = ModuleName::new_static("builtins").unwrap();
        let builtins =
            resolve_module_confident(&db, &builtins_module_name).expect("builtins to resolve");

        assert_eq!(
            builtins.file(&db).unwrap().path(&db),
            &stdlib.join("builtins.pyi")
        );
    }

    #[test]
    fn builtins_custom() {
        const TYPESHED: MockedTypeshed = MockedTypeshed {
            stdlib_files: &[("builtins.pyi", "def min(a, b): ...")],
            versions: "builtins: 3.8-",
        };

        const SRC: &[FileSpec] = &[("builtins.py", "FOOOO = 42")];

        let TestCase { db, stdlib, .. } = TestCaseBuilder::new()
            .with_src_files(SRC)
            .with_mocked_typeshed(TYPESHED)
            .with_python_version(PythonVersion::PY38)
            .build();

        let builtins_module_name = ModuleName::new_static("builtins").unwrap();
        let builtins =
            resolve_module_confident(&db, &builtins_module_name).expect("builtins to resolve");

        assert_eq!(
            builtins.file(&db).unwrap().path(&db),
            &stdlib.join("builtins.pyi")
        );
    }

    #[test]
    fn stdlib() {
        const TYPESHED: MockedTypeshed = MockedTypeshed {
            stdlib_files: &[("functools.pyi", "def update_wrapper(): ...")],
            versions: "functools: 3.8-",
        };

        let TestCase { db, stdlib, .. } = TestCaseBuilder::new()
            .with_mocked_typeshed(TYPESHED)
            .with_python_version(PythonVersion::PY38)
            .build();

        let functools_module_name = ModuleName::new_static("functools").unwrap();
        let functools_module = resolve_module_confident(&db, &functools_module_name).unwrap();

        assert_eq!(
            Some(&functools_module),
            resolve_module_confident(&db, &functools_module_name).as_ref()
        );

        assert_eq!(&stdlib, functools_module.search_path(&db).unwrap());
        assert_eq!(ModuleKind::Module, functools_module.kind(&db));

        let expected_functools_path = stdlib.join("functools.pyi");
        assert_eq!(
            &expected_functools_path,
            functools_module.file(&db).unwrap().path(&db)
        );

        assert_eq!(
            Some(functools_module),
            path_to_module(&db, &FilePath::from(expected_functools_path))
        );
    }

    fn create_module_names(raw_names: &[&str]) -> Vec<ModuleName> {
        raw_names
            .iter()
            .map(|raw| ModuleName::new(raw).unwrap())
            .collect()
    }

    #[test]
    fn resolve_module_uses_resolver_environment_python_version() {
        const TYPESHED: MockedTypeshed = MockedTypeshed {
            stdlib_files: &[("_sha256.pyi", ""), ("py312_only.pyi", "")],
            versions: "_sha256: 3.11-\npy312_only: 3.12-",
        };

        let TestCase {
            db, src, stdlib, ..
        } = TestCaseBuilder::new()
            .with_src_files(&[
                ("main.py", ""),
                ("_sha256.py", ""),
                ("namespace/module.py", ""),
            ])
            .with_mocked_typeshed(TYPESHED)
            .with_python_version(PythonVersion::PY311)
            .build();
        let importing_file = system_path_to_file(&db, src.join("main.py")).unwrap();
        let py311 = ResolverEnvironment::new(&db, PythonVersion::PY311, db.search_paths());
        let py312 = ResolverEnvironment::new(&db, PythonVersion::PY312, db.search_paths());
        let sha256 = ModuleName::new_static("_sha256").unwrap();
        let py311_module =
            resolve_module(&db, ImportingFile::File(importing_file, py311), &sha256).unwrap();
        let py312_module =
            resolve_module(&db, ImportingFile::File(importing_file, py312), &sha256).unwrap();
        assert_eq!(
            py311_module.file(&db).unwrap().path(&db),
            &stdlib.join("_sha256.pyi")
        );
        assert_eq!(
            py312_module.file(&db).unwrap().path(&db),
            &src.join("_sha256.py")
        );
        assert_eq!(py311_module.python_version(&db), PythonVersion::PY311);
        assert_eq!(py312_module.python_version(&db), PythonVersion::PY312);

        let namespace = ModuleName::new_static("namespace").unwrap();
        let py311_namespace =
            resolve_module(&db, ImportingFile::File(importing_file, py311), &namespace).unwrap();
        let py312_namespace =
            resolve_module(&db, ImportingFile::File(importing_file, py312), &namespace).unwrap();
        assert!(matches!(py311_namespace, Module::Namespace(_)));
        assert!(matches!(py312_namespace, Module::Namespace(_)));
        assert_eq!(py311_namespace.python_version(&db), PythonVersion::PY311);
        assert_eq!(py312_namespace.python_version(&db), PythonVersion::PY312);
        assert_ne!(py311_namespace, py312_namespace);

        let py312_only = ModuleName::new_static("py312_only").unwrap();
        assert!(
            resolve_module(&db, ImportingFile::File(importing_file, py311), &py312_only).is_none()
        );
        assert_eq!(
            resolve_module(&db, ImportingFile::File(importing_file, py312), &py312_only)
                .and_then(|module| module.file(&db))
                .unwrap()
                .path(&db),
            &stdlib.join("py312_only.pyi")
        );
    }

    #[test]
    fn resolve_module_uses_resolver_environment_search_paths() {
        let TestCase { mut db, src, .. } = TestCaseBuilder::new()
            .with_src_files(&[("main.py", ""), ("shared.py", "from_src = True")])
            .with_vendored_typeshed()
            .build();
        db.write_file("/alternate/shared.py", "from_alternate = True")
            .unwrap();

        let alternate_paths = SearchPathSettings {
            src_roots: vec![SystemPathBuf::from("/alternate")],
            ..SearchPathSettings::empty()
        }
        .to_search_paths(db.system(), db.vendored(), &FallibleStrategy)
        .unwrap();
        alternate_paths.try_register_static_roots(&db);

        let primary = db.resolver_environment();
        let alternate = ResolverEnvironment::new(&db, PythonVersion::default(), &alternate_paths);
        let importing_file = system_path_to_file(&db, src.join("main.py")).unwrap();
        let name = ModuleName::new_static("shared").unwrap();

        let primary_module =
            resolve_module(&db, ImportingFile::File(importing_file, primary), &name).unwrap();
        let alternate_module =
            resolve_module(&db, ImportingFile::File(importing_file, alternate), &name).unwrap();

        assert_eq!(
            primary_module.file(&db).unwrap().path(&db),
            &src.join("shared.py")
        );
        assert_eq!(
            alternate_module.file(&db).unwrap().path(&db),
            &SystemPathBuf::from("/alternate/shared.py")
        );
        assert_ne!(primary_module, alternate_module);
    }

    #[test]
    fn stdlib_resolution_respects_versions_file_py38_existing_modules() {
        const VERSIONS: &str = "\
            asyncio: 3.8-               # 'Regular' package on py38+
            asyncio.tasks: 3.9-3.11     # Submodule on py39+ only
            functools: 3.8-             # Top-level single-file module
        ";

        const STDLIB: &[FileSpec] = &[
            ("asyncio/__init__.pyi", ""),
            ("asyncio/tasks.pyi", ""),
            ("functools.pyi", ""),
        ];

        const TYPESHED: MockedTypeshed = MockedTypeshed {
            stdlib_files: STDLIB,
            versions: VERSIONS,
        };

        let TestCase { db, stdlib, .. } = TestCaseBuilder::new()
            .with_mocked_typeshed(TYPESHED)
            .with_python_version(PythonVersion::PY38)
            .build();

        let existing_modules = create_module_names(&["asyncio", "functools"]);
        for module_name in existing_modules {
            let resolved_module =
                resolve_module_confident(&db, &module_name).unwrap_or_else(|| {
                    panic!("Expected module {module_name} to exist in the mock stdlib")
                });
            let search_path = resolved_module.search_path(&db).unwrap();
            assert_eq!(
                &stdlib, search_path,
                "Search path for {module_name} was unexpectedly {search_path:?}"
            );
            assert!(
                search_path.is_standard_library(),
                "Expected a stdlib search path, but got {search_path:?}"
            );
        }
    }

    #[test]
    fn stdlib_resolution_respects_versions_file_py38_nonexisting_modules() {
        const VERSIONS: &str = "\
            asyncio: 3.8-               # 'Regular' package on py38+
            asyncio.tasks: 3.9-3.11     # Submodule on py39+ only
            collections: 3.9-           # 'Regular' package on py39+
        ";

        const STDLIB: &[FileSpec] = &[
            ("collections/__init__.pyi", ""),
            ("asyncio/__init__.pyi", ""),
            ("asyncio/tasks.pyi", ""),
        ];

        const TYPESHED: MockedTypeshed = MockedTypeshed {
            stdlib_files: STDLIB,
            versions: VERSIONS,
        };

        let TestCase { db, .. } = TestCaseBuilder::new()
            .with_mocked_typeshed(TYPESHED)
            .with_python_version(PythonVersion::PY38)
            .build();

        let nonexisting_modules = create_module_names(&["collections", "asyncio.tasks"]);

        for module_name in nonexisting_modules {
            assert!(
                resolve_module_confident(&db, &module_name).is_none(),
                "Unexpectedly resolved a module for {module_name}"
            );
        }
    }

    #[test]
    fn stdlib_resolution_respects_versions_file_py39_existing_modules() {
        const VERSIONS: &str = "\
            asyncio: 3.8-               # 'Regular' package on py38+
            asyncio.tasks: 3.9-3.11     # Submodule on py39+ only
            collections: 3.9-           # 'Regular' package on py39+
            functools: 3.8-             # Top-level single-file module
        ";

        const STDLIB: &[FileSpec] = &[
            ("asyncio/__init__.pyi", ""),
            ("asyncio/tasks.pyi", ""),
            ("collections/__init__.pyi", ""),
            ("functools.pyi", ""),
        ];

        const TYPESHED: MockedTypeshed = MockedTypeshed {
            stdlib_files: STDLIB,
            versions: VERSIONS,
        };

        let TestCase { db, stdlib, .. } = TestCaseBuilder::new()
            .with_mocked_typeshed(TYPESHED)
            .with_python_version(PythonVersion::PY39)
            .build();

        let existing_modules =
            create_module_names(&["asyncio", "functools", "collections", "asyncio.tasks"]);

        for module_name in existing_modules {
            let resolved_module =
                resolve_module_confident(&db, &module_name).unwrap_or_else(|| {
                    panic!("Expected module {module_name} to exist in the mock stdlib")
                });
            let search_path = resolved_module.search_path(&db).unwrap();
            assert_eq!(
                &stdlib, search_path,
                "Search path for {module_name} was unexpectedly {search_path:?}"
            );
            assert!(
                search_path.is_standard_library(),
                "Expected a stdlib search path, but got {search_path:?}"
            );
        }
    }
    #[test]
    fn stdlib_resolution_respects_versions_file_py39_nonexisting_modules() {
        const VERSIONS: &str = "\
            importlib: 3.9-   # Namespace package on py39+
            xml: 3.8-3.8      # Namespace package on 3.8 only
        ";

        const STDLIB: &[FileSpec] = &[("importlib/abc.pyi", ""), ("xml/etree.pyi", "")];

        const TYPESHED: MockedTypeshed = MockedTypeshed {
            stdlib_files: STDLIB,
            versions: VERSIONS,
        };

        let TestCase { db, .. } = TestCaseBuilder::new()
            .with_mocked_typeshed(TYPESHED)
            .with_python_version(PythonVersion::PY39)
            .build();

        let nonexisting_modules = create_module_names(&["importlib", "xml", "xml.etree"]);
        for module_name in nonexisting_modules {
            assert!(
                resolve_module_confident(&db, &module_name).is_none(),
                "Unexpectedly resolved a module for {module_name}"
            );
        }
    }

    #[test]
    fn first_party_precedence_over_stdlib() {
        const SRC: &[FileSpec] = &[("functools.py", "def update_wrapper(): ...")];

        const TYPESHED: MockedTypeshed = MockedTypeshed {
            stdlib_files: &[("functools.pyi", "def update_wrapper(): ...")],
            versions: "functools: 3.8-",
        };

        let TestCase { db, src, .. } = TestCaseBuilder::new()
            .with_src_files(SRC)
            .with_mocked_typeshed(TYPESHED)
            .with_python_version(PythonVersion::PY38)
            .build();

        let functools_module_name = ModuleName::new_static("functools").unwrap();
        let functools_module = resolve_module_confident(&db, &functools_module_name).unwrap();

        assert_eq!(
            Some(&functools_module),
            resolve_module_confident(&db, &functools_module_name).as_ref()
        );
        assert_eq!(&src, functools_module.search_path(&db).unwrap());
        assert_eq!(ModuleKind::Module, functools_module.kind(&db));
        assert_eq!(
            &src.join("functools.py"),
            functools_module.file(&db).unwrap().path(&db)
        );

        assert_eq!(
            Some(functools_module),
            path_to_module(&db, &FilePath::from(src.join("functools.py")))
        );
    }

    #[test]
    fn stdlib_uses_vendored_typeshed_when_no_custom_typeshed_supplied() {
        let TestCase { db, stdlib, .. } = TestCaseBuilder::new()
            .with_vendored_typeshed()
            .with_python_version(PythonVersion::default())
            .build();

        let pydoc_data_topics_name = ModuleName::new_static("pydoc_data.topics").unwrap();
        let pydoc_data_topics = resolve_module_confident(&db, &pydoc_data_topics_name).unwrap();

        assert_eq!("pydoc_data.topics", pydoc_data_topics.name(&db));
        assert_eq!(pydoc_data_topics.search_path(&db).unwrap(), &stdlib);
        assert_eq!(
            pydoc_data_topics.file(&db).unwrap().path(&db),
            &stdlib.join("pydoc_data/topics.pyi")
        );
    }

    #[test]
    fn resolve_package() {
        let TestCase { src, db, .. } = TestCaseBuilder::new()
            .with_src_files(&[("foo/__init__.py", "print('Hello, world!'")])
            .build();

        let foo_path = src.join("foo/__init__.py");
        let foo_module =
            resolve_module_confident(&db, &ModuleName::new_static("foo").unwrap()).unwrap();

        assert_eq!("foo", foo_module.name(&db));
        assert_eq!(&src, foo_module.search_path(&db).unwrap());
        assert_eq!(&foo_path, foo_module.file(&db).unwrap().path(&db));

        assert_eq!(
            Some(&foo_module),
            path_to_module(&db, &FilePath::from(foo_path)).as_ref()
        );

        // Resolving by directory doesn't resolve to the init file.
        assert_eq!(None, path_to_module(&db, &FilePath::from(src.join("foo"))));
    }

    #[test]
    fn package_priority_over_module() {
        const SRC: &[FileSpec] = &[
            ("foo/__init__.py", "print('Hello, world!')"),
            ("foo.py", "print('Hello, world!')"),
        ];

        let TestCase { db, src, .. } = TestCaseBuilder::new().with_src_files(SRC).build();

        let foo_module =
            resolve_module_confident(&db, &ModuleName::new_static("foo").unwrap()).unwrap();
        let foo_init_path = src.join("foo/__init__.py");

        assert_eq!(&src, foo_module.search_path(&db).unwrap());
        assert_eq!(&foo_init_path, foo_module.file(&db).unwrap().path(&db));
        assert_eq!(ModuleKind::Package, foo_module.kind(&db));

        assert_eq!(
            Some(foo_module),
            path_to_module(&db, &FilePath::from(foo_init_path))
        );
        assert_eq!(
            None,
            path_to_module(&db, &FilePath::from(src.join("foo.py")))
        );
    }

    #[test]
    fn typing_stub_over_module() {
        const SRC: &[FileSpec] = &[("foo.py", "print('Hello, world!')"), ("foo.pyi", "x: int")];

        let TestCase { db, src, .. } = TestCaseBuilder::new().with_src_files(SRC).build();

        let foo = resolve_module_confident(&db, &ModuleName::new_static("foo").unwrap()).unwrap();
        let foo_real =
            resolve_real_module_confident(&db, &ModuleName::new_static("foo").unwrap()).unwrap();
        let foo_stub = src.join("foo.pyi");

        assert_eq!(&src, foo.search_path(&db).unwrap());
        assert_eq!(&foo_stub, foo.file(&db).unwrap().path(&db));

        assert_eq!(Some(foo), path_to_module(&db, &FilePath::from(foo_stub)));
        assert_eq!(
            Some(foo_real),
            path_to_module(&db, &FilePath::from(src.join("foo.py")))
        );
        assert_ne!(foo_real, foo);
    }

    #[test]
    fn sub_packages() {
        const SRC: &[FileSpec] = &[
            ("foo/__init__.py", ""),
            ("foo/bar/__init__.py", ""),
            ("foo/bar/baz.py", "print('Hello, world!)'"),
        ];

        let TestCase { db, src, .. } = TestCaseBuilder::new().with_src_files(SRC).build();

        let baz_module =
            resolve_module_confident(&db, &ModuleName::new_static("foo.bar.baz").unwrap()).unwrap();
        let baz_path = src.join("foo/bar/baz.py");

        assert_eq!(&src, baz_module.search_path(&db).unwrap());
        assert_eq!(&baz_path, baz_module.file(&db).unwrap().path(&db));

        assert_eq!(
            Some(baz_module),
            path_to_module(&db, &FilePath::from(baz_path))
        );
    }

    #[test]
    fn module_search_path_priority() {
        let TestCase {
            db,
            src,
            site_packages,
            ..
        } = TestCaseBuilder::new()
            .with_src_files(&[("foo.py", "")])
            .with_site_packages_files(&[("foo.py", "")])
            .build();

        let foo_module =
            resolve_module_confident(&db, &ModuleName::new_static("foo").unwrap()).unwrap();
        let foo_src_path = src.join("foo.py");

        assert_eq!(&src, foo_module.search_path(&db).unwrap());
        assert_eq!(&foo_src_path, foo_module.file(&db).unwrap().path(&db));
        assert_eq!(
            Some(foo_module),
            path_to_module(&db, &FilePath::from(foo_src_path))
        );

        assert_eq!(
            None,
            path_to_module(&db, &FilePath::from(site_packages.join("foo.py")))
        );
    }

    #[test]
    #[cfg(target_family = "unix")]
    fn symlink() -> anyhow::Result<()> {
        use anyhow::Context;
        use ruff_db::system::{OsSystem, SystemPath};

        use crate::db::tests::TestDb;

        let mut db = TestDb::new().with_python_version(PythonVersion::PY38);

        let temp_dir = tempfile::tempdir()?;
        let root = temp_dir
            .path()
            .canonicalize()
            .context("Failed to canonicalize temp dir")?;
        let root = SystemPath::from_std_path(&root).unwrap();
        db.use_system(OsSystem::new(root));

        let src = root.join("src");
        let site_packages = root.join("site-packages");
        let custom_typeshed = root.join("typeshed");

        let foo = src.join("foo.py");
        let bar = src.join("bar.py");

        std::fs::create_dir_all(src.as_std_path())?;
        std::fs::create_dir_all(site_packages.as_std_path())?;
        std::fs::create_dir_all(custom_typeshed.join("stdlib").as_std_path())?;
        std::fs::File::create(custom_typeshed.join("stdlib/VERSIONS").as_std_path())?;

        std::fs::write(foo.as_std_path(), "")?;
        std::os::unix::fs::symlink(foo.as_std_path(), bar.as_std_path())?;

        db.set_search_paths(
            SearchPathSettings {
                src_roots: vec![src.clone()],
                custom_typeshed: Some(custom_typeshed),
                site_packages_paths: vec![site_packages],
                ..SearchPathSettings::empty()
            }
            .to_search_paths(db.system(), db.vendored(), &FallibleStrategy)
            .expect("Valid search path settings"),
        );

        let foo_module =
            resolve_module_confident(&db, &ModuleName::new_static("foo").unwrap()).unwrap();
        let bar_module =
            resolve_module_confident(&db, &ModuleName::new_static("bar").unwrap()).unwrap();

        assert_ne!(foo_module, bar_module);

        assert_eq!(&src, foo_module.search_path(&db).unwrap());
        assert_eq!(&foo, foo_module.file(&db).unwrap().path(&db));

        // `foo` and `bar` shouldn't resolve to the same file

        assert_eq!(&src, bar_module.search_path(&db).unwrap());
        assert_eq!(&bar, bar_module.file(&db).unwrap().path(&db));
        assert_eq!(&foo, foo_module.file(&db).unwrap().path(&db));

        assert_ne!(&foo_module, &bar_module);

        assert_eq!(Some(foo_module), path_to_module(&db, &FilePath::from(foo)));
        assert_eq!(Some(bar_module), path_to_module(&db, &FilePath::from(bar)));

        Ok(())
    }

    #[test]
    fn deleting_file_from_different_directory_doesnt_change_module_resolution() {
        let TestCase { mut db, src, .. } = TestCaseBuilder::new()
            .with_src_files(&[("foo.py", "x = 1"), ("other/bar.py", "x = 2")])
            .with_python_version(PythonVersion::PY38)
            .build();

        let foo_module_name = ModuleName::new_static("foo").unwrap();
        let foo_module = resolve_module_confident(&db, &foo_module_name).unwrap();
        let foo_pieces = (
            foo_module.name(&db).clone(),
            foo_module.file(&db),
            foo_module.known(&db),
            foo_module.search_path(&db).cloned(),
            foo_module.kind(&db),
        );

        let bar_path = src.join("other/bar.py");
        let bar = system_path_to_file(&db, &bar_path).expect("bar.py to exist");

        db.clear_salsa_events();

        // Delete `bar.py`
        db.memory_file_system().remove_file(&bar_path).unwrap();
        bar.sync(&mut db);

        // Re-query the foo module. The foo module should still be cached
        // because `bar.py` isn't relevant for resolving `foo`.

        let foo_module2 = resolve_module_confident(&db, &foo_module_name);
        let foo_pieces2 = foo_module2.map(|foo_module2| {
            (
                foo_module2.name(&db).clone(),
                foo_module2.file(&db),
                foo_module2.known(&db),
                foo_module2.search_path(&db).cloned(),
                foo_module2.kind(&db),
            )
        });

        assert!(
            !db.take_salsa_events()
                .iter()
                .any(|event| { matches!(event.kind, salsa::EventKind::WillExecute { .. }) })
        );

        assert_eq!(Some(foo_pieces), foo_pieces2);
    }

    #[test]
    fn adding_file_on_which_module_resolution_depends_invalidates_previously_failing_query_that_now_succeeds()
    -> anyhow::Result<()> {
        let TestCase { mut db, src, .. } = TestCaseBuilder::new().build();
        let foo_path = src.join("foo.py");

        let foo_module_name = ModuleName::new_static("foo").unwrap();
        assert_eq!(resolve_module_confident(&db, &foo_module_name), None);

        // Now write the foo file
        db.write_file(&foo_path, "x = 1")?;

        let foo_file = system_path_to_file(&db, &foo_path).expect("foo.py to exist");

        let foo_module =
            resolve_module_confident(&db, &foo_module_name).expect("Foo module to resolve");
        assert_eq!(foo_file, foo_module.file(&db).unwrap());

        Ok(())
    }

    #[test]
    fn removing_file_on_which_module_resolution_depends_invalidates_previously_successful_query_that_now_fails()
    -> anyhow::Result<()> {
        const SRC: &[FileSpec] = &[("foo.py", "x = 1"), ("foo/__init__.py", "x = 2")];

        let TestCase { mut db, src, .. } = TestCaseBuilder::new().with_src_files(SRC).build();

        let foo_module_name = ModuleName::new_static("foo").unwrap();
        let foo_module =
            resolve_module_confident(&db, &foo_module_name).expect("foo module to exist");
        let foo_init_path = src.join("foo/__init__.py");

        assert_eq!(&foo_init_path, foo_module.file(&db).unwrap().path(&db));

        // Delete `foo/__init__.py` and the `foo` folder. `foo` should now resolve to `foo.py`
        db.memory_file_system().remove_file(&foo_init_path)?;
        db.memory_file_system()
            .remove_directory(foo_init_path.parent().unwrap())?;
        File::sync_path(&mut db, &foo_init_path);
        File::sync_path(&mut db, foo_init_path.parent().unwrap());

        let foo_module =
            resolve_module_confident(&db, &foo_module_name).expect("Foo module to resolve");
        assert_eq!(&src.join("foo.py"), foo_module.file(&db).unwrap().path(&db));

        Ok(())
    }

    #[test]
    fn adding_file_to_search_path_with_lower_priority_does_not_invalidate_query() {
        const TYPESHED: MockedTypeshed = MockedTypeshed {
            versions: "functools: 3.8-",
            stdlib_files: &[("functools.pyi", "def update_wrapper(): ...")],
        };

        let TestCase {
            mut db,
            stdlib,
            site_packages,
            ..
        } = TestCaseBuilder::new()
            .with_mocked_typeshed(TYPESHED)
            .with_python_version(PythonVersion::PY38)
            .build();

        let functools_module_name = ModuleName::new_static("functools").unwrap();
        let stdlib_functools_path = stdlib.join("functools.pyi");

        let functools_module = resolve_module_confident(&db, &functools_module_name).unwrap();
        assert_eq!(functools_module.search_path(&db).unwrap(), &stdlib);
        assert_eq!(
            Ok(functools_module.file(&db).unwrap()),
            system_path_to_file(&db, &stdlib_functools_path)
        );

        // Adding a file to site-packages does not invalidate the query,
        // since site-packages takes lower priority in the module resolution
        db.clear_salsa_events();
        let site_packages_functools_path = site_packages.join("functools.py");
        db.write_file(&site_packages_functools_path, "f: int")
            .unwrap();
        let functools_module = resolve_module_confident(&db, &functools_module_name).unwrap();
        let functools_file = functools_module.file(&db).unwrap();
        let functools_search_path = functools_module.search_path(&db).unwrap().clone();
        let events = db.take_salsa_events();
        assert_function_query_was_not_run(
            &db,
            resolve_module_query,
            ModuleNameIngredient::new(
                &db,
                functools_module_name,
                ModuleResolveMode::Typing,
                db.resolver_environment(),
            ),
            &events,
        );
        assert_eq!(&functools_search_path, &stdlib);
        assert_eq!(
            Ok(functools_file),
            system_path_to_file(&db, &stdlib_functools_path)
        );
    }

    #[test]
    fn adding_file_to_search_path_with_higher_priority_invalidates_the_query() {
        const TYPESHED: MockedTypeshed = MockedTypeshed {
            versions: "functools: 3.8-",
            stdlib_files: &[("functools.pyi", "def update_wrapper(): ...")],
        };

        let TestCase {
            mut db,
            stdlib,
            src,
            ..
        } = TestCaseBuilder::new()
            .with_mocked_typeshed(TYPESHED)
            .with_python_version(PythonVersion::PY38)
            .build();

        let functools_module_name = ModuleName::new_static("functools").unwrap();
        let functools_module = resolve_module_confident(&db, &functools_module_name).unwrap();
        assert_eq!(functools_module.search_path(&db).unwrap(), &stdlib);
        assert_eq!(
            Ok(functools_module.file(&db).unwrap()),
            system_path_to_file(&db, stdlib.join("functools.pyi"))
        );

        // Adding a first-party file invalidates the query,
        // since first-party files take higher priority in module resolution:
        let src_functools_path = src.join("functools.py");
        db.write_file(&src_functools_path, "FOO: int").unwrap();
        let functools_module = resolve_module_confident(&db, &functools_module_name).unwrap();
        assert_eq!(functools_module.search_path(&db).unwrap(), &src);
        assert_eq!(
            Ok(functools_module.file(&db).unwrap()),
            system_path_to_file(&db, &src_functools_path)
        );
    }

    #[test]
    fn deleting_file_from_higher_priority_search_path_invalidates_the_query() {
        const SRC: &[FileSpec] = &[("functools.py", "FOO: int")];

        const TYPESHED: MockedTypeshed = MockedTypeshed {
            versions: "functools: 3.8-",
            stdlib_files: &[("functools.pyi", "def update_wrapper(): ...")],
        };

        let TestCase {
            mut db,
            stdlib,
            src,
            ..
        } = TestCaseBuilder::new()
            .with_src_files(SRC)
            .with_mocked_typeshed(TYPESHED)
            .with_python_version(PythonVersion::PY38)
            .build();

        let functools_module_name = ModuleName::new_static("functools").unwrap();
        let src_functools_path = src.join("functools.py");

        let functools_module = resolve_module_confident(&db, &functools_module_name).unwrap();
        assert_eq!(functools_module.search_path(&db).unwrap(), &src);
        assert_eq!(
            Ok(functools_module.file(&db).unwrap()),
            system_path_to_file(&db, &src_functools_path)
        );

        // If we now delete the first-party file,
        // it should resolve to the stdlib:
        db.memory_file_system()
            .remove_file(&src_functools_path)
            .unwrap();
        File::sync_path(&mut db, &src_functools_path);
        let functools_module = resolve_module_confident(&db, &functools_module_name).unwrap();
        assert_eq!(functools_module.search_path(&db).unwrap(), &stdlib);
        assert_eq!(
            Ok(functools_module.file(&db).unwrap()),
            system_path_to_file(&db, stdlib.join("functools.pyi"))
        );
    }

    #[test]
    fn editable_install_absolute_path() {
        const SITE_PACKAGES: &[FileSpec] = &[("_foo.pth", "/x/src")];
        let x_directory = [("/x/src/foo/__init__.py", ""), ("/x/src/foo/bar.py", "")];

        let TestCase { mut db, .. } = TestCaseBuilder::new()
            .with_site_packages_files(SITE_PACKAGES)
            .build();

        db.write_files(x_directory).unwrap();

        let foo_module_name = ModuleName::new_static("foo").unwrap();
        let foo_bar_module_name = ModuleName::new_static("foo.bar").unwrap();

        let foo_module = resolve_module_confident(&db, &foo_module_name).unwrap();
        let foo_bar_module = resolve_module_confident(&db, &foo_bar_module_name).unwrap();

        assert_eq!(
            foo_module.file(&db).unwrap().path(&db),
            &FilePath::system("/x/src/foo/__init__.py")
        );
        assert_eq!(
            foo_bar_module.file(&db).unwrap().path(&db),
            &FilePath::system("/x/src/foo/bar.py")
        );
    }

    #[test]
    fn editable_install_pth_file_with_whitespace() {
        const SITE_PACKAGES: &[FileSpec] = &[
            ("_foo.pth", "        /x/src"),
            ("_bar.pth", "/y/src        "),
        ];
        let external_files = [("/x/src/foo.py", ""), ("/y/src/bar.py", "")];

        let TestCase { mut db, .. } = TestCaseBuilder::new()
            .with_site_packages_files(SITE_PACKAGES)
            .build();

        db.write_files(external_files).unwrap();

        // Lines with leading whitespace in `.pth` files do not parse:
        let foo_module_name = ModuleName::new_static("foo").unwrap();
        assert_eq!(resolve_module_confident(&db, &foo_module_name), None);

        // Lines with trailing whitespace in `.pth` files do:
        let bar_module_name = ModuleName::new_static("bar").unwrap();
        let bar_module = resolve_module_confident(&db, &bar_module_name).unwrap();
        assert_eq!(
            bar_module.file(&db).unwrap().path(&db),
            &FilePath::system("/y/src/bar.py")
        );
    }

    #[test]
    fn editable_install_relative_path() {
        const SITE_PACKAGES: &[FileSpec] = &[
            ("_foo.pth", "../../x/../x/y/src"),
            ("../x/y/src/foo.pyi", ""),
        ];

        let TestCase { db, .. } = TestCaseBuilder::new()
            .with_site_packages_files(SITE_PACKAGES)
            .build();

        let foo_module_name = ModuleName::new_static("foo").unwrap();
        let foo_module = resolve_module_confident(&db, &foo_module_name).unwrap();

        assert_eq!(
            foo_module.file(&db).unwrap().path(&db),
            &FilePath::system("/x/y/src/foo.pyi")
        );
    }

    #[test]
    fn editable_install_multiple_pth_files_with_multiple_paths() {
        const COMPLEX_PTH_FILE: &str = "\
/

# a comment
/baz

import not_an_editable_install; do_something_else_crazy_dynamic()

# another comment
spam

not_a_directory
";

        const SITE_PACKAGES: &[FileSpec] = &[
            ("_foo.pth", "../../x/../x/y/src"),
            ("_lots_of_others.pth", COMPLEX_PTH_FILE),
            ("../x/y/src/foo.pyi", ""),
            ("spam/spam.py", ""),
        ];

        let root_files = [("/a.py", ""), ("/baz/b.py", "")];

        let TestCase {
            mut db,
            site_packages,
            ..
        } = TestCaseBuilder::new()
            .with_site_packages_files(SITE_PACKAGES)
            .build();

        db.write_files(root_files).unwrap();

        let foo_module_name = ModuleName::new_static("foo").unwrap();
        let a_module_name = ModuleName::new_static("a").unwrap();
        let b_module_name = ModuleName::new_static("b").unwrap();
        let spam_module_name = ModuleName::new_static("spam").unwrap();

        let foo_module = resolve_module_confident(&db, &foo_module_name).unwrap();
        let a_module = resolve_module_confident(&db, &a_module_name).unwrap();
        let b_module = resolve_module_confident(&db, &b_module_name).unwrap();
        let spam_module = resolve_module_confident(&db, &spam_module_name).unwrap();

        assert_eq!(
            foo_module.file(&db).unwrap().path(&db),
            &FilePath::system("/x/y/src/foo.pyi")
        );
        assert_eq!(
            a_module.file(&db).unwrap().path(&db),
            &FilePath::system("/a.py")
        );
        assert_eq!(
            b_module.file(&db).unwrap().path(&db),
            &FilePath::system("/baz/b.py")
        );
        assert_eq!(
            spam_module.file(&db).unwrap().path(&db),
            &FilePath::from(site_packages.join("spam/spam.py"))
        );
    }

    #[test]
    fn module_resolution_paths_cached_between_different_module_resolutions() {
        const SITE_PACKAGES: &[FileSpec] = &[("_foo.pth", "/x/src"), ("_bar.pth", "/y/src")];
        let external_directories = [("/x/src/foo.py", ""), ("/y/src/bar.py", "")];

        let TestCase { mut db, .. } = TestCaseBuilder::new()
            .with_site_packages_files(SITE_PACKAGES)
            .build();

        db.write_files(external_directories).unwrap();

        let foo_module_name = ModuleName::new_static("foo").unwrap();
        let bar_module_name = ModuleName::new_static("bar").unwrap();

        let foo_module = resolve_module_confident(&db, &foo_module_name).unwrap();
        assert_eq!(
            foo_module.file(&db).unwrap().path(&db),
            &FilePath::system("/x/src/foo.py")
        );

        db.clear_salsa_events();
        let bar_module = resolve_module_confident(&db, &bar_module_name).unwrap();
        assert_eq!(
            bar_module.file(&db).unwrap().path(&db),
            &FilePath::system("/y/src/bar.py")
        );
        let events = db.take_salsa_events();
        assert_function_query_was_not_run(
            &db,
            dynamic_resolution_paths,
            ModuleResolveModeIngredient::new(
                &db,
                db.resolver_environment(),
                ModuleResolveMode::Typing,
            ),
            &events,
        );
    }

    #[test]
    fn nested_site_packages_change_does_not_invalidate_dynamic_resolution_paths() {
        const SITE_PACKAGES: &[FileSpec] = &[("_foo.pth", "/x/src"), ("package/__init__.py", "")];

        let TestCase {
            mut db,
            site_packages,
            ..
        } = TestCaseBuilder::new()
            .with_site_packages_files(SITE_PACKAGES)
            .build();

        dynamic_resolution_paths(
            &db,
            ModuleResolveModeIngredient::new(
                &db,
                db.resolver_environment(),
                ModuleResolveMode::Typing,
            ),
        );
        db.clear_salsa_events();

        db.write_file(site_packages.join("package/nested.py"), "")
            .unwrap();
        dynamic_resolution_paths(
            &db,
            ModuleResolveModeIngredient::new(
                &db,
                db.resolver_environment(),
                ModuleResolveMode::Typing,
            ),
        );

        let events = db.take_salsa_events();
        assert_function_query_was_not_run(
            &db,
            dynamic_resolution_paths,
            ModuleResolveModeIngredient::new(
                &db,
                db.resolver_environment(),
                ModuleResolveMode::Typing,
            ),
            &events,
        );
    }

    #[test]
    fn modifying_pth_file_invalidates_dynamic_resolution_paths() {
        const SITE_PACKAGES: &[FileSpec] = &[("_editable.pth", "/x/src")];

        let TestCase {
            mut db,
            site_packages,
            ..
        } = TestCaseBuilder::new()
            .with_site_packages_files(SITE_PACKAGES)
            .build();
        db.write_files([("/x/src/foo.py", ""), ("/y/src/bar.py", "")])
            .unwrap();

        assert!(resolve_module_confident(&db, &ModuleName::new_static("foo").unwrap()).is_some());

        let pth_path = site_packages.join("_editable.pth");
        db.memory_file_system()
            .write_file(&pth_path, "/y/src")
            .unwrap();
        File::sync_path_only(&mut db, &pth_path);

        assert!(resolve_module_confident(&db, &ModuleName::new_static("foo").unwrap()).is_none());
        assert!(resolve_module_confident(&db, &ModuleName::new_static("bar").unwrap()).is_some());
    }

    #[test]
    fn deleting_pth_file_on_which_module_resolution_depends_invalidates_cache() {
        const SITE_PACKAGES: &[FileSpec] = &[("_foo.pth", "/x/src")];
        let x_directory = [("/x/src/foo.py", "")];

        let TestCase {
            mut db,
            site_packages,
            ..
        } = TestCaseBuilder::new()
            .with_site_packages_files(SITE_PACKAGES)
            .build();

        db.write_files(x_directory).unwrap();

        let foo_module_name = ModuleName::new_static("foo").unwrap();
        let foo_module = resolve_module_confident(&db, &foo_module_name).unwrap();
        assert_eq!(
            foo_module.file(&db).unwrap().path(&db),
            &FilePath::system("/x/src/foo.py")
        );

        db.memory_file_system()
            .remove_file(site_packages.join("_foo.pth"))
            .unwrap();

        File::sync_path(&mut db, &site_packages.join("_foo.pth"));

        assert_eq!(resolve_module_confident(&db, &foo_module_name), None);
    }

    #[test]
    fn deleting_editable_install_on_which_module_resolution_depends_invalidates_cache() {
        const SITE_PACKAGES: &[FileSpec] = &[("_foo.pth", "/x/src")];
        let x_directory = [("/x/src/foo.py", "")];

        let TestCase { mut db, .. } = TestCaseBuilder::new()
            .with_site_packages_files(SITE_PACKAGES)
            .build();

        db.write_files(x_directory).unwrap();

        let foo_module_name = ModuleName::new_static("foo").unwrap();
        let foo_module = resolve_module_confident(&db, &foo_module_name).unwrap();
        let src_path = SystemPathBuf::from("/x/src");
        assert_eq!(
            foo_module.file(&db).unwrap().path(&db),
            &FilePath::from(src_path.join("foo.py"))
        );

        db.memory_file_system()
            .remove_file(src_path.join("foo.py"))
            .unwrap();
        db.memory_file_system().remove_directory(&src_path).unwrap();
        File::sync_path(&mut db, &src_path.join("foo.py"));
        File::sync_path(&mut db, &src_path);
        assert_eq!(resolve_module_confident(&db, &foo_module_name), None);
    }

    #[test]
    fn no_duplicate_search_paths_added() {
        let TestCase { db, .. } = TestCaseBuilder::new()
            .with_src_files(&[("foo.py", "")])
            .with_site_packages_files(&[("_foo.pth", "/src")])
            .build();

        let search_paths: Vec<&SearchPath> =
            search_paths(&db, db.resolver_environment(), ModuleResolveMode::Typing).collect();

        assert!(search_paths.contains(
            &&SearchPath::first_party(db.system(), SystemPathBuf::from("/src")).unwrap()
        ));
        assert!(
            !search_paths.contains(
                &&SearchPath::editable(db.system(), SystemPathBuf::from("/src")).unwrap()
            )
        );
    }

    #[test]
    fn multiple_site_packages_with_editables() {
        let mut db = TestDb::new();

        let venv_site_packages = SystemPathBuf::from("/venv-site-packages");
        let site_packages_pth = venv_site_packages.join("foo.pth");
        let system_site_packages = SystemPathBuf::from("/system-site-packages");
        let editable_install_location = SystemPathBuf::from("/x/y/a.py");
        let system_site_packages_location = system_site_packages.join("a.py");

        db.memory_file_system()
            .create_directory_all("/src")
            .unwrap();
        db.write_files([
            (&site_packages_pth, "/x/y"),
            (&editable_install_location, ""),
            (&system_site_packages_location, ""),
        ])
        .unwrap();

        db.set_search_paths(
            SearchPathSettings {
                site_packages_paths: vec![venv_site_packages, system_site_packages],
                ..SearchPathSettings::new(vec![SystemPathBuf::from("/src")])
            }
            .to_search_paths(db.system(), db.vendored(), &FallibleStrategy)
            .expect("Valid search path settings"),
        );

        // The editable installs discovered from the `.pth` file in the first `site-packages` directory
        // take precedence over the second `site-packages` directory...
        let a_module_name = ModuleName::new_static("a").unwrap();
        let a_module = resolve_module_confident(&db, &a_module_name).unwrap();
        assert_eq!(
            a_module.file(&db).unwrap().path(&db),
            &editable_install_location
        );

        db.memory_file_system()
            .remove_file(&site_packages_pth)
            .unwrap();
        File::sync_path(&mut db, &site_packages_pth);

        // ...But now that the `.pth` file in the first `site-packages` directory has been deleted,
        // the editable install no longer exists, so the module now resolves to the file in the
        // second `site-packages` directory
        let a_module = resolve_module_confident(&db, &a_module_name).unwrap();
        assert_eq!(
            a_module.file(&db).unwrap().path(&db),
            &system_site_packages_location
        );
    }

    #[test]
    #[cfg(unix)]
    fn case_sensitive_resolution_with_symlinked_directory() -> anyhow::Result<()> {
        use anyhow::Context;
        use ruff_db::system::OsSystem;

        let temp_dir = tempfile::TempDir::new()?;
        let root = SystemPathBuf::from_path_buf(
            temp_dir
                .path()
                .canonicalize()
                .context("Failed to canonicalized path")?,
        )
        .expect("UTF8 path for temp dir");

        let mut db = TestDb::new();

        let src = root.join("src");
        let a_package_target = root.join("a-package");
        let a_src = src.join("a");

        db.use_system(OsSystem::new(&root));

        db.write_file(
            a_package_target.join("__init__.py"),
            "class Foo: x: int = 4",
        )
        .context("Failed to write `a-package/__init__.py`")?;

        db.write_file(src.join("main.py"), "print('Hy')")
            .context("Failed to write `main.py`")?;

        // The lexical directory listing must accept the symlink named `a` while rejecting `A`.
        std::os::unix::fs::symlink(a_package_target.as_std_path(), a_src.as_std_path())
            .context("Failed to symlink `src/a` to `a-package`")?;

        db.set_search_paths(
            SearchPathSettings::new(vec![src])
                .to_search_paths(db.system(), db.vendored(), &FallibleStrategy)
                .expect("Valid search path settings"),
        );

        // Now try to resolve the module `A` (note the capital `A` instead of `a`).
        let a_module_name = ModuleName::new_static("A").unwrap();
        assert_eq!(resolve_module_confident(&db, &a_module_name), None);

        // Now lookup the same module using the lowercase `a` and it should
        // resolve to the file in the system site-packages
        let a_module_name = ModuleName::new_static("a").unwrap();
        let a_module = resolve_module_confident(&db, &a_module_name).expect("a.py to resolve");
        assert!(
            a_module
                .file(&db)
                .unwrap()
                .path(&db)
                .as_str()
                .ends_with("src/a/__init__.py"),
        );

        Ok(())
    }

    #[test]
    fn file_to_module_where_one_search_path_is_subdirectory_of_other() {
        let project_directory = SystemPathBuf::from("/project");
        let site_packages = project_directory.join(".venv/lib/python3.13/site-packages");
        let installed_foo_module = site_packages.join("foo/__init__.py");

        let mut db = TestDb::new();
        db.write_file(&installed_foo_module, "").unwrap();

        let search_paths = SearchPathSettings {
            src_roots: vec![project_directory],
            site_packages_paths: vec![site_packages.clone()],
            ..SearchPathSettings::empty()
        }
        .to_search_paths(db.system(), db.vendored(), &FallibleStrategy)
        .expect("Valid search path settings");
        db.set_search_paths(search_paths);

        let foo_module_file = File::new(&db, FilePath::from(installed_foo_module));
        let module = file_to_module(
            &db,
            ResolverFile::new(&db, foo_module_file, db.resolver_environment()),
        )
        .unwrap();
        assert_eq!(module.search_path(&db).unwrap(), &site_packages);
    }
}