brrr-lint 0.1.0

A fast linter and language server for F* (FStar) with autofix capabilities
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
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
//! FST004: Unused open statements detector.
//!
//! Detects `open` statements that import modules which are never used in the file.
//! This helps keep imports clean and reduces compilation overhead.
//!
//! # Examples of detected issues:
//! - `open FStar.List` when no List functions are called
//! - `open Module { name1, name2 }` when name1 or name2 are unused
//! - Module aliases that are never referenced

use lazy_static::lazy_static;
use regex::Regex;
use std::collections::HashSet;
use std::path::PathBuf;

use super::rules::{Diagnostic, DiagnosticSeverity, Edit, Fix, FixConfidence, FixSafetyLevel, Range, Rule, RuleCode};

lazy_static! {
    /// Modules that should NEVER have auto-remove suggested.
    /// These modules bring critical operators or implicit features into scope
    /// that are difficult to detect via static analysis.
    ///
    /// SAFETY: Removing these opens can break working code in subtle ways:
    /// - FStar.Mul: Brings `*` operator for integer multiplication into scope
    /// - FStar.Integers: Generic integer operators (+^, -^, *^, etc.)
    /// - Lib.IntTypes: Type abbreviations and operators (+!, -!, etc.)
    /// - FStar.Tactics*: Metaprogramming that may affect elaboration
    /// - FStar.Pervasives: Core types and operators (usually auto-opened)
    static ref NEVER_AUTO_REMOVE: HashSet<&'static str> = [
        // Operator-providing modules (CRITICAL)
        "FStar.Mul",           // op_Star for multiplication
        "FStar.Integers",      // Generic integer operators
        "Lib.IntTypes",        // Type aliases + operators (+!, -!, etc.)
        "LowStar.BufferOps",   // !*, *= operators

        // Pervasives and core (usually implicit, but dangerous if explicitly opened)
        "FStar.Pervasives",
        "FStar.Pervasives.Native",
        "Prims",

        // Tactics modules (can affect elaboration in subtle ways)
        "FStar.Tactics",
        "FStar.Tactics.V1",
        "FStar.Tactics.V2",
        "FStar.Tactics.Typeclasses",

        // Effect modules (may provide effect abbreviations)
        "FStar.HyperStack.ST",
        "FStar.ST",
        "FStar.All",

        // Modules that provide implicit resolution or coercions
        "FStar.FunctionalExtensionality",
        "FStar.PropositionalExtensionality",
        "FStar.PredicateExtensionality",
    ].iter().cloned().collect();

    /// Modules where removal is RISKY but can be suggested with low confidence.
    /// These bring commonly-used unqualified names or have complex usage patterns.
    static ref RISKY_MODULES: HashSet<&'static str> = [
        // Modules with very common exported names
        "FStar.Classical",      // forall_intro, exists_elim, move_requires
        "FStar.Squash",         // squash, return_squash
        "FStar.Ghost",          // reveal, hide, erased

        // Modules with operators that might be missed
        "FStar.Seq",            // @| operator
        "FStar.Seq.Base",
        "FStar.List.Tot",       // @ operator
        "FStar.List.Tot.Base",
        "FStar.Bytes",          // @| operator

        // Buffer/memory modules with array operators
        "FStar.Buffer",
        "LowStar.Buffer",
        "LowStar.Monotonic.Buffer",
        "Lib.Buffer",

        // Modules with ref operators (!, :=)
        "FStar.Ref",
        "FStar.Heap",
    ].iter().cloned().collect();

    /// Pattern for simple open statements: `open Module.Path`
    /// Captures the full module path (e.g., "FStar.List.Tot")
    static ref OPEN_PATTERN: Regex = Regex::new(
        r"^open\s+([A-Z][\w.]*)"
    ).unwrap();

    /// Pattern for selective open statements: `open Module { name1, name2 }`
    /// Captures both the module path and the selective imports
    static ref OPEN_SELECTIVE_PATTERN: Regex = Regex::new(
        r"^open\s+([A-Z][\w.]*)\s*\{\s*([^}]*)\s*\}"
    ).unwrap();

    /// Pattern for let-open statements: `let open Module.Path in`
    /// This is a local scoped open - captures the module path
    static ref LET_OPEN_PATTERN: Regex = Regex::new(
        r"let\s+open\s+([A-Z][\w.]*)\s+in"
    ).unwrap();

    /// Pattern for module aliases: `module M = Long.Module.Path`
    /// Used to track when aliases are referenced
    static ref MODULE_ALIAS_PATTERN: Regex = Regex::new(
        r"^module\s+([A-Z]\w*)\s*=\s*([A-Z][\w.]*)"
    ).unwrap();

    /// Pattern for qualified identifier usage: `Module.function` or `FStar.List.length`
    /// Captures the module prefix and the identifier being accessed
    static ref QUALIFIED_USE_PATTERN: Regex = Regex::new(
        r"\b([A-Z][\w.]*)\.([\w']+)"
    ).unwrap();

    /// Pattern for unqualified identifiers that might come from opens
    /// Captures lowercase identifiers that could be imported names
    static ref UNQUALIFIED_IDENT_PATTERN: Regex = Regex::new(
        r"\b([a-z_][\w']*)\b"
    ).unwrap();

    /// Pattern for type constructors (capitalized identifiers)
    /// These might be imported via open statements
    static ref TYPE_CONSTRUCTOR_PATTERN: Regex = Regex::new(
        r"\b([A-Z][\w']*)\b"
    ).unwrap();

    /// Pattern for F* operators that might be imported via opens.
    /// These are commonly defined operators in the F* ecosystem.
    static ref OPERATOR_PATTERN: Regex = Regex::new(
        // Match common F* operators (avoiding false positives in comments/strings)
        // Multiplication, addition, subtraction, division, modulo
        // Bitwise: &, |, ^
        // Comparison: ==, !=, <, >, <=, >=
        // List/seq append: @, @|
        // Buffer ops: !*, *=, .(), .()<-
        // Integer ops with hat: +^, -^, *^, /^, %^, &^, |^, <<^, >>^
        // Integer ops with bang: +!, -!, *!
        // Integer ops with dot: +., -., *., &., |., ^., <<., >>.
        r"(?x)
        # Hat operators (FStar integers)
        (\+\^|\-\^|\*\^|/\^|%\^|&\^|\|\^|<<\^|>>^|=\^|<\^|>\^|<=\^|>=\^) |
        # Bang operators (Lib.IntTypes)
        (\+!|\-!|\*!) |
        # Dot operators (Lib.IntTypes)
        (\+\.|\-\.|\*\.|&\.|\|\.|\^\.|\<\<\.|\>\>\.) |
        # Buffer operators
        (!\*|\*=) |
        # List/seq append
        (@\|)
        # NOTE: Lookahead/lookbehind not supported by rust regex crate.
        # Simplified patterns used instead (may have slight false positives).
        # Basic * and @ are handled via string contains checks.
        "
    ).unwrap();
}

/// Represents an open statement in F* source code.
#[derive(Debug, Clone)]
pub struct OpenStatement {
    /// Full module path (e.g., "FStar.List.Tot")
    pub module_path: String,
    /// For selective opens, the list of imported names
    /// None for full module opens (e.g., `open FStar.List`)
    pub selective: Option<Vec<String>>,
    /// 1-indexed line number where the open appears
    pub line: usize,
    /// 1-indexed column where the open starts
    pub col: usize,
    /// The full line text for fix generation
    pub line_text: String,
}

impl OpenStatement {
    /// Returns the last component of the module path.
    /// For "FStar.List.Tot", returns "Tot".
    pub fn module_name(&self) -> &str {
        self.module_path
            .rsplit('.')
            .next()
            .unwrap_or(&self.module_path)
    }

    /// Returns all module path prefixes that could be used for qualified access.
    /// For "FStar.List.Tot", returns ["FStar", "FStar.List", "FStar.List.Tot", "List", "List.Tot", "Tot"]
    pub fn accessible_prefixes(&self) -> Vec<String> {
        let parts: Vec<&str> = self.module_path.split('.').collect();
        let mut prefixes = Vec::new();

        // Add full paths starting from each position
        for start in 0..parts.len() {
            let mut current = String::new();
            for (i, part) in parts[start..].iter().enumerate() {
                if i > 0 {
                    current.push('.');
                }
                current.push_str(part);
                prefixes.push(current.clone());
            }
        }

        prefixes
    }
}

/// Represents a module alias declaration.
#[derive(Debug, Clone)]
pub struct ModuleAlias {
    /// The alias name (e.g., "L" in `module L = FStar.List`)
    pub alias: String,
    /// The target module path
    pub target: String,
    /// 1-indexed line number
    pub line: usize,
}

/// Result of parsing a file for open statement analysis.
#[derive(Debug, Clone)]
pub struct OpenAnalysis {
    /// All open statements found in the file (top-level)
    pub opens: Vec<OpenStatement>,
    /// Local scope opens (let open Module in)
    pub let_opens: Vec<OpenStatement>,
    /// All module aliases found in the file
    pub aliases: Vec<ModuleAlias>,
    /// Module prefixes used in qualified access (e.g., "List" from "List.map")
    pub used_module_prefixes: HashSet<String>,
    /// All unqualified identifiers used in the file
    pub used_identifiers: HashSet<String>,
    /// Type constructors used in the file
    pub used_type_constructors: HashSet<String>,
    /// Operator internal names extracted from source (e.g., "op_Star" for *)
    pub used_operators: HashSet<String>,
}

/// Parse all open statements from F* source content.
///
/// Handles both simple opens (`open FStar.List`) and selective opens
/// (`open FStar.List { map, filter }`).
///
/// # Arguments
/// * `content` - The F* source code to parse
///
/// # Returns
/// A vector of all open statements found, in order of appearance.
pub fn parse_opens(content: &str) -> Vec<OpenStatement> {
    let mut opens = Vec::new();
    // Strip comments and strings first so we don't parse opens inside them.
    // This correctly handles multi-line block comments like:
    //   (* open FStar.Unused
    //      open FStar.AlsoUnused *)
    let clean = strip_comments_and_strings(content);
    let original_lines: Vec<&str> = content.lines().collect();

    for (line_num, line) in clean.lines().enumerate() {
        let stripped = line.trim();

        // After stripping, empty lines or whitespace-only lines are skipped
        if stripped.is_empty() {
            continue;
        }

        // Check selective open first (more specific pattern)
        if let Some(caps) = OPEN_SELECTIVE_PATTERN.captures(stripped) {
            let module = caps.get(1).unwrap().as_str().to_string();
            let names_str = caps.get(2).map(|m| m.as_str()).unwrap_or("");
            let names: Vec<String> = names_str
                .split(',')
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
                .collect();

            // Use original line for column calculation and line_text
            let orig_line = original_lines.get(line_num).unwrap_or(&"");
            let col = orig_line.find("open").map(|p| p + 1).unwrap_or(1);

            opens.push(OpenStatement {
                module_path: module,
                selective: Some(names),
                line: line_num + 1,
                col,
                line_text: orig_line.to_string(),
            });
        } else if let Some(caps) = OPEN_PATTERN.captures(stripped) {
            let module = caps.get(1).unwrap().as_str().to_string();
            let orig_line = original_lines.get(line_num).unwrap_or(&"");
            let col = orig_line.find("open").map(|p| p + 1).unwrap_or(1);

            opens.push(OpenStatement {
                module_path: module,
                selective: None,
                line: line_num + 1,
                col,
                line_text: orig_line.to_string(),
            });
        }
    }

    opens
}

/// Parse module alias declarations from content.
///
/// Finds declarations like `module L = FStar.List`.
///
/// # Arguments
/// * `content` - The F* source code to parse
///
/// # Returns
/// A vector of all module aliases found.
pub fn parse_module_aliases(content: &str) -> Vec<ModuleAlias> {
    let mut aliases = Vec::new();
    let clean = strip_comments_and_strings(content);

    for (line_num, line) in clean.lines().enumerate() {
        let stripped = line.trim();

        if stripped.is_empty() {
            continue;
        }

        if let Some(caps) = MODULE_ALIAS_PATTERN.captures(stripped) {
            aliases.push(ModuleAlias {
                alias: caps.get(1).unwrap().as_str().to_string(),
                target: caps.get(2).unwrap().as_str().to_string(),
                line: line_num + 1,
            });
        }
    }

    aliases
}

/// Parse `let open Module in` statements from content.
///
/// These are local-scope opens that bring module contents into scope
/// for the remainder of the expression. They are common in F* code.
///
/// # Arguments
/// * `content` - The F* source code to parse
///
/// # Returns
/// A vector of let-open statements found.
pub fn parse_let_opens(content: &str) -> Vec<OpenStatement> {
    let mut let_opens = Vec::new();
    let clean = strip_comments_and_strings(content);
    let original_lines: Vec<&str> = content.lines().collect();

    for (line_num, line) in clean.lines().enumerate() {
        let stripped = line.trim();

        if stripped.is_empty() {
            continue;
        }

        // Find all let-opens on this line (use cleaned line for matching)
        for caps in LET_OPEN_PATTERN.captures_iter(line) {
            if let Some(module_match) = caps.get(1) {
                let module = module_match.as_str().to_string();
                let col = module_match.start() + 1;
                let orig_line = original_lines.get(line_num).unwrap_or(&"");

                let_opens.push(OpenStatement {
                    module_path: module,
                    selective: None,
                    line: line_num + 1,
                    col,
                    line_text: orig_line.to_string(),
                });
            }
        }
    }

    let_opens
}

/// Strip comments and string literals from F* source code.
///
/// This prevents false positives from identifiers mentioned in comments
/// or string literals.
fn strip_comments_and_strings(content: &str) -> String {
    let mut result = String::with_capacity(content.len());
    let chars: Vec<char> = content.chars().collect();
    let n = chars.len();
    let mut i = 0;
    let mut comment_depth = 0;
    let mut in_line_comment = false;

    while i < n {
        // Handle line comments
        if i + 1 < n && chars[i] == '/' && chars[i + 1] == '/' {
            in_line_comment = true;
            i += 2;
            continue;
        }

        // End of line comment
        if in_line_comment {
            if chars[i] == '\n' {
                in_line_comment = false;
                result.push('\n');
            }
            i += 1;
            continue;
        }

        // Handle block comment start
        if i + 1 < n && chars[i] == '(' && chars[i + 1] == '*' {
            comment_depth += 1;
            i += 2;
            continue;
        }

        // Handle block comment end
        if i + 1 < n && chars[i] == '*' && chars[i + 1] == ')' && comment_depth > 0 {
            comment_depth -= 1;
            i += 2;
            continue;
        }

        // Inside comment - skip
        if comment_depth > 0 {
            if chars[i] == '\n' {
                result.push('\n');
            }
            i += 1;
            continue;
        }

        // Handle string literals
        if chars[i] == '"' {
            i += 1;
            while i < n && chars[i] != '"' {
                if chars[i] == '\\' && i + 1 < n {
                    i += 2;
                } else {
                    i += 1;
                }
            }
            if i < n {
                i += 1; // Skip closing quote
            }
            continue;
        }

        result.push(chars[i]);
        i += 1;
    }

    result
}

/// Check if a line is a declaration/directive that should be excluded from
/// identifier extraction. These lines reference modules by name but do NOT
/// constitute usage of names imported via `open`.
///
/// Excluded lines:
/// - `open Module` - the open statement itself
/// - `module X = Module.Path` - alias declarations (work without opens)
/// - `friend Module` - friend declarations (work without opens)
/// - `include Module` - include declarations (separate from opens)
fn is_declaration_line(trimmed: &str) -> bool {
    trimmed.starts_with("open ")
        || trimmed.starts_with("module ")
        || trimmed.starts_with("friend ")
        || trimmed.starts_with("include ")
}

/// Extract all module prefixes used in qualified access patterns.
///
/// For code like `List.map x` or `FStar.List.Tot.length`, extracts
/// "List" and "FStar.List.Tot" as used prefixes.
/// Excludes declaration lines (open, module alias, friend, include)
/// to avoid false positives/negatives.
fn extract_used_module_prefixes(content: &str) -> HashSet<String> {
    // Filter out declaration lines to avoid counting module paths in
    // opens/aliases/friend as "used"
    let filtered_content: String = content
        .lines()
        .filter(|line| {
            let trimmed = line.trim();
            !is_declaration_line(trimmed)
        })
        .collect::<Vec<_>>()
        .join("\n");

    let clean_content = strip_comments_and_strings(&filtered_content);
    let mut prefixes = HashSet::new();

    for caps in QUALIFIED_USE_PATTERN.captures_iter(&clean_content) {
        if let Some(m) = caps.get(1) {
            let prefix = m.as_str();
            // Add the full prefix
            prefixes.insert(prefix.to_string());
            // Also add each nested prefix
            let parts: Vec<&str> = prefix.split('.').collect();
            for i in 1..parts.len() {
                prefixes.insert(parts[..i].join("."));
            }
        }
    }

    prefixes
}

/// Extract identifiers that are accessed via qualified paths (e.g., `empty` from `S.empty`).
/// These are NOT imported via `open` but via module aliases or direct qualified access.
fn extract_qualified_identifiers(content: &str) -> HashSet<String> {
    let filtered_content: String = content
        .lines()
        .filter(|line| {
            let trimmed = line.trim();
            !is_declaration_line(trimmed)
        })
        .collect::<Vec<_>>()
        .join("\n");

    let clean_content = strip_comments_and_strings(&filtered_content);
    let mut qualified_idents = HashSet::new();

    // QUALIFIED_USE_PATTERN captures Module.identifier - group 2 is the identifier
    for caps in QUALIFIED_USE_PATTERN.captures_iter(&clean_content) {
        if let Some(m) = caps.get(2) {
            qualified_idents.insert(m.as_str().to_string());
        }
    }

    qualified_idents
}

/// Extract all unqualified identifiers from content.
///
/// These are potential uses of names imported via `open` statements.
/// Excludes identifiers from declaration lines (open, module alias, friend,
/// include) and identifiers accessed through qualified paths (e.g., `empty`
/// from `S.empty` is NOT an unqualified use of `empty`).
pub fn extract_used_identifiers(content: &str) -> HashSet<String> {
    // Filter out declaration lines to avoid counting imported/declared names as "used"
    let filtered_content: String = content
        .lines()
        .filter(|line| {
            let trimmed = line.trim();
            !is_declaration_line(trimmed)
        })
        .collect::<Vec<_>>()
        .join("\n");

    let clean_content = strip_comments_and_strings(&filtered_content);
    let mut identifiers = HashSet::new();

    // Collect identifiers from qualified accesses (e.g., `empty` from `S.empty`).
    // These are NOT unqualified uses - they come from module aliases or qualified paths.
    let qualified_idents = extract_qualified_identifiers(content);

    // Extract lowercase identifiers (functions, values)
    for caps in UNQUALIFIED_IDENT_PATTERN.captures_iter(&clean_content) {
        if let Some(m) = caps.get(1) {
            let ident = m.as_str().to_string();
            // Only count as unqualified if the identifier also appears
            // outside of qualified access contexts. We use a heuristic:
            // if an identifier ONLY appears as part of qualified access
            // (i.e., always after a dot), it's not an unqualified use.
            // However, if it appears both ways, we conservatively include it.
            identifiers.insert(ident);
        }
    }

    // Remove identifiers that ONLY appear in qualified contexts.
    // We check: for each qualified identifier, does it also appear standalone?
    // We look for pattern: the identifier preceded by something other than '.'
    for qi in &qualified_idents {
        // Check if identifier appears unqualified anywhere in the content
        if !has_unqualified_use(&clean_content, qi) {
            identifiers.remove(qi);
        }
    }

    identifiers
}

/// Check if an identifier has at least one unqualified use in the content.
/// An unqualified use is one NOT preceded by a dot.
fn has_unqualified_use(content: &str, ident: &str) -> bool {
    let bytes = content.as_bytes();
    let ident_bytes = ident.as_bytes();
    let ident_len = ident_bytes.len();

    let mut pos = 0;
    while pos + ident_len <= bytes.len() {
        if let Some(found) = content[pos..].find(ident) {
            let abs_pos = pos + found;

            // Check if this is a whole-word match
            let before_ok = if abs_pos == 0 {
                true
            } else {
                let c = bytes[abs_pos - 1];
                !c.is_ascii_alphanumeric() && c != b'_' && c != b'\''
            };

            let after_ok = if abs_pos + ident_len >= bytes.len() {
                true
            } else {
                let c = bytes[abs_pos + ident_len];
                !c.is_ascii_alphanumeric() && c != b'_' && c != b'\''
            };

            if before_ok && after_ok {
                // Check if preceded by a dot (qualified access)
                let preceded_by_dot = abs_pos > 0 && bytes[abs_pos - 1] == b'.';
                if !preceded_by_dot {
                    return true;
                }
            }

            pos = abs_pos + 1;
        } else {
            break;
        }
    }

    false
}

/// Extract type constructors (capitalized identifiers) from content.
/// Excludes type constructors that appear in declaration lines (open, module
/// alias, friend, include) to avoid counting imported/declared names as "used".
/// Also excludes type constructors that only appear in qualified access contexts
/// (e.g., `Module.SomeType` - the `SomeType` is accessed via the module, not an open).
fn extract_type_constructors(content: &str) -> HashSet<String> {
    // Filter out declaration lines to avoid counting imported/declared names as "used".
    let filtered_content: String = content
        .lines()
        .filter(|line| {
            let trimmed = line.trim();
            !is_declaration_line(trimmed)
        })
        .collect::<Vec<_>>()
        .join("\n");

    let clean_content = strip_comments_and_strings(&filtered_content);
    let qualified_idents = extract_qualified_identifiers(content);
    let mut constructors = HashSet::new();

    for caps in TYPE_CONSTRUCTOR_PATTERN.captures_iter(&clean_content) {
        if let Some(m) = caps.get(1) {
            constructors.insert(m.as_str().to_string());
        }
    }

    // Remove type constructors that ONLY appear in qualified contexts
    for qi in &qualified_idents {
        if qi.chars().next().map_or(false, |c| c.is_uppercase()) {
            if !has_unqualified_use(&clean_content, qi) {
                constructors.remove(qi);
            }
        }
    }

    constructors
}

/// Perform full analysis of a file for unused open detection.
///
/// This is the main entry point for FST004 analysis.
///
/// # Arguments
/// * `content` - The F* source code to analyze
///
/// # Returns
/// An `OpenAnalysis` struct containing all parsed information needed
/// to determine which opens are unused.
pub fn analyze_opens(content: &str) -> OpenAnalysis {
    OpenAnalysis {
        opens: parse_opens(content),
        let_opens: parse_let_opens(content),
        aliases: parse_module_aliases(content),
        used_module_prefixes: extract_used_module_prefixes(content),
        used_identifiers: extract_used_identifiers(content),
        used_type_constructors: extract_type_constructors(content),
        used_operators: extract_operator_internal_names(content),
    }
}

/// Determine if an open statement is potentially used.
///
/// This is a conservative check - it returns true if there's any evidence
/// the open might be used. False positives (marking used as unused) are
/// worse than false negatives.
///
/// # Arguments
/// * `open_stmt` - The open statement to check
/// * `analysis` - The full file analysis
///
/// # Returns
/// `true` if the open appears to be used, `false` if it's likely unused.
pub fn is_open_used(open_stmt: &OpenStatement, analysis: &OpenAnalysis) -> bool {
    // Check if any accessible prefix is used in qualified access
    for prefix in open_stmt.accessible_prefixes() {
        if analysis.used_module_prefixes.contains(&prefix) {
            return true;
        }
    }

    // Check if the module name itself is used as a prefix
    let module_name = open_stmt.module_name();
    if analysis.used_module_prefixes.contains(module_name) {
        return true;
    }

    // For selective opens, check if any imported name is used
    if let Some(ref names) = open_stmt.selective {
        for name in names {
            if analysis.used_identifiers.contains(name) {
                return true;
            }
            if analysis.used_type_constructors.contains(name) {
                return true;
            }
        }
        // If we have selective imports and none are used, it's unused
        return false;
    }

    // For full module opens, we can't be certain what names are imported
    // This is where we'd need module signature information for accurate detection
    // For now, be conservative and assume it might be used
    true
}

/// Generate a fix to remove an unused open statement.
///
/// # Arguments
/// * `open_stmt` - The open statement to remove
/// * `file` - The file path
///
/// # Returns
/// A `Fix` that removes the open statement line.
/// Note: This function creates a Caution-level fix since it doesn't have
/// full safety analysis context. Use the rule's check() method for accurate
/// safety classification.
pub fn generate_remove_fix(open_stmt: &OpenStatement, file: &PathBuf) -> Fix {
    Fix::caution(
        format!("Remove unused open `{}`", open_stmt.module_path),
        vec![Edit {
            file: file.clone(),
            range: Range::new(open_stmt.line, 1, open_stmt.line + 1, 1),
            new_text: String::new(),
        }],
    )
    .with_reversible(false)  // Removal is not easily reversible
}

/// Check if content has the `!` dereference operator (not `!=` or `!*`).
fn content_has_bang_operator(content: &str) -> bool {
    let chars: Vec<char> = content.chars().collect();
    for i in 0..chars.len() {
        if chars[i] == '!' {
            // Check that it's not `!=` or `!*`
            let next = chars.get(i + 1);
            if next != Some(&'=') && next != Some(&'*') {
                // Check that it's not preceded by another `!`
                let prev = if i > 0 { chars.get(i - 1) } else { None };
                if prev != Some(&'!') && prev != Some(&'=') {
                    return true;
                }
            }
        }
    }
    false
}

/// Check if content has the `*` multiplication operator in arithmetic context.
/// Looks for patterns like `word * word` or `paren * paren`.
fn content_has_mul_operator(content: &str) -> bool {
    let chars: Vec<char> = content.chars().collect();
    for i in 1..chars.len().saturating_sub(1) {
        if chars[i] == '*' {
            // Don't count if part of *= or *^ or *! or *. or !* or (*
            let next = chars.get(i + 1);
            let prev = chars.get(i.saturating_sub(1));
            if next == Some(&'=')
                || next == Some(&'^')
                || next == Some(&'!')
                || next == Some(&'.')
                || next == Some(&')')
            {
                continue;
            }
            if prev == Some(&'!')
                || prev == Some(&'(')
                || prev == Some(&'*')
                || prev == Some(&':')
            {
                continue;
            }
            // Check for word/paren * word/paren pattern
            // There should be alphanumeric or ) before, and alphanumeric or ( after
            if let Some(p) = prev {
                if let Some(n) = next {
                    if (p.is_alphanumeric() || *p == ')' || *p == ' ')
                        && (n.is_alphanumeric() || *n == '(' || *n == ' ')
                    {
                        return true;
                    }
                }
            }
        }
    }
    false
}

/// Check if content has the `@` list append operator.
/// Avoids matching email addresses or attribute markers.
fn content_has_append_operator(content: &str) -> bool {
    let chars: Vec<char> = content.chars().collect();
    for i in 1..chars.len().saturating_sub(1) {
        if chars[i] == '@' {
            // Don't count if part of @| or attribute marker
            let next = chars.get(i + 1);
            let prev = chars.get(i.saturating_sub(1));
            if next == Some(&'|') {
                continue;
            }
            // Check for word/bracket @ word/bracket pattern
            if let Some(p) = prev {
                if let Some(n) = next {
                    if (p.is_alphanumeric() || *p == ']' || *p == ')' || *p == ' ')
                        && (n.is_alphanumeric() || *n == '[' || *n == '(' || *n == ' ')
                    {
                        return true;
                    }
                }
            }
        }
    }
    false
}

/// Map F* source-level operators to their internal names.
///
/// In F*, operators like `*` are represented internally as `op_Star`.
/// This function extracts operators from source code and maps them to
/// the corresponding internal names that appear in module exports.
///
/// Returns a set of internal operator names found in the content.
fn extract_operator_internal_names(content: &str) -> HashSet<String> {
    let clean_content = strip_comments_and_strings(content);
    let mut internal_names = HashSet::new();

    // Check for specific operators and add their internal names
    // Hat operators (FStar.Int*, FStar.UInt*, FStar.Integers)
    if clean_content.contains("+^") {
        internal_names.insert("op_Plus_Hat".to_string());
    }
    if clean_content.contains("-^") {
        internal_names.insert("op_Subtraction_Hat".to_string());
    }
    if clean_content.contains("*^") {
        internal_names.insert("op_Star_Hat".to_string());
    }
    if clean_content.contains("/^") {
        internal_names.insert("op_Slash_Hat".to_string());
    }
    if clean_content.contains("%^") {
        internal_names.insert("op_Percent_Hat".to_string());
    }
    if clean_content.contains("&^") {
        internal_names.insert("op_Amp_Hat".to_string());
    }
    if clean_content.contains("|^") {
        internal_names.insert("op_Bar_Hat".to_string());
    }
    if clean_content.contains("^^") {
        internal_names.insert("op_Hat_Hat".to_string());
    }
    if clean_content.contains("<<^") {
        internal_names.insert("op_Less_Less_Hat".to_string());
    }
    if clean_content.contains(">>^") {
        internal_names.insert("op_Greater_Greater_Hat".to_string());
    }
    if clean_content.contains("=^") {
        internal_names.insert("op_Equals_Hat".to_string());
    }
    if clean_content.contains("<^") {
        internal_names.insert("op_Less_Hat".to_string());
    }
    if clean_content.contains(">^") {
        internal_names.insert("op_Greater_Hat".to_string());
    }
    if clean_content.contains("<=^") {
        internal_names.insert("op_Less_Equals_Hat".to_string());
    }
    if clean_content.contains(">=^") {
        internal_names.insert("op_Greater_Equals_Hat".to_string());
    }

    // Bang operators (Lib.IntTypes)
    if clean_content.contains("+!") {
        internal_names.insert("op_Plus_Bang".to_string());
    }
    if clean_content.contains("-!") {
        internal_names.insert("op_Subtraction_Bang".to_string());
    }
    if clean_content.contains("*!") {
        internal_names.insert("op_Star_Bang".to_string());
    }

    // Dot operators (Lib.IntTypes)
    if clean_content.contains("+.") {
        internal_names.insert("op_Plus_Dot".to_string());
    }
    if clean_content.contains("-.") {
        internal_names.insert("op_Subtraction_Dot".to_string());
    }
    if clean_content.contains("*.") {
        internal_names.insert("op_Star_Dot".to_string());
    }
    if clean_content.contains("&.") {
        internal_names.insert("op_Amp_Dot".to_string());
    }
    if clean_content.contains("|.") {
        internal_names.insert("op_Bar_Dot".to_string());
    }
    if clean_content.contains("^.") {
        internal_names.insert("op_Hat_Dot".to_string());
    }
    if clean_content.contains("<<.") {
        internal_names.insert("op_Less_Less_Dot".to_string());
    }
    if clean_content.contains(">>.") {
        internal_names.insert("op_Greater_Greater_Dot".to_string());
    }

    // Buffer operators (LowStar.BufferOps)
    if clean_content.contains("!*") {
        internal_names.insert("op_Bang_Star".to_string());
    }
    if clean_content.contains("*=") {
        internal_names.insert("op_Star_Equals".to_string());
    }

    // Array access operators (LowStar.Buffer, Lib.Buffer, FStar.Buffer)
    // These use .() and .()<- syntax which we detect differently
    if clean_content.contains(".(") {
        internal_names.insert("op_Array_Access".to_string());
    }
    if clean_content.contains(".()<-") || clean_content.contains(".(") && clean_content.contains("<-")
    {
        internal_names.insert("op_Array_Assignment".to_string());
    }

    // Sequence/list append operators
    if clean_content.contains("@|") {
        internal_names.insert("op_At_Bar".to_string());
    }

    // ST operators
    // Check for ! used as dereference (not != or !* patterns)
    // Use simple string scanning
    if content_has_bang_operator(&clean_content) {
        internal_names.insert("op_Bang".to_string());
    }
    if clean_content.contains(":=") {
        internal_names.insert("op_Colon_Equals".to_string());
    }

    // Basic multiplication - FStar.Mul
    // This is tricky: * is used in many contexts (types, comments, etc.)
    // We look for patterns like `expr * expr` in arithmetic contexts
    if content_has_mul_operator(&clean_content) {
        internal_names.insert("op_Star".to_string());
    }

    // List append @
    // Avoid matching email addresses or attribute markers
    if content_has_append_operator(&clean_content) {
        internal_names.insert("op_At".to_string());
    }

    internal_names
}

/// Known module exports database.
/// Returns known exported names for common F* modules.
/// This allows the linter to check if any exported name is actually used.
///
/// This database covers the F* standard library and common verification libraries.
/// When a module is not in this database, the linter conservatively assumes
/// the open might be used (to avoid false positives).
fn get_known_exports(module: &str) -> Option<HashSet<&'static str>> {
    match module {
        // ========================================
        // FStar Core / Pervasives
        // ========================================
        "FStar.Pervasives" | "FStar.Pervasives.Native" => Some(
            [
                // Normalization and tactics
                "normalize",
                "normalize_term",
                "assert_norm",
                "norm",
                "reveal_opaque",
                "synth",
                "intro_ambient",
                "ambient",
                // Native types
                "option",
                "Some",
                "None",
                "tuple2",
                "tuple3",
                "tuple4",
                "tuple5",
                "fst",
                "snd",
                // Result type
                "result",
                "V",
                "E",
                // Common effects
                "pure_return",
                "pure_bind",
                // Attributes
                "inline_let",
                "rename_let",
                "plugin",
                "tcnorm",
                "erasable",
                "comment",
                "deprecated",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        // Multiplication operator (commonly needed for * in specs)
        "FStar.Mul" => Some(["op_Star"].iter().cloned().collect()),

        // ========================================
        // FStar.List modules
        // ========================================
        "FStar.List.Tot" | "FStar.List.Tot.Base" => Some(
            [
                // Basic operations
                "length",
                "hd",
                "tl",
                "nth",
                "index",
                "count",
                "isEmpty",
                "noRepeats",
                "last",
                // Construction/destruction
                "rev",
                "append",
                "op_At",
                "flatten",
                "concat",
                "snoc",
                "init",
                "unsnoc",
                // Higher-order
                "map",
                "mapi",
                "map2",
                "map3",
                "fold_left",
                "fold_right",
                "fold_left2",
                "filter",
                "find",
                "find_l",
                "partition",
                "for_all",
                "for_all2",
                "existsb",
                "exists_",
                "collect",
                "concatMap",
                // Membership and search
                "mem",
                "memP",
                "contains",
                "assoc",
                // Zipping and splitting
                "split",
                "unzip",
                "unzip3",
                "zip",
                "zip3",
                "zipWith",
                // Sorting
                "sortWith",
                "sorted",
                "insert_sorted",
                // List creation
                "list_refb",
                "list_ref",
                // Indexed operations
                "index_of",
                "split_at",
                "splitAt",
                // Take/drop
                "take",
                "drop",
                // Comparison
                "compare_of_bool",
                "bool_of_compare",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "FStar.List.Tot.Properties" => Some(
            [
                // Length lemmas
                "append_length",
                "rev_length",
                "map_length",
                "flatten_length",
                "filter_length",
                // Append lemmas
                "append_mem",
                "append_assoc",
                "append_nil_l",
                "append_l_nil",
                "append_inv_head",
                "append_inv_tail",
                // Rev lemmas
                "rev_involutive",
                "rev_append",
                "rev_mem",
                "rev_rev",
                "rev_injective",
                // Map lemmas
                "map_append",
                "map_rev",
                "map_map",
                "map_id",
                "map_injective",
                // Fold lemmas
                "fold_left_append",
                "fold_right_append",
                "fold_left_map",
                "fold_right_map",
                // Membership lemmas
                "index_mem",
                "mem_index",
                "mem_rev",
                "mem_append",
                "mem_filter",
                "mem_map",
                "mem_existsb",
                "mem_count",
                // Index lemmas
                "lemma_index_append1",
                "lemma_index_append2",
                "nth_split_at",
                // Other
                "assoc_mem",
                "for_all_mem",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "FStar.List.Pure" | "FStar.List.Pure.Base" => Some(
            [
                "length",
                "hd",
                "tl",
                "nth",
                "index",
                "rev",
                "append",
                "flatten",
                "map",
                "mapi",
                "fold_left",
                "fold_right",
                "filter",
                "find",
                "mem",
                "for_all",
                "existsb",
                "assoc",
                "split",
                "zip",
                "unzip",
                "concat",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        // ========================================
        // FStar.Seq modules
        // ========================================
        "FStar.Seq" | "FStar.Seq.Base" => Some(
            [
                // Type
                "seq",
                "lseq",
                // Construction
                "empty",
                "create",
                "init",
                "createL",
                "of_list",
                // Access
                "length",
                "index",
                "head",
                "tail",
                "last",
                // Update
                "upd",
                // Concatenation
                "append",
                "op_At_Bar",
                "cons",
                "snoc",
                // Subsequences
                "slice",
                "split",
                // Equality
                "equal",
                "eq",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "FStar.Seq.Properties" => Some(
            [
                // Length lemmas
                "lemma_len_append",
                "lemma_len_slice",
                "lemma_create_len",
                "lemma_init_len",
                // Index lemmas
                "lemma_index_app1",
                "lemma_index_app2",
                "lemma_index_slice",
                "lemma_index_create",
                "lemma_index_upd1",
                "lemma_index_upd2",
                // Equality lemmas
                "lemma_eq_intro",
                "lemma_eq_elim",
                "lemma_eq_refl",
                // Append lemmas
                "append_assoc",
                "append_empty_l",
                "append_empty_r",
                "lemma_append_inj",
                // Membership
                "mem",
                "lemma_mem_append",
                "lemma_mem_snoc",
                // Counting
                "count",
                "lemma_count_slice",
                // Slice lemmas
                "lemma_slice_snoc",
                "lemma_slice_first_in_append",
                "slice_slice",
                // Split lemmas
                "lemma_split",
                "split_eq",
                // Find
                "find_l",
                "find_append_some",
                "find_append_none",
                // Other
                "contains",
                "seq_of_list",
                "seq_to_list",
                "lemma_seq_of_list_induction",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        // ========================================
        // FStar.Option
        // ========================================
        "FStar.Option" => Some(
            [
                "option",
                "Some",
                "None",
                "isSome",
                "isNone",
                "get",
                "map",
                "mapTot",
                "bind",
                "optionToBool",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        // ========================================
        // FStar.Either
        // ========================================
        "FStar.Either" => Some(
            [
                "either",
                "Inl",
                "Inr",
                "isLeft",
                "isRight",
                "left",
                "right",
                "map_left",
                "map_right",
                "fold",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        // ========================================
        // FStar.Set / FStar.Map
        // ========================================
        "FStar.Set" => Some(
            [
                "set",
                "empty",
                "singleton",
                "mem",
                "equal",
                "subset",
                "union",
                "intersect",
                "complement",
                "add",
                "remove",
                "intension",
                "as_set",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "FStar.Map" => Some(
            [
                "t",
                "domain",
                "sel",
                "upd",
                "const",
                "concat",
                "contains",
                "restrict",
                "equal",
                "map_literal",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "FStar.OrdMap" => Some(
            [
                "ordmap", "empty", "const_on", "select", "update", "contains", "dom", "remove",
                "choose", "size", "equal", "map", "fold",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "FStar.OrdSet" => Some(
            [
                "ordset",
                "empty",
                "mem",
                "singleton",
                "union",
                "intersect",
                "subset",
                "equal",
                "choose",
                "remove",
                "as_list",
                "size",
                "fold",
                "map",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        // ========================================
        // FStar.Ghost / FStar.Erased
        // ========================================
        "FStar.Ghost" => Some(
            [
                "erased",
                "reveal",
                "hide",
                "elift1",
                "elift2",
                "elift3",
                "push_refinement",
                "pull_refinement",
                "join",
                "bind",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        // ========================================
        // FStar.Classical
        // ========================================
        "FStar.Classical" => Some(
            [
                "give_witness",
                "get_witness",
                "forall_intro",
                "exists_elim",
                "impl_intro",
                "impl_elim",
                "or_elim",
                "and_elim",
                "exists_intro",
                "forall_elim",
                "move_requires",
                "lemma_forall_intro_gtot",
                "ghost_lemma",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "FStar.Classical.Sugar" => Some(
            ["forall_intro", "exists_elim", "implies_intro", "or_elim"]
                .iter()
                .cloned()
                .collect(),
        ),

        "FStar.Squash" => Some(
            [
                "squash",
                "return_squash",
                "bind_squash",
                "get_proof",
                "give_proof",
                "map_squash",
                "join_squash",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "FStar.IndefiniteDescription" => Some(
            [
                "indefinite_description_ghost",
                "indefinite_description_tot",
                "strong_indefinite_description_ghost",
                "elim_squash",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        // ========================================
        // FStar integer modules
        // ========================================
        "FStar.Int" => Some(
            [
                "int_t",
                "v",
                "int_to_t",
                "add",
                "sub",
                "mul",
                "div",
                "rem",
                "logand",
                "logxor",
                "logor",
                "lognot",
                "shift_left",
                "shift_right",
                "shift_arithmetic_right",
                "op_Plus_Hat",
                "op_Subtraction_Hat",
                "op_Star_Hat",
                "op_Slash_Hat",
                "op_Percent_Hat",
                "op_Hat_Hat",
                "op_Amp_Hat",
                "op_Bar_Hat",
                "op_Less_Less_Hat",
                "op_Greater_Greater_Hat",
                "op_Equals_Hat",
                "op_Greater_Hat",
                "op_Less_Hat",
                "op_Greater_Equals_Hat",
                "op_Less_Equals_Hat",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "FStar.Int8" | "FStar.Int16" | "FStar.Int32" | "FStar.Int64" | "FStar.Int128" => Some(
            [
                "t",
                "v",
                "int_to_t",
                "add",
                "sub",
                "mul",
                "div",
                "rem",
                "logand",
                "logxor",
                "logor",
                "lognot",
                "shift_left",
                "shift_right",
                "shift_arithmetic_right",
                "add_mod",
                "sub_mod",
                "mul_mod",
                "op_Plus_Hat",
                "op_Subtraction_Hat",
                "op_Star_Hat",
                "op_Slash_Hat",
                "op_Percent_Hat",
                "op_Hat_Hat",
                "op_Amp_Hat",
                "op_Bar_Hat",
                "op_Less_Less_Hat",
                "op_Greater_Greater_Hat",
                "op_Equals_Hat",
                "op_Greater_Hat",
                "op_Less_Hat",
                "op_Greater_Equals_Hat",
                "op_Less_Equals_Hat",
                "n",
                "zero",
                "one",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "FStar.UInt" => Some(
            [
                "uint_t",
                "v",
                "uint_to_t",
                "add",
                "sub",
                "mul",
                "div",
                "rem",
                "logand",
                "logxor",
                "logor",
                "lognot",
                "shift_left",
                "shift_right",
                "add_mod",
                "sub_mod",
                "mul_mod",
                "op_Plus_Hat",
                "op_Subtraction_Hat",
                "op_Star_Hat",
                "op_Slash_Hat",
                "op_Percent_Hat",
                "op_Hat_Hat",
                "op_Amp_Hat",
                "op_Bar_Hat",
                "op_Less_Less_Hat",
                "op_Greater_Greater_Hat",
                "op_Equals_Hat",
                "op_Greater_Hat",
                "op_Less_Hat",
                "op_Greater_Equals_Hat",
                "op_Less_Equals_Hat",
                "max_int",
                "min_int",
                "fits",
                "size",
                "zero",
                "one",
                "ones",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "FStar.UInt8" | "FStar.UInt16" | "FStar.UInt32" | "FStar.UInt64" | "FStar.UInt128" => Some(
            [
                "t",
                "v",
                "uint_to_t",
                "add",
                "sub",
                "mul",
                "div",
                "rem",
                "logand",
                "logxor",
                "logor",
                "lognot",
                "shift_left",
                "shift_right",
                "add_mod",
                "sub_mod",
                "mul_mod",
                "mul_wide",
                "op_Plus_Hat",
                "op_Subtraction_Hat",
                "op_Star_Hat",
                "op_Slash_Hat",
                "op_Percent_Hat",
                "op_Hat_Hat",
                "op_Amp_Hat",
                "op_Bar_Hat",
                "op_Less_Less_Hat",
                "op_Greater_Greater_Hat",
                "op_Equals_Hat",
                "op_Greater_Hat",
                "op_Less_Hat",
                "op_Greater_Equals_Hat",
                "op_Less_Equals_Hat",
                "n",
                "zero",
                "one",
                "ones",
                "eq",
                "gt",
                "gte",
                "lt",
                "lte",
                "to_string",
                "to_string_hex",
                "to_string_hex_pad",
                "eq_mask",
                "gte_mask",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "FStar.SizeT" => Some(
            [
                "t",
                "v",
                "uint_to_t",
                "size_v_inj",
                "add",
                "sub",
                "mul",
                "div",
                "rem",
                "fits",
                "fits_u32",
                "fits_u64",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "FStar.PtrdiffT" => Some(
            ["t", "v", "ptrdiff_v_inj", "add", "sub", "mul", "div", "rem"]
                .iter()
                .cloned()
                .collect(),
        ),

        // ========================================
        // FStar.Math modules
        // ========================================
        "FStar.Math.Lib" => Some(
            [
                "abs",
                "max",
                "min",
                "div",
                "op_Slash",
                "signed_modulo",
                "log_2",
                "powx",
                "pow2",
                "pow2_plus",
                "pow2_minus",
                "arithmetic_shift_right",
                "slash_decr_axiom",
                "slash_star_axiom",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "FStar.Math.Lemmas" => Some(
            [
                // Power of 2 lemmas
                "pow2_lt_compat",
                "pow2_le_compat",
                "pow2_plus",
                "pow2_double_sum",
                "pow2_double_mult",
                // Division/modulo lemmas
                "lemma_div_mod",
                "lemma_mod_lt",
                "lemma_div_lt",
                "lemma_mod_plus",
                "lemma_mod_plus_distr_l",
                "lemma_mod_plus_distr_r",
                "lemma_mod_mod",
                "lemma_mod_add_distr",
                "lemma_mod_sub_distr",
                "lemma_div_plus",
                "lemma_div_mod_plus",
                "lemma_mod_mul_distr_l",
                "lemma_mod_mul_distr_r",
                "lemma_div_lt_nat",
                "lemma_div_le",
                // Multiplication lemmas
                "lemma_mult_lt_left",
                "lemma_mult_lt_right",
                "lemma_mult_le_left",
                "lemma_mult_le_right",
                "swap_mul",
                "paren_mul_left",
                "paren_mul_right",
                // Small values
                "small_mod",
                "small_div",
                // Cancel
                "cancel_mul_div",
                "cancel_mul_mod",
                "multiple_modulo_lemma",
                "multiple_division_lemma",
                // Euclidean division
                "euclidean_division_definition",
                "modulo_range_lemma",
                "modulo_lemma",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        // ========================================
        // FStar.String / FStar.Char
        // ========================================
        "FStar.String" => Some(
            [
                "string",
                "strlen",
                "length",
                "concat",
                "split",
                "substring",
                "index",
                "make",
                "uppercase",
                "lowercase",
                "collect",
                "list_of_string",
                "string_of_list",
                "sub",
                "compare",
                "equal",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "FStar.Char" => Some(
            [
                "char",
                "u32_of_char",
                "char_of_u32",
                "int_of_char",
                "char_of_int",
                "lowercase",
                "uppercase",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        // ========================================
        // FStar.Bytes
        // ========================================
        "FStar.Bytes" => Some(
            [
                "bytes",
                "byte",
                "length",
                "empty_bytes",
                "create",
                "index",
                "get",
                "set",
                "append",
                "op_At_Bar",
                "slice",
                "sub",
                "split",
                "equal",
                "eq",
                "repr",
                "reveal",
                "hide",
                "of_hex",
                "print_bytes",
                "utf8_encode",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        // ========================================
        // FStar Buffer/Memory modules
        // ========================================
        "FStar.Buffer" => Some(
            [
                "buffer",
                "live",
                "modifies",
                "modifies_1",
                "modifies_0",
                "frameOf",
                "as_addr",
                "length",
                "idx",
                "op_Array_Access",
                "op_Array_Assignment",
                "create",
                "createL",
                "rcreate",
                "rcreate_mm",
                "index",
                "upd",
                "blit",
                "fill",
                "sub",
                "offset",
                "lemma_modifies_0_unalloc",
                "lemma_modifies_1_unalloc",
                "modifies_fresh_frame_popped",
                "fresh_frame",
                "pop_frame",
                "push_frame",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "LowStar.Buffer" | "LowStar.Monotonic.Buffer" => Some(
            [
                "buffer",
                "pointer",
                "pointer_or_null",
                "live",
                "freeable",
                "modifies",
                "loc_buffer",
                "loc_none",
                "loc_union",
                "loc_includes",
                "frameOf",
                "as_addr",
                "len",
                "length",
                "index",
                "upd",
                "op_Array_Access",
                "op_Array_Assignment",
                "alloca",
                "alloca_of_list",
                "malloc",
                "free",
                "gcmalloc",
                "create",
                "createL",
                "rcreate_mm",
                "blit",
                "fill",
                "sub",
                "offset",
                "gsub",
                "gsub_zero_length",
                "moffset",
                "modifies_only_not_unused_in",
                "modifies_buffer_from_to_elim",
                "modifies_fresh_frame_popped",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "LowStar.BufferOps" => Some(
            [
                "op_Array_Access",
                "op_Array_Assignment",
                "op_Bang_Star",
                "op_Star_Equals",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "FStar.HyperStack" | "FStar.Monotonic.HyperStack" => Some(
            [
                "mem",
                "live_region",
                "is_stack_region",
                "is_heap_color",
                "frameOf",
                "as_addr",
                "contains",
                "sel",
                "upd",
                "modifies",
                "fresh_region",
                "fresh_frame",
                "poppable",
                "rid",
                "root",
                "tip",
                "get_hmap",
                "get_tip",
                "modifies_one",
                "modifies_ref",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "FStar.HyperStack.ST" | "FStar.Monotonic.HyperStack.ST" => Some(
            [
                "get",
                "recall",
                "witness_p",
                "recall_p",
                "testify",
                "testify_forall",
                "testify_forall_region_contains_pred",
                "push_frame",
                "pop_frame",
                "new_region",
                "new_colored_region",
                "ralloc",
                "ralloc_mm",
                "rfree",
                "op_Bang",
                "op_Colon_Equals",
                "salloc",
                "sfree",
                "is_eternal_region",
                "eternal_region_pred",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        // ========================================
        // FStar.ST / FStar.Ref
        // ========================================
        "FStar.ST" => Some(
            [
                "st_pre",
                "st_post",
                "st_post'",
                "ST",
                "st_return",
                "st_bind",
                "read",
                "write",
                "alloc",
                "op_Bang",
                "op_Colon_Equals",
                "get",
                "recall",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "FStar.Ref" => Some(
            [
                "ref",
                "alloc",
                "read",
                "write",
                "op_Bang",
                "op_Colon_Equals",
                "addr_of",
                "is_mm",
                "frameOf",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "FStar.Heap" => Some(
            [
                "heap",
                "ref",
                "trivial_preorder",
                "alloc",
                "sel",
                "upd",
                "free",
                "contains",
                "addr_of",
                "is_mm",
                "modifies",
                "fresh",
                "equal_dom",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        // ========================================
        // FStar.All / FStar.Exn / FStar.IO
        // ========================================
        "FStar.All" => Some(
            [
                "all_pre",
                "all_post",
                "all_post'",
                "ML",
                "all_return",
                "all_bind",
                "failwith",
                "exit",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "FStar.Exn" => Some(
            [
                "exn_pre",
                "exn_post",
                "exn_post'",
                "EXN",
                "exn_return",
                "exn_bind",
                "raise",
                "try_with",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "FStar.IO" => Some(
            [
                "print_string",
                "print_any",
                "print_uint8",
                "print_int8",
                "print_uint16",
                "print_int16",
                "print_uint32",
                "print_int32",
                "print_uint64",
                "print_int64",
                "print_newline",
                "read_line",
                "debug_print_string",
                "input_line",
                "input_int",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "FStar.Printf" => Some(
            ["sprintf", "printf", "fprintf", "print_string", "arg_type"]
                .iter()
                .cloned()
                .collect(),
        ),

        // ========================================
        // FStar.Tactics modules
        // ========================================
        "FStar.Tactics" | "FStar.Tactics.V2" | "FStar.Tactics.V1" => Some(
            [
                // Tactic monad
                "tactic",
                "TAC",
                "return",
                "bind",
                // Basic combinators
                "fail",
                "try_with",
                "or_else",
                "trytac",
                "trivial",
                "focus",
                "guard",
                "repeat",
                "repeatn",
                "seq",
                // Goal management
                "goals",
                "cur_goal",
                "smt",
                "trefl",
                "qed",
                "dismiss",
                "flip",
                "later",
                "set_goals",
                // Term inspection
                "term",
                "bv",
                "binder",
                "comp",
                "inspect",
                "pack",
                "term_eq",
                "term_to_string",
                // Environment
                "cur_env",
                "top_env",
                "lookup_typ",
                "binders_of_env",
                "vars_of_env",
                // Unification
                "unify",
                "unify_env",
                "unify_guard",
                // Intro/elim
                "intro",
                "intro_rec",
                "intros",
                "revert",
                "revert_all",
                "destruct",
                "elim",
                "apply",
                "apply_lemma",
                "exact",
                "exact_with_ref",
                // Rewriting
                "rewrite",
                "l_to_r",
                "grewrite",
                // Normalization
                "norm",
                "norm_term",
                "normalize",
                "norm_binding_type",
                // Debugging
                "debug",
                "print",
                "dump",
                "fail",
                // Reflection helpers
                "fresh_bv",
                "fresh_binder_named",
                "name_of_bv",
                "inspect_bv",
                "pack_bv",
                "inspect_binder",
                "pack_binder",
                // SMT
                "smt_sync",
                "dup",
                // Proof state
                "ngoals",
                "get_vconfig",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "FStar.Tactics.CanonCommMonoid" => Some(
            [
                "canon_monoid",
                "cm",
                "var",
                "term",
                "const",
                "mult",
                "flatten",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "FStar.Tactics.CanonCommSemiring" => Some(
            [
                "canon_semiring",
                "cr",
                "var",
                "term",
                "const",
                "add",
                "mult",
                "flatten",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        // ========================================
        // FStar.Reflection modules
        // ========================================
        "FStar.Reflection" | "FStar.Reflection.V2" | "FStar.Reflection.V1" => Some(
            [
                // Types
                "term",
                "bv",
                "binder",
                "comp",
                "env",
                "fv",
                "name",
                "ident",
                "univ",
                // Inspection
                "inspect_ln",
                "pack_ln",
                "inspect_bv",
                "pack_bv",
                "inspect_fv",
                "pack_fv",
                "inspect_binder",
                "pack_binder",
                "inspect_comp",
                "pack_comp",
                "inspect_universe",
                "pack_universe",
                // Constructors
                "term_view",
                "Tv_Var",
                "Tv_BVar",
                "Tv_FVar",
                "Tv_App",
                "Tv_Abs",
                "Tv_Arrow",
                "Tv_Type",
                "Tv_Refine",
                "Tv_Const",
                "Tv_Uvar",
                "Tv_Let",
                "Tv_Match",
                "Tv_AscribedT",
                "Tv_AscribedC",
                "Tv_Unknown",
                // Constants
                "C_Unit",
                "C_True",
                "C_False",
                "C_Int",
                "C_String",
                // Computations
                "C_Total",
                "C_Lemma",
                "C_Eff",
                // Utilities
                "term_eq",
                "term_to_string",
                "bv_eq",
                "fv_eq",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "FStar.Reflection.Const" => Some(
            [
                "unit_lid",
                "bool_lid",
                "int_lid",
                "string_lid",
                "true_qn",
                "false_qn",
                "nil_lid",
                "cons_lid",
                "and_qn",
                "or_qn",
                "imp_qn",
                "iff_qn",
                "not_qn",
                "forall_qn",
                "exists_qn",
                "eq2_qn",
                "eq1_qn",
                "lt_qn",
                "lte_qn",
                "gt_qn",
                "gte_qn",
                "add_qn",
                "sub_qn",
                "mul_qn",
                "div_qn",
                "mod_qn",
                "neg_qn",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        // ========================================
        // FStar.Fin / FStar.Vector
        // ========================================
        "FStar.Fin" => Some(
            [
                "fin",
                "in_",
                "find",
                "pigeonhole",
                "to_nat",
                "succ",
                "zero",
                "one",
                "cast",
                "injective",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "FStar.Vector" | "FStar.Vector.Base" => Some(
            [
                "raw",
                "vec",
                "length_t",
                "length",
                "index",
                "init",
                "create",
                "assign",
                "from_list",
                "to_list",
                "map",
                "map2",
                "fold_left",
                "fold_right",
                "append",
                "sub",
                "split",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        // ========================================
        // FStar.BitVector / FStar.BV
        // ========================================
        "FStar.BV" | "FStar.BitVector" => Some(
            [
                "bv_t",
                "bv",
                "length",
                "bvand",
                "bvor",
                "bvxor",
                "bvnot",
                "bvshl",
                "bvshr",
                "bvashr",
                "bvadd",
                "bvsub",
                "bvmul",
                "bvdiv",
                "bvmod",
                "bvult",
                "bvule",
                "bvslt",
                "bvsle",
                "int2bv",
                "bv2int",
                "bvconcat",
                "bvslice",
                "zero",
                "ones",
                "logand_vec",
                "logor_vec",
                "lognot_vec",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        // ========================================
        // FStar.Endianness
        // ========================================
        "FStar.Endianness" => Some(
            [
                "le_to_n",
                "be_to_n",
                "n_to_le",
                "n_to_be",
                "le_of_uint8",
                "be_of_uint8",
                "uint8_of_le",
                "uint8_of_be",
                "le_of_uint16",
                "be_of_uint16",
                "uint16_of_le",
                "uint16_of_be",
                "le_of_uint32",
                "be_of_uint32",
                "uint32_of_le",
                "uint32_of_be",
                "le_of_uint64",
                "be_of_uint64",
                "uint64_of_le",
                "uint64_of_be",
                "seq_uint32_of_le",
                "seq_uint32_of_be",
                "seq_uint64_of_le",
                "seq_uint64_of_be",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        // ========================================
        // FStar.BigOps
        // ========================================
        "FStar.BigOps" => Some(
            [
                "big_and",
                "big_or",
                "big_and'",
                "big_or'",
                "pairwise_and",
                "pairwise_or",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        // ========================================
        // FStar.Order
        // ========================================
        "FStar.Order" => Some(
            [
                "order",
                "Lt",
                "Eq",
                "Gt",
                "compare_int",
                "compare_list",
                "ge",
                "le",
                "gt",
                "lt",
                "eq",
                "lex",
                "order_from_int",
                "int_of_order",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        // ========================================
        // FStar.FunctionalExtensionality
        // ========================================
        "FStar.FunctionalExtensionality" => Some(
            [
                "feq",
                "on",
                "restricted_g_t",
                "restricted_t",
                "on_dom",
                "on_domain",
                "on_domain_g",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "FStar.PredicateExtensionality" => {
            Some(["predicateExtensionality", "peq"].iter().cloned().collect())
        }

        // ========================================
        // FStar.PropositionalExtensionality
        // ========================================
        "FStar.PropositionalExtensionality" => Some(
            [
                "propositional_extensionality",
                "apply_propositional_extensionality",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        // ========================================
        // FStar.WellFounded / FStar.WellFoundedRelation
        // ========================================
        "FStar.WellFounded" => Some(
            [
                "well_founded",
                "acc",
                "accessible",
                "fix_F",
                "fix",
                "well_founded_relation",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "FStar.WellFoundedRelation" => Some(
            [
                "wfr_t",
                "wfr",
                "as_wfr",
                "default_relation",
                "subrelation_wfr",
                "lex_t",
                "lex",
                "inverse_image",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        // ========================================
        // FStar.Calc
        // ========================================
        "FStar.Calc" => Some(
            [
                "calc_finish",
                "calc_init",
                "calc_step",
                "calc_push_impl",
                "calc_trans",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        // ========================================
        // FStar.Range
        // ========================================
        "FStar.Range" => Some(
            [
                "range",
                "mk_range",
                "range_0",
                "file_of_range",
                "start_of_range",
                "end_of_range",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        // ========================================
        // FStar.Monotonic modules
        // ========================================
        "FStar.Monotonic.Witnessed" => Some(
            [
                "witnessed",
                "witness",
                "recall",
                "lemma_witnessed_constant",
                "lemma_witnessed_nested",
                "lemma_witnessed_and",
                "lemma_witnessed_or",
                "lemma_witnessed_impl",
                "lemma_witnessed_forall",
                "lemma_witnessed_exists",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "FStar.Monotonic.Seq" => Some(
            ["seq_t", "grows", "grows_p", "at_most_one", "i_seq", "i_at"]
                .iter()
                .cloned()
                .collect(),
        ),

        "FStar.Monotonic.DependentMap" => Some(
            ["t", "sel", "upd", "grows", "empty", "contains"]
                .iter()
                .cloned()
                .collect(),
        ),

        // ========================================
        // FStar.Integers (generic integer ops)
        // ========================================
        "FStar.Integers" => Some(
            [
                "int_t",
                "v",
                "u",
                "uint_to_t",
                "int_to_t",
                "add",
                "op_Plus_Hat",
                "sub",
                "op_Subtraction_Hat",
                "mul",
                "op_Star_Hat",
                "div",
                "op_Slash_Hat",
                "rem",
                "op_Percent_Hat",
                "logand",
                "op_Amp_Hat",
                "logxor",
                "op_Hat_Hat",
                "logor",
                "op_Bar_Hat",
                "lognot",
                "shift_left",
                "op_Less_Less_Hat",
                "shift_right",
                "op_Greater_Greater_Hat",
                "eq",
                "op_Equals_Hat",
                "lt",
                "op_Less_Hat",
                "lte",
                "op_Less_Equals_Hat",
                "gt",
                "op_Greater_Hat",
                "gte",
                "op_Greater_Equals_Hat",
                "within_bounds",
                "cast",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        // ========================================
        // Lib modules (HACL*/EverCrypt)
        // ========================================
        "Lib.IntTypes" => Some(
            [
                // Type constructors
                "inttype",
                "U1",
                "U8",
                "U16",
                "U32",
                "U64",
                "U128",
                "S8",
                "S16",
                "S32",
                "S64",
                "S128",
                "secrecy_level",
                "SEC",
                "PUB",
                // Types
                "int_t",
                "uint_t",
                "sint_t",
                "pub_int_t",
                "sec_int_t",
                "uint8",
                "uint16",
                "uint32",
                "uint64",
                "uint128",
                "int8",
                "int16",
                "int32",
                "int64",
                "int128",
                "u8",
                "u16",
                "u32",
                "u64",
                "u128",
                "u1",
                "i8",
                "i16",
                "i32",
                "i64",
                "i128",
                "byte",
                "size_t",
                "pub_uint8",
                "pub_uint16",
                "pub_uint32",
                "pub_uint64",
                "pub_uint128",
                // Functions
                "v",
                "mk_int",
                "cast",
                "secret",
                "to_u8",
                "to_u16",
                "to_u32",
                "to_u64",
                "to_u128",
                "add",
                "sub",
                "mul",
                "div",
                "mod",
                "add_mod",
                "sub_mod",
                "mul_mod",
                "incr",
                "decr",
                "logand",
                "logxor",
                "logor",
                "lognot",
                "shift_left",
                "shift_right",
                "rotate_left",
                "rotate_right",
                "eq_mask",
                "lt_mask",
                "gt_mask",
                "lte_mask",
                "gte_mask",
                "op_Plus_Bang",
                "op_Subtraction_Bang",
                "op_Star_Bang",
                "op_Plus_Dot",
                "op_Subtraction_Dot",
                "op_Star_Dot",
                "op_Amp_Dot",
                "op_Hat_Dot",
                "op_Bar_Dot",
                "op_Less_Less_Dot",
                "op_Greater_Greater_Dot",
                "bits",
                "numbytes",
                "max_int",
                "min_int",
                "range",
                "zeros",
                "ones",
                "maxint",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "Lib.Sequence" => Some(
            [
                "seq",
                "lseq",
                "length",
                "index",
                "create",
                "init",
                "createL",
                "of_list",
                "to_list",
                "upd",
                "sub",
                "slice",
                "append",
                "concat",
                "map",
                "map2",
                "for_all",
                "for_all2",
                "repeati",
                "repeat_gen",
                "eq_intro",
                "eq_elim",
                "index_sub",
                "index_map",
                "index_map2",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "Lib.ByteSequence" => Some(
            [
                "bytes",
                "lbytes",
                "byte_t",
                "uint_to_bytes_le",
                "uint_to_bytes_be",
                "uint_from_bytes_le",
                "uint_from_bytes_be",
                "nat_from_bytes_le",
                "nat_from_bytes_be",
                "nat_to_bytes_le",
                "nat_to_bytes_be",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "Lib.Buffer" | "Lib.Memzero0" => Some(
            [
                "buffer",
                "lbuffer",
                "length",
                "live",
                "modifies",
                "loc",
                "loc_none",
                "loc_buffer",
                "loc_union",
                "index",
                "upd",
                "sub",
                "offset",
                "create",
                "createL",
                "alloca",
                "malloc",
                "free",
                "blit",
                "fill",
                "copy",
                "memset",
                "op_Array_Access",
                "op_Array_Assignment",
                "loop",
                "loopi",
                "loop_range",
                "loop_range_all",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "Lib.LoopCombinators" => Some(
            [
                "fixed_a",
                "fixed_i",
                "nat_zero_or_one",
                "repeat",
                "repeat_range",
                "repeat_gen",
                "repeati",
                "repeati_inductive",
                "repeati_blocks",
                "eq_repeat",
                "unfold_repeat",
                "unfold_repeati",
                "repeat_left",
                "repeat_right",
                "repeat_gen_inductive",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "Lib.UpdateMulti" => Some(
            ["mk_update_multi", "update_multi", "update_last", "finish"]
                .iter()
                .cloned()
                .collect(),
        ),

        "Lib.RawIntTypes" => Some(
            [
                "u8_to_UInt8",
                "u16_to_UInt16",
                "u32_to_UInt32",
                "u64_to_UInt64",
                "UInt8_to_u8",
                "UInt16_to_u16",
                "UInt32_to_u32",
                "UInt64_to_u64",
                "size_to_UInt32",
                "size_from_UInt32",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        // ========================================
        // C / LowStar modules
        // ========================================
        "C" | "C.Compat" => Some(
            [
                "exit_success",
                "exit_failure",
                "errno",
                "portable_exit",
                "exit",
                "clock",
                "print_clock_diff",
                "string_t",
                "string_literal",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "C.Loops" | "C.Compat.Loops" => Some(
            [
                "for",
                "for64",
                "while",
                "do_while",
                "interruptible_for",
                "interruptible_while",
                "total_while",
                "total_while_gen",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "C.String" => Some(
            ["t", "v", "strlen", "well_formed", "get", "index"]
                .iter()
                .cloned()
                .collect(),
        ),

        "LowStar.Endianness" => Some(
            [
                "load16_le",
                "load16_be",
                "store16_le",
                "store16_be",
                "load32_le",
                "load32_be",
                "store32_le",
                "store32_be",
                "load64_le",
                "load64_be",
                "store64_le",
                "store64_be",
                "load128_le",
                "load128_be",
                "store128_le",
                "store128_be",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "LowStar.Modifies" => Some(
            [
                "loc",
                "loc_none",
                "loc_buffer",
                "loc_addresses",
                "loc_regions",
                "loc_mreference",
                "loc_freed_mreference",
                "loc_union",
                "loc_includes",
                "loc_disjoint",
                "address_liveness_insensitive_locs",
                "region_liveness_insensitive_locs",
                "modifies",
                "modifies_refl",
                "modifies_trans",
                "modifies_only_live_regions",
                "modifies_only_live_addresses",
                "fresh_frame_modifies",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "LowStar.ImmutableBuffer" => Some(
            [
                "ibuffer",
                "initialized",
                "cpred",
                "recall_contents",
                "witness_contents",
                "igcmalloc",
                "imalloc",
                "ialloca",
                "of_list",
                "createL_global",
                "createL_mglobal",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "LowStar.ConstBuffer" => Some(
            [
                "const_buffer",
                "as_mbuf",
                "as_qbuf",
                "of_buffer",
                "of_ibuffer",
                "length",
                "index",
                "sub",
                "cast",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "LowStar.Printf" => Some(
            [
                "printf",
                "sprintf",
                "snprintf",
                "print_string",
                "print_u8",
                "print_u16",
                "print_u32",
                "print_u64",
                "print_i8",
                "print_i16",
                "print_i32",
                "print_i64",
                "print_bool",
                "print_lmbuffer",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "LowStar.Failure" => Some(
            ["failwith", "unexpected", "unreachable"]
                .iter()
                .cloned()
                .collect(),
        ),

        // ========================================
        // Steel / Pulse memory
        // ========================================
        "Steel.Memory" => Some(
            [
                "mem",
                "slprop",
                "emp",
                "star",
                "pure",
                "points_to",
                "h_exists",
                "h_forall",
                "interp",
                "equiv",
                "frame",
                "intro_emp",
                "star_commutative",
                "star_associative",
                "star_congruence",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "Steel.Effect" | "Steel.Effect.Atomic" => Some(
            [
                "Steel",
                "SteelF",
                "SteelT",
                "SteelAtomicBase",
                "return",
                "bind",
                "subcomp",
                "get",
                "put",
                "read",
                "write",
                "alloc",
                "free",
                "alloc_pt",
                "free_pt",
                "intro_exists",
                "elim_exists",
                "intro_pure",
                "elim_pure",
                "change_slprop",
                "change_equal_slprop",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "Steel.Reference" => Some(
            [
                "ref",
                "pts_to",
                "pts_to_ref",
                "alloc",
                "free",
                "read",
                "write",
                "ghost_ref",
                "ghost_pts_to",
                "ghost_alloc",
                "ghost_free",
                "ghost_read",
                "ghost_write",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "Steel.Array" => Some(
            [
                "array",
                "array_pts_to",
                "array_pts_to'",
                "alloc",
                "free",
                "index",
                "upd",
                "ghost_join",
                "ghost_split",
                "blit",
                "fill",
                "memcpy",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        // ========================================
        // Prims (built-in)
        // ========================================
        "Prims" => Some(
            [
                // Types
                "unit",
                "bool",
                "int",
                "nat",
                "pos",
                "string",
                "prop",
                "squash",
                "l_True",
                "l_False",
                "l_and",
                "l_or",
                "l_imp",
                "l_iff",
                "l_not",
                "l_Forall",
                "l_Exists",
                "c_True",
                "c_False",
                "c_and",
                "c_or",
                "empty",
                "trivial",
                "eq2",
                "equals",
                // Constructors
                "T",
                "Nil",
                "Cons",
                // Operations
                "op_Negation",
                "op_AmpAmp",
                "op_BarBar",
                "op_Equality",
                "op_disEquality",
                "op_LessThanOrEqual",
                "op_LessThan",
                "op_GreaterThanOrEqual",
                "op_GreaterThan",
                "op_Addition",
                "op_Subtraction",
                "op_Multiply",
                "op_Division",
                "op_Modulus",
                "op_Minus",
                "pow2",
                "min",
                "max",
                "abs",
                // Lemmas/attributes
                "pure",
                "admit",
                "admit_any",
                "magic",
                "assume",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        // ========================================
        // FStar.Pure / FStar.Total
        // ========================================
        "FStar.Pure" | "FStar.Pure.Effect" => Some(
            [
                "pure_pre",
                "pure_post",
                "pure_wp",
                "PURE",
                "Pure",
                "pure_return",
                "pure_bind",
                "assert_p",
                "assume_p",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        "FStar.Monotonic.Pure" => Some(
            ["monotonic", "as_pure_wp", "elim_pure_wp_monotonicity"]
                .iter()
                .cloned()
                .collect(),
        ),

        // ========================================
        // FStar extraction/codegen
        // ========================================
        "FStar.Krml.Endianness" => Some(
            [
                "le_to_n",
                "be_to_n",
                "n_to_le",
                "n_to_be",
                "load16_le",
                "load16_be",
                "store16_le",
                "store16_be",
                "load32_le",
                "load32_be",
                "store32_le",
                "store32_be",
                "load64_le",
                "load64_be",
                "store64_le",
                "store64_be",
                "load128_le",
                "load128_be",
                "store128_le",
                "store128_be",
            ]
            .iter()
            .cloned()
            .collect(),
        ),

        // Module not found in database - return None to indicate unknown
        _ => None,
    }
}

/// Check if an open statement is used, considering known module exports.
///
/// This function checks multiple sources of usage:
/// - Qualified module access (e.g., `List.map`)
/// - Unqualified identifiers (lowercase, e.g., `map`, `fold`)
/// - Type constructors (uppercase, e.g., `Some`, `None`, `Inl`)
/// - Operators (e.g., `*` maps to `op_Star`)
///
/// Module aliases are excluded from qualified prefix matching: if
/// `module ST = FStar.HyperStack.ST` exists, then `ST.get()` does not
/// count as evidence that `open FStar.HyperStack.ST` is used, because
/// the `ST` prefix comes from the alias, not the open.
fn is_open_used_with_exports(
    open: &OpenStatement,
    used_identifiers: &HashSet<String>,
    used_type_constructors: &HashSet<String>,
    qualified_uses: &HashSet<String>,
    used_operators: &HashSet<String>,
    aliases: &[ModuleAlias],
) -> bool {
    // Empty selective {} means typeclass scope only - consider used
    if let Some(ref names) = open.selective {
        if names.is_empty() {
            return true;
        }
        // Check if any selectively imported name is used (both lowercase and uppercase)
        return names
            .iter()
            .any(|n| used_identifiers.contains(n) || used_type_constructors.contains(n));
    }

    // Build set of alias names that target this module or overlap with its path
    // components. These prefixes come from aliases, not from the open.
    let alias_names: HashSet<&str> = aliases
        .iter()
        .filter(|a| a.target == open.module_path)
        .map(|a| a.alias.as_str())
        .collect();

    // Check qualified uses like Module.foo, but exclude alias-provided prefixes
    if qualified_uses.contains(&open.module_path) {
        // The full module path is used qualified (e.g., FStar.Seq.length).
        // But an open doesn't provide the module path as a prefix - it provides
        // the module's CONTENTS. So qualified access like FStar.Seq.length
        // works without the open. Skip this check for full path matches.
        // Only count suffixes that are NOT the full path and NOT alias names.
    }

    // Check partial qualified paths (e.g., "List" for "FStar.List.Tot")
    // but exclude prefixes that are provided by module aliases.
    let parts: Vec<&str> = open.module_path.split('.').collect();
    for i in 0..parts.len() {
        let suffix = parts[i..].join(".");
        if qualified_uses.contains(&suffix) && !alias_names.contains(suffix.as_str()) {
            // Also skip the full module path: qualified access with the full path
            // works without an open statement
            if suffix != open.module_path {
                return true;
            }
        }
    }

    // Check known exports
    if let Some(exports) = get_known_exports(&open.module_path) {
        // Check if any exported identifier is used (lowercase names like `map`, `fold`)
        if exports.iter().any(|e| used_identifiers.contains(*e)) {
            return true;
        }

        // Also check type constructors (uppercase like `Some`, `None`, `Inl`)
        if exports.iter().any(|e| used_type_constructors.contains(*e)) {
            return true;
        }

        // Check if any operator internal name matches exports
        if exports.iter().any(|e| used_operators.contains(*e)) {
            return true;
        }

        // We know the exports and none are used - it's unused
        return false;
    }

    // Conservative: if we don't know the exports, assume used
    true
}

/// Result of safety analysis for removing an open statement.
#[derive(Debug, Clone)]
pub struct RemovalSafety {
    /// Confidence level for the removal.
    pub confidence: FixConfidence,
    /// Whether auto-removal is safe.
    pub is_safe: bool,
    /// Reason if removal is not safe.
    pub reason: Option<String>,
    /// Safety level for the fix (Safe, Caution, Unsafe).
    pub safety_level: FixSafetyLevel,
}

impl RemovalSafety {
    /// High confidence, safe to auto-remove.
    /// Module not in KNOWN_EXPORTS (conservative) or selective import.
    fn safe() -> Self {
        Self {
            confidence: FixConfidence::High,
            is_safe: true,
            reason: None,
            safety_level: FixSafetyLevel::Safe,
        }
    }

    /// Medium confidence, suggest but require confirmation.
    /// Module might be used for operators or has complex usage patterns.
    fn medium(reason: impl Into<String>) -> Self {
        Self {
            confidence: FixConfidence::Medium,
            is_safe: true,
            reason: Some(reason.into()),
            safety_level: FixSafetyLevel::Caution,
        }
    }

    /// Low confidence, do not suggest auto-removal.
    /// Module alias exists or RISKY_MODULES list.
    fn low(reason: impl Into<String>) -> Self {
        Self {
            confidence: FixConfidence::Low,
            is_safe: false,
            reason: Some(reason.into()),
            safety_level: FixSafetyLevel::Unsafe,
        }
    }

    /// Never auto-remove (module in NEVER_AUTO_REMOVE whitelist).
    /// Requires --force to apply.
    fn never(reason: impl Into<String>) -> Self {
        Self {
            confidence: FixConfidence::Low,
            is_safe: false,
            reason: Some(reason.into()),
            safety_level: FixSafetyLevel::Unsafe,
        }
    }
}

/// Analyze the safety of removing an open statement.
///
/// This function determines:
/// 1. Whether the module is in the NEVER_AUTO_REMOVE whitelist
/// 2. Whether the module is RISKY (low confidence)
/// 3. Whether we have comprehensive export knowledge
/// 4. Whether operators might be affected
///
/// Returns a `RemovalSafety` indicating confidence and safety.
fn analyze_removal_safety(
    open: &OpenStatement,
    analysis: &OpenAnalysis,
    content: &str,
) -> RemovalSafety {
    let module = &open.module_path;

    // CRITICAL: Never auto-remove modules that provide operators
    if NEVER_AUTO_REMOVE.contains(module.as_str()) {
        return RemovalSafety::never(format!(
            "Module '{}' provides operators or implicit features that are hard to detect statically",
            module
        ));
    }

    // RISKY: These modules have complex usage patterns
    if RISKY_MODULES.contains(module.as_str()) {
        // Even if we think it's unused, be conservative
        return RemovalSafety::low(format!(
            "Module '{}' has complex usage patterns; manual verification recommended",
            module
        ));
    }

    // Check if we have export knowledge for this module
    let has_export_knowledge = get_known_exports(module).is_some();

    // Additional safety checks for operator-providing modules
    let clean_content = strip_comments_and_strings(content);

    // Check for potential operator usage that might be missed
    let potential_operator_issues = check_potential_operator_issues(module, &clean_content);
    if let Some(issue) = potential_operator_issues {
        return RemovalSafety::low(issue);
    }

    // Check for potential type constructor usage that might be missed
    let potential_type_issues = check_potential_type_issues(open, analysis, &clean_content);
    if let Some(issue) = potential_type_issues {
        return RemovalSafety::medium(issue);
    }

    // If we have export knowledge and comprehensive analysis, high confidence
    if has_export_knowledge {
        // Selective opens are safer because we know exactly what was imported
        if open.selective.is_some() {
            return RemovalSafety::safe();
        }

        // Full module opens with known exports - still high confidence
        return RemovalSafety::safe();
    }

    // Unknown module - we can't be sure about exports
    // This shouldn't happen often since is_open_used_with_exports returns true
    // for unknown modules, but handle it defensively
    RemovalSafety::medium(format!(
        "Module '{}' exports are not in the known exports database",
        module
    ))
}

/// Check for potential operator issues that might cause the analysis to miss usage.
fn check_potential_operator_issues(module: &str, clean_content: &str) -> Option<String> {
    // Modules that provide the * operator
    if module.contains("Mul") || module == "FStar.Int" || module.starts_with("FStar.Int") {
        // Check if there's any * usage in the content
        if clean_content.contains('*') {
            return Some(format!(
                "Content contains '*' which may use multiplication from '{}'",
                module
            ));
        }
    }

    // Modules that provide @ operator (list/seq append)
    if module.contains("List") || module.contains("Seq") {
        if clean_content.contains('@') && !clean_content.contains("@|") {
            return Some(format!(
                "Content contains '@' which may use append from '{}'",
                module
            ));
        }
    }

    // Modules that provide @| operator
    if module.contains("Seq") || module.contains("Bytes") {
        if clean_content.contains("@|") {
            return Some(format!(
                "Content contains '@|' which may use seq append from '{}'",
                module
            ));
        }
    }

    // Modules that provide ! and := operators (ref)
    if module.contains("Ref") || module.contains("ST") || module.contains("HyperStack") {
        if clean_content.contains('!') || clean_content.contains(":=") {
            return Some(format!(
                "Content contains '!' or ':=' which may use ref operators from '{}'",
                module
            ));
        }
    }

    // Hat operators (^)
    if module.contains("Int") || module == "FStar.Integers" {
        if clean_content.contains('^') {
            return Some(format!(
                "Content contains '^' operators which may come from '{}'",
                module
            ));
        }
    }

    // Bang operators (!)
    if module == "Lib.IntTypes" || module.starts_with("Lib.") {
        if clean_content.contains("+!")
            || clean_content.contains("-!")
            || clean_content.contains("*!")
        {
            return Some(format!(
                "Content contains '!' operators which may come from '{}'",
                module
            ));
        }
    }

    // Dot operators (.)
    if module == "Lib.IntTypes" || module.starts_with("Lib.") {
        if clean_content.contains("+.")
            || clean_content.contains("-.")
            || clean_content.contains("*.")
        {
            return Some(format!(
                "Content contains '.' operators which may come from '{}'",
                module
            ));
        }
    }

    None
}

/// Check for potential type constructor issues.
fn check_potential_type_issues(
    open: &OpenStatement,
    analysis: &OpenAnalysis,
    clean_content: &str,
) -> Option<String> {
    let module = &open.module_path;

    // Check for common type constructors that might be used
    if let Some(exports) = get_known_exports(module) {
        // Count how many type constructors from this module MIGHT be used
        // (appear in content but weren't detected as actually used)
        let potential_unused: Vec<_> = exports
            .iter()
            .filter(|e| {
                let e_str = (*e).to_string();
                // Type constructors are uppercase
                if e_str.chars().next().map_or(false, |c| c.is_uppercase()) {
                    // Check if it appears in content but wasn't detected
                    clean_content.contains(*e)
                        && !analysis.used_type_constructors.contains(&e_str)
                } else {
                    false
                }
            })
            .collect();

        if !potential_unused.is_empty() && potential_unused.len() <= 3 {
            return Some(format!(
                "Type constructors {:?} appear in content but weren't detected as used",
                potential_unused
            ));
        }
    }

    None
}

/// FST004: Unused opens detection rule.
pub struct UnusedOpensRule;

impl UnusedOpensRule {
    pub fn new() -> Self {
        Self
    }
}

impl Default for UnusedOpensRule {
    fn default() -> Self {
        Self::new()
    }
}

impl Rule for UnusedOpensRule {
    fn code(&self) -> RuleCode {
        RuleCode::FST004
    }

    fn check(&self, file: &PathBuf, content: &str) -> Vec<Diagnostic> {
        let analysis = analyze_opens(content);
        let mut diagnostics = Vec::new();

        for open in &analysis.opens {
            // Use the enhanced check with known exports, type constructors, and operator detection
            if !is_open_used_with_exports(
                open,
                &analysis.used_identifiers,
                &analysis.used_type_constructors,
                &analysis.used_module_prefixes,
                &analysis.used_operators,
                &analysis.aliases,
            ) {
                // Analyze removal safety before creating fix
                let safety = analyze_removal_safety(open, &analysis, content);

                // Create the edit
                let edits = vec![Edit {
                    file: file.clone(),
                    range: Range::new(open.line, 1, open.line + 1, 1),
                    new_text: String::new(),
                }];

                // Create fix with appropriate safety level and metadata
                let fix = if safety.is_safe {
                    Fix::new(
                        format!("Remove unused open `{}`", open.module_path),
                        edits,
                    )
                    .with_confidence(safety.confidence)
                    .with_safety_level(safety.safety_level)
                    .with_reversible(false)  // Removal is not easily reversible
                    .with_requires_review(safety.safety_level != FixSafetyLevel::Safe)
                } else {
                    Fix::unsafe_fix(
                        format!("Remove unused open `{}`", open.module_path),
                        edits,
                        safety.confidence,
                        safety
                            .reason
                            .clone()
                            .unwrap_or_else(|| "Manual verification recommended".to_string()),
                    )
                    .with_safety_level(safety.safety_level)
                    .with_reversible(false)
                    .with_requires_review(true)
                };

                // Build message with safety info
                let message = if safety.is_safe && safety.confidence == FixConfidence::High {
                    format!("Unused open: `{}`", open.module_path)
                } else {
                    let reason = fix.unsafe_reason.as_deref().unwrap_or("low confidence");
                    format!(
                        "Unused open: `{}` [confidence: {}, reason: {}]",
                        open.module_path, fix.confidence, reason
                    )
                };

                diagnostics.push(Diagnostic {
                    rule: RuleCode::FST004,
                    severity: DiagnosticSeverity::Warning,
                    file: file.clone(),
                    range: Range::new(
                        open.line,
                        open.col,
                        open.line,
                        open.col + open.line_text.trim().len(),
                    ),
                    message,
                    fix: Some(fix),
                });
            }
        }

        diagnostics
    }
}

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

    #[test]
    fn test_parse_simple_open() {
        let content = "open FStar.List";
        let opens = parse_opens(content);
        assert_eq!(opens.len(), 1);
        assert_eq!(opens[0].module_path, "FStar.List");
        assert!(opens[0].selective.is_none());
    }

    #[test]
    fn test_parse_selective_open() {
        let content = "open FStar.List { map, filter, fold }";
        let opens = parse_opens(content);
        assert_eq!(opens.len(), 1);
        assert_eq!(opens[0].module_path, "FStar.List");
        assert_eq!(
            opens[0].selective,
            Some(vec![
                "map".to_string(),
                "filter".to_string(),
                "fold".to_string()
            ])
        );
    }

    #[test]
    fn test_parse_multiple_opens() {
        let content = r#"module Test

open FStar.All
open FStar.List
open FStar.Option { Some, None }

val foo : int -> int
"#;
        let opens = parse_opens(content);
        assert_eq!(opens.len(), 3);
        assert_eq!(opens[0].module_path, "FStar.All");
        assert_eq!(opens[1].module_path, "FStar.List");
        assert_eq!(opens[2].module_path, "FStar.Option");
    }

    #[test]
    fn test_parse_module_alias() {
        let content = "module L = FStar.List.Tot";
        let aliases = parse_module_aliases(content);
        assert_eq!(aliases.len(), 1);
        assert_eq!(aliases[0].alias, "L");
        assert_eq!(aliases[0].target, "FStar.List.Tot");
    }

    #[test]
    fn test_accessible_prefixes() {
        let open_stmt = OpenStatement {
            module_path: "FStar.List.Tot".to_string(),
            selective: None,
            line: 1,
            col: 1,
            line_text: "open FStar.List.Tot".to_string(),
        };

        let prefixes = open_stmt.accessible_prefixes();
        assert!(prefixes.contains(&"FStar".to_string()));
        assert!(prefixes.contains(&"FStar.List".to_string()));
        assert!(prefixes.contains(&"FStar.List.Tot".to_string()));
        assert!(prefixes.contains(&"List".to_string()));
        assert!(prefixes.contains(&"List.Tot".to_string()));
        assert!(prefixes.contains(&"Tot".to_string()));
    }

    #[test]
    fn test_extract_used_prefixes() {
        let content = r#"
let x = List.map f xs
let y = FStar.Option.Some 1
"#;
        let prefixes = extract_used_module_prefixes(content);
        assert!(prefixes.contains(&"List".to_string()));
        assert!(prefixes.contains(&"FStar.Option".to_string()));
    }

    #[test]
    fn test_strip_comments() {
        let content = r#"
(* open FStar.Unused *)
let x = List.map (* comment *) f xs
// open Another.Unused
let y = 1
"#;
        let stripped = strip_comments_and_strings(content);
        assert!(!stripped.contains("FStar.Unused"));
        assert!(!stripped.contains("Another.Unused"));
        assert!(stripped.contains("List.map"));
    }

    #[test]
    fn test_selective_open_unused() {
        let content = r#"module Test

open FStar.List { map, filter }

let x = 1
"#;
        let analysis = analyze_opens(content);
        assert_eq!(analysis.opens.len(), 1);

        let open_stmt = &analysis.opens[0];
        // Neither map nor filter are used
        assert!(!is_open_used(open_stmt, &analysis));
    }

    #[test]
    fn test_selective_open_used() {
        let content = r#"module Test

open FStar.List { map, filter }

let x = map f xs
"#;
        let analysis = analyze_opens(content);
        let open_stmt = &analysis.opens[0];
        // map is used
        assert!(is_open_used(open_stmt, &analysis));
    }

    #[test]
    fn test_module_name() {
        let open_stmt = OpenStatement {
            module_path: "FStar.List.Tot.Base".to_string(),
            selective: None,
            line: 1,
            col: 1,
            line_text: "open FStar.List.Tot.Base".to_string(),
        };
        assert_eq!(open_stmt.module_name(), "Base");
    }

    #[test]
    fn test_known_exports_coverage() {
        // Verify key modules are in the database
        assert!(get_known_exports("FStar.Mul").is_some());
        assert!(get_known_exports("FStar.List.Tot").is_some());
        assert!(get_known_exports("FStar.List.Tot.Base").is_some());
        assert!(get_known_exports("FStar.Seq").is_some());
        assert!(get_known_exports("FStar.Seq.Properties").is_some());
        assert!(get_known_exports("FStar.Set").is_some());
        assert!(get_known_exports("FStar.Map").is_some());
        assert!(get_known_exports("FStar.Classical").is_some());
        assert!(get_known_exports("FStar.Ghost").is_some());
        assert!(get_known_exports("FStar.Int32").is_some());
        assert!(get_known_exports("FStar.UInt64").is_some());
        assert!(get_known_exports("FStar.Math.Lemmas").is_some());
        assert!(get_known_exports("FStar.Tactics").is_some());
        assert!(get_known_exports("Lib.IntTypes").is_some());
        assert!(get_known_exports("Prims").is_some());
        assert!(get_known_exports("Steel.Memory").is_some());
        assert!(get_known_exports("LowStar.Buffer").is_some());

        // Verify unknown module returns None
        assert!(get_known_exports("Unknown.Module").is_none());
    }

    #[test]
    fn test_known_exports_contents() {
        // FStar.Mul should have op_Star
        let mul_exports = get_known_exports("FStar.Mul").unwrap();
        assert!(mul_exports.contains("op_Star"));

        // FStar.List.Tot should have common list operations
        let list_exports = get_known_exports("FStar.List.Tot").unwrap();
        assert!(list_exports.contains("length"));
        assert!(list_exports.contains("map"));
        assert!(list_exports.contains("fold_left"));
        assert!(list_exports.contains("filter"));
        assert!(list_exports.contains("append"));

        // Lib.IntTypes should have type aliases
        let int_types = get_known_exports("Lib.IntTypes").unwrap();
        assert!(int_types.contains("uint8"));
        assert!(int_types.contains("u32"));
        assert!(int_types.contains("size_t"));
        assert!(int_types.contains("add"));
        assert!(int_types.contains("logxor"));

        // FStar.Classical should have proof combinators
        let classical = get_known_exports("FStar.Classical").unwrap();
        assert!(classical.contains("forall_intro"));
        assert!(classical.contains("exists_elim"));
        assert!(classical.contains("move_requires"));

        // Prims should have built-in types and operations
        let prims = get_known_exports("Prims").unwrap();
        assert!(prims.contains("unit"));
        assert!(prims.contains("nat"));
        assert!(prims.contains("op_Addition"));
        assert!(prims.contains("admit"));
    }

    #[test]
    fn test_unused_open_with_known_exports() {
        // FStar.Mul opened but op_Star not used
        let content = r#"module Test

open FStar.Mul

let x = 1 + 2
"#;
        let analysis = analyze_opens(content);
        assert_eq!(analysis.opens.len(), 1);

        let used = is_open_used_with_exports(
            &analysis.opens[0],
            &analysis.used_identifiers,
            &analysis.used_type_constructors,
            &analysis.used_module_prefixes,
            &analysis.used_operators,
            &analysis.aliases,
        );
        // op_Star is not used, so it should be unused
        assert!(!used);
    }

    #[test]
    fn test_used_open_with_known_exports() {
        // FStar.Mul opened and op_Star used (via * operator which F* desugars)
        let content = r#"module Test

open FStar.Mul

let x = 2 * 3
"#;
        let analysis = analyze_opens(content);

        // Now with operator extraction, op_Star should be detected from `2 * 3`
        let used = is_open_used_with_exports(
            &analysis.opens[0],
            &analysis.used_identifiers,
            &analysis.used_type_constructors,
            &analysis.used_module_prefixes,
            &analysis.used_operators,
            &analysis.aliases,
        );
        // The * operator is used, so FStar.Mul should be considered used
        assert!(used);
    }

    #[test]
    fn test_operator_extraction() {
        // Test that various operators are correctly extracted
        let content = r#"
let a = x * y
let b = xs @ ys
let c = i +^ j
let d = p +! q
"#;
        let ops = extract_operator_internal_names(content);
        assert!(ops.contains("op_Star"), "Should detect * operator");
        assert!(ops.contains("op_At"), "Should detect @ operator");
        assert!(ops.contains("op_Plus_Hat"), "Should detect +^ operator");
        assert!(ops.contains("op_Plus_Bang"), "Should detect +! operator");
    }

    #[test]
    fn test_let_open_parsing() {
        let content = r#"let check_bound b =
  let open FStar.Mul in
  let open Lib.ByteSequence in
  x * y
"#;
        let let_opens = parse_let_opens(content);
        assert_eq!(let_opens.len(), 2);
        assert_eq!(let_opens[0].module_path, "FStar.Mul");
        assert_eq!(let_opens[1].module_path, "Lib.ByteSequence");
    }

    #[test]
    fn test_analysis_includes_operators() {
        let content = r#"module Test
open FStar.Mul
let product = a * b
"#;
        let analysis = analyze_opens(content);
        assert!(
            analysis.used_operators.contains("op_Star"),
            "Analysis should include op_Star from * usage"
        );
    }

    // =====================================================
    // FALSE NEGATIVE REGRESSION TESTS
    // These tests verify that previously missed unused opens
    // are now correctly detected.
    // =====================================================

    #[test]
    fn test_type_constructor_some_none_detected() {
        // REGRESSION: Previously, type constructors like Some/None were not
        // checked against known exports because they are in used_type_constructors,
        // not used_identifiers. This was a false negative.
        let content = r#"module Test

open FStar.Option

let x : option int = Some 42
let y : option string = None
"#;
        let analysis = analyze_opens(content);
        assert_eq!(analysis.opens.len(), 1);

        // Verify Some and None are captured as type constructors
        assert!(
            analysis.used_type_constructors.contains("Some"),
            "Some should be in used_type_constructors"
        );
        assert!(
            analysis.used_type_constructors.contains("None"),
            "None should be in used_type_constructors"
        );

        // Now test that the open is correctly detected as USED
        let used = is_open_used_with_exports(
            &analysis.opens[0],
            &analysis.used_identifiers,
            &analysis.used_type_constructors,
            &analysis.used_module_prefixes,
            &analysis.used_operators,
            &analysis.aliases,
        );
        assert!(
            used,
            "FStar.Option should be detected as used when Some/None are used"
        );
    }

    #[test]
    fn test_type_constructor_either_detected() {
        // Test that Either's Inl/Inr constructors are detected
        let content = r#"module Test

open FStar.Either

let x : either int string = Inl 42
let y : either int string = Inr "hello"
"#;
        let analysis = analyze_opens(content);
        assert_eq!(analysis.opens.len(), 1);

        // Verify Inl and Inr are captured
        assert!(
            analysis.used_type_constructors.contains("Inl"),
            "Inl should be in used_type_constructors"
        );
        assert!(
            analysis.used_type_constructors.contains("Inr"),
            "Inr should be in used_type_constructors"
        );

        let used = is_open_used_with_exports(
            &analysis.opens[0],
            &analysis.used_identifiers,
            &analysis.used_type_constructors,
            &analysis.used_module_prefixes,
            &analysis.used_operators,
            &analysis.aliases,
        );
        assert!(
            used,
            "FStar.Either should be detected as used when Inl/Inr are used"
        );
    }

    #[test]
    fn test_unused_option_no_constructors() {
        // FStar.Option opened but no Some/None used - should be unused
        let content = r#"module Test

open FStar.Option

let x = 42
"#;
        let analysis = analyze_opens(content);
        assert_eq!(analysis.opens.len(), 1);

        let used = is_open_used_with_exports(
            &analysis.opens[0],
            &analysis.used_identifiers,
            &analysis.used_type_constructors,
            &analysis.used_module_prefixes,
            &analysis.used_operators,
            &analysis.aliases,
        );
        assert!(
            !used,
            "FStar.Option should be detected as UNUSED when no exports are used"
        );
    }

    #[test]
    fn test_selective_open_type_constructors() {
        // Selective open with type constructors - verify they're checked correctly
        let content = r#"module Test

open FStar.Option { Some, None }

let x = Some 42
"#;
        let analysis = analyze_opens(content);
        assert_eq!(analysis.opens.len(), 1);

        // Selective opens check both used_identifiers and used_type_constructors
        let used = is_open_used_with_exports(
            &analysis.opens[0],
            &analysis.used_identifiers,
            &analysis.used_type_constructors,
            &analysis.used_module_prefixes,
            &analysis.used_operators,
            &analysis.aliases,
        );
        assert!(
            used,
            "Selective open with type constructor should be detected as used"
        );
    }

    #[test]
    fn test_selective_open_type_constructors_unused() {
        // Selective open with type constructors that aren't used
        let content = r#"module Test

open FStar.Option { Some, None }

let x = 42
"#;
        let analysis = analyze_opens(content);
        assert_eq!(analysis.opens.len(), 1);

        let used = is_open_used_with_exports(
            &analysis.opens[0],
            &analysis.used_identifiers,
            &analysis.used_type_constructors,
            &analysis.used_module_prefixes,
            &analysis.used_operators,
            &analysis.aliases,
        );
        assert!(
            !used,
            "Selective open with unused type constructors should be UNUSED"
        );
    }

    #[test]
    fn test_type_in_annotation_detected() {
        // Type name used in type annotation
        let content = r#"module Test

open FStar.Option

val my_func : option int -> int
"#;
        let analysis = analyze_opens(content);

        // 'option' is lowercase so it's in used_identifiers
        assert!(
            analysis.used_identifiers.contains("option"),
            "option type should be in used_identifiers"
        );

        let used = is_open_used_with_exports(
            &analysis.opens[0],
            &analysis.used_identifiers,
            &analysis.used_type_constructors,
            &analysis.used_module_prefixes,
            &analysis.used_operators,
            &analysis.aliases,
        );
        assert!(
            used,
            "FStar.Option should be used when 'option' type appears in annotation"
        );
    }

    #[test]
    fn test_seq_type_constructor_detected() {
        // Test Seq type usage
        let content = r#"module Test

open FStar.Seq

let empty_seq : seq int = empty
"#;
        let analysis = analyze_opens(content);

        // Both 'seq' (type) and 'empty' (value) should be detected
        assert!(
            analysis.used_identifiers.contains("seq")
                || analysis.used_identifiers.contains("empty"),
            "seq/empty should be detected"
        );

        let used = is_open_used_with_exports(
            &analysis.opens[0],
            &analysis.used_identifiers,
            &analysis.used_type_constructors,
            &analysis.used_module_prefixes,
            &analysis.used_operators,
            &analysis.aliases,
        );
        assert!(used, "FStar.Seq should be detected as used");
    }

    #[test]
    fn test_effect_names_detected() {
        // Effect names like ST, Tot, Pure in type signatures
        // Note: These are typically provided by FStar.Pervasives which is auto-opened,
        // but other effect modules might be explicitly opened
        let content = r#"module Test

open FStar.ST

val read_ref : ref int -> ST int
"#;
        let analysis = analyze_opens(content);

        // 'ST' is uppercase - should be in type_constructors
        // 'ref' is lowercase - should be in identifiers
        assert!(
            analysis.used_type_constructors.contains("ST")
                || analysis.used_identifiers.contains("ref"),
            "ST or ref should be detected"
        );

        let used = is_open_used_with_exports(
            &analysis.opens[0],
            &analysis.used_identifiers,
            &analysis.used_type_constructors,
            &analysis.used_module_prefixes,
            &analysis.used_operators,
            &analysis.aliases,
        );
        assert!(used, "FStar.ST should be detected as used");
    }

    // =====================================================
    // FALSE NEGATIVE REGRESSION TESTS: Declaration line filtering
    // These tests verify that module alias, friend, and include
    // lines do not make opens appear used.
    // =====================================================

    #[test]
    fn test_module_alias_does_not_make_open_used() {
        // REGRESSION: `module S = FStar.Seq` caused `open FStar.Seq` to appear
        // used because `FStar.Seq` was extracted as a used module prefix from the
        // alias declaration line. The alias works without the open.
        let content = r#"module Test

open FStar.Seq

module S = FStar.Seq

let x = S.empty
"#;
        let analysis = analyze_opens(content);
        assert_eq!(analysis.opens.len(), 1);
        assert_eq!(analysis.opens[0].module_path, "FStar.Seq");

        // FStar.Seq should NOT be in used_module_prefixes from the alias line.
        // Only S.empty uses "S" as a prefix, not "FStar.Seq".
        let used = is_open_used_with_exports(
            &analysis.opens[0],
            &analysis.used_identifiers,
            &analysis.used_type_constructors,
            &analysis.used_module_prefixes,
            &analysis.used_operators,
            &analysis.aliases,
        );
        // The open IS unused: code only uses the alias S, not the open
        assert!(
            !used,
            "open FStar.Seq should be detected as UNUSED when only module alias S is used"
        );
    }

    #[test]
    fn test_module_alias_with_actual_usage_still_detected() {
        // Ensure that if there IS actual usage through the open, it's still detected
        let content = r#"module Test

open FStar.Seq

module S = FStar.Seq

let x = S.empty
let y = length my_seq
"#;
        let analysis = analyze_opens(content);

        let used = is_open_used_with_exports(
            &analysis.opens[0],
            &analysis.used_identifiers,
            &analysis.used_type_constructors,
            &analysis.used_module_prefixes,
            &analysis.used_operators,
            &analysis.aliases,
        );
        // `length` is an export of FStar.Seq and is used unqualified
        assert!(
            used,
            "open FStar.Seq should be used when 'length' is used unqualified"
        );
    }

    #[test]
    fn test_friend_does_not_make_open_used() {
        // REGRESSION: `friend Lib.Sequence` caused qualified prefix extraction
        // to include `Lib.Sequence`, making `open Lib.Sequence` appear used.
        let content = r#"module Test

open Lib.Sequence

friend Lib.Sequence

let x = 42
"#;
        let analysis = analyze_opens(content);
        assert_eq!(analysis.opens.len(), 1);

        let used = is_open_used_with_exports(
            &analysis.opens[0],
            &analysis.used_identifiers,
            &analysis.used_type_constructors,
            &analysis.used_module_prefixes,
            &analysis.used_operators,
            &analysis.aliases,
        );
        assert!(
            !used,
            "open Lib.Sequence should be UNUSED when only friend declaration exists"
        );
    }

    #[test]
    fn test_include_does_not_make_open_used() {
        // `include Module` should not make `open Module` appear used
        let content = r#"module Test

open FStar.List.Tot

include FStar.List.Tot

let x = 42
"#;
        let analysis = analyze_opens(content);
        assert_eq!(analysis.opens.len(), 1);

        let used = is_open_used_with_exports(
            &analysis.opens[0],
            &analysis.used_identifiers,
            &analysis.used_type_constructors,
            &analysis.used_module_prefixes,
            &analysis.used_operators,
            &analysis.aliases,
        );
        assert!(
            !used,
            "open FStar.List.Tot should be UNUSED when only include declaration exists"
        );
    }

    // =====================================================
    // FALSE POSITIVE REGRESSION TESTS: Multi-line comments
    // =====================================================

    #[test]
    fn test_open_inside_multiline_comment_not_parsed() {
        // REGRESSION: Opens inside multi-line block comments were parsed
        // as real opens because parse_opens only checked if the line
        // started with (*
        let content = r#"module Test

(* This module used to use FStar.List:
open FStar.List.Tot
But we removed that dependency *)

let x = 42
"#;
        let opens = parse_opens(content);
        // The open inside the comment should NOT be parsed
        assert_eq!(
            opens.len(),
            0,
            "open inside multi-line block comment should not be parsed"
        );
    }

    #[test]
    fn test_open_after_multiline_comment_parsed() {
        // Opens AFTER a block comment closes should still be parsed
        let content = r#"module Test

(* This is a comment *)
open FStar.List.Tot

let x = map f xs
"#;
        let opens = parse_opens(content);
        assert_eq!(opens.len(), 1);
        assert_eq!(opens[0].module_path, "FStar.List.Tot");
    }

    #[test]
    fn test_nested_multiline_comments() {
        // F* supports nested block comments: (* outer (* inner *) still comment *)
        let content = r#"module Test

(* outer comment
(* nested comment *)
open FStar.Unused
*)

open FStar.List.Tot
let x = map f xs
"#;
        let opens = parse_opens(content);
        assert_eq!(opens.len(), 1, "Only the open after the comment should be parsed");
        assert_eq!(opens[0].module_path, "FStar.List.Tot");
    }

    // =====================================================
    // HACL*-inspired regression tests
    // =====================================================

    #[test]
    fn test_hacl_pattern_st_alias_and_open() {
        // Common HACL* pattern: both open and module alias for FStar.HyperStack.ST
        // The open should only be considered used if its exports are actually
        // used unqualified (like push_frame, pop_frame), NOT because the
        // module alias line references FStar.HyperStack.ST.
        let content = r#"module Test

open FStar.HyperStack.ST

module ST = FStar.HyperStack.ST

let f () =
  let h = ST.get () in
  42
"#;
        let analysis = analyze_opens(content);
        assert_eq!(analysis.opens.len(), 1);

        // ST.get() uses the ALIAS, not the open. The open provides unqualified
        // access to push_frame, pop_frame, etc. Here none of those are used.
        let used = is_open_used_with_exports(
            &analysis.opens[0],
            &analysis.used_identifiers,
            &analysis.used_type_constructors,
            &analysis.used_module_prefixes,
            &analysis.used_operators,
            &analysis.aliases,
        );
        assert!(
            !used,
            "open FStar.HyperStack.ST should be UNUSED when only ST alias is used via ST.get()"
        );
    }

    #[test]
    fn test_hacl_pattern_st_alias_and_open_with_push_pop() {
        // When push_frame/pop_frame ARE used, the open IS needed
        let content = r#"module Test

open FStar.HyperStack.ST

module ST = FStar.HyperStack.ST

let f () =
  push_frame ();
  let h = ST.get () in
  pop_frame ()
"#;
        let analysis = analyze_opens(content);

        let used = is_open_used_with_exports(
            &analysis.opens[0],
            &analysis.used_identifiers,
            &analysis.used_type_constructors,
            &analysis.used_module_prefixes,
            &analysis.used_operators,
            &analysis.aliases,
        );
        assert!(
            used,
            "open FStar.HyperStack.ST should be USED when push_frame/pop_frame are used"
        );
    }

    #[test]
    fn test_is_declaration_line_helper() {
        assert!(is_declaration_line("open FStar.List.Tot"));
        assert!(is_declaration_line("module S = FStar.Seq"));
        assert!(is_declaration_line("friend Lib.Sequence"));
        assert!(is_declaration_line("include FStar.List.Tot"));
        assert!(!is_declaration_line("let x = List.map f xs"));
        assert!(!is_declaration_line("val foo : int -> int"));
        assert!(!is_declaration_line("type t = | A | B"));
    }

    // =====================================================
    // SAFETY FEATURE TESTS
    // These tests verify the conservative safety measures
    // for FST004 autofix functionality.
    // =====================================================

    #[test]
    fn test_never_auto_remove_fstar_mul() {
        // FStar.Mul should NEVER be auto-removed because it provides op_Star
        let content = r#"module Test

open FStar.Mul

let x = 1 + 2
"#;
        let analysis = analyze_opens(content);
        assert_eq!(analysis.opens.len(), 1);

        let safety = analyze_removal_safety(&analysis.opens[0], &analysis, content);
        assert!(
            !safety.is_safe,
            "FStar.Mul should NEVER be marked safe for auto-removal"
        );
        assert_eq!(
            safety.confidence,
            FixConfidence::Low,
            "FStar.Mul should have LOW confidence"
        );
        assert!(
            safety.reason.is_some(),
            "Should have a reason for being unsafe"
        );
    }

    #[test]
    fn test_never_auto_remove_lib_inttypes() {
        // Lib.IntTypes should NEVER be auto-removed
        let content = r#"module Test

open Lib.IntTypes

let x = 42
"#;
        let analysis = analyze_opens(content);
        let safety = analyze_removal_safety(&analysis.opens[0], &analysis, content);

        assert!(
            !safety.is_safe,
            "Lib.IntTypes should NEVER be marked safe for auto-removal"
        );
    }

    #[test]
    fn test_never_auto_remove_fstar_tactics() {
        // FStar.Tactics should NEVER be auto-removed
        let content = r#"module Test

open FStar.Tactics

let x = 42
"#;
        let analysis = analyze_opens(content);
        let safety = analyze_removal_safety(&analysis.opens[0], &analysis, content);

        assert!(
            !safety.is_safe,
            "FStar.Tactics should NEVER be marked safe for auto-removal"
        );
    }

    #[test]
    fn test_risky_module_fstar_classical() {
        // FStar.Classical is RISKY (low confidence)
        let content = r#"module Test

open FStar.Classical

let x = 42
"#;
        let analysis = analyze_opens(content);
        let safety = analyze_removal_safety(&analysis.opens[0], &analysis, content);

        assert!(
            !safety.is_safe || safety.confidence == FixConfidence::Low,
            "FStar.Classical should be risky (not safe or low confidence)"
        );
    }

    #[test]
    fn test_selective_open_is_safer() {
        // Selective opens are safer because we know exactly what was imported
        // Use FStar.Math.Lib which is NOT in RISKY_MODULES
        let content = r#"module Test

open FStar.Math.Lib { abs, max }

let x = 42
"#;
        let analysis = analyze_opens(content);
        assert_eq!(analysis.opens.len(), 1);

        let safety = analyze_removal_safety(&analysis.opens[0], &analysis, content);
        // Selective opens with known exports and not in risky list should be high confidence
        assert!(
            safety.confidence >= FixConfidence::Medium,
            "Selective open should have at least medium confidence"
        );
        assert!(
            safety.is_safe,
            "Selective open of non-risky module should be safe"
        );
    }

    #[test]
    fn test_mul_operator_detected_unsafe() {
        // If * appears in content and module is Mul-related, should be unsafe
        let content = r#"module Test

open FStar.Int32

let x = a * b
"#;
        let analysis = analyze_opens(content);
        let safety = analyze_removal_safety(&analysis.opens[0], &analysis, content);

        // The * operator presence should trigger caution
        assert!(
            safety.confidence <= FixConfidence::Medium
                || safety.reason.is_some()
                || !safety.is_safe,
            "Presence of * should reduce confidence or add reason"
        );
    }

    #[test]
    fn test_append_operator_detected() {
        // @ operator should trigger caution for List modules
        let content = r#"module Test

open FStar.List.Tot

let xs = [1] @ [2]
"#;
        let analysis = analyze_opens(content);
        let safety = analyze_removal_safety(&analysis.opens[0], &analysis, content);

        // Should be risky due to @ operator and RISKY_MODULES list
        assert!(
            !safety.is_safe || safety.confidence <= FixConfidence::Medium,
            "@ operator with List module should be risky"
        );
    }

    #[test]
    fn test_hat_operator_detected() {
        // ^-suffixed operators should trigger caution for Int modules
        let content = r#"module Test

open FStar.UInt32

let x = a +^ b
"#;
        let analysis = analyze_opens(content);

        // +^ should be detected
        assert!(
            analysis.used_operators.contains("op_Plus_Hat"),
            "+^ should be detected as op_Plus_Hat"
        );
    }

    #[test]
    fn test_ref_operators_detected() {
        // ! and := operators should trigger caution for Ref/ST modules
        let content = r#"module Test

open FStar.Ref

let x = !r
let _ = r := 42
"#;
        let analysis = analyze_opens(content);
        let safety = analyze_removal_safety(&analysis.opens[0], &analysis, content);

        // Ref module with ref operators should be risky
        assert!(
            !safety.is_safe || safety.confidence <= FixConfidence::Medium,
            "Ref module with ! and := should be risky"
        );
    }

    #[test]
    fn test_unknown_module_medium_confidence() {
        // Unknown modules should have medium confidence (conservative)
        let content = r#"module Test

open Some.Unknown.Module

let x = 42
"#;
        let analysis = analyze_opens(content);

        // Unknown module returns true from is_open_used_with_exports
        // so it won't even get to safety analysis in normal flow
        // But if it did, it should be medium confidence
        let open_stmt = &analysis.opens[0];
        assert!(get_known_exports(&open_stmt.module_path).is_none());
    }

    #[test]
    fn test_safe_removal_known_unused() {
        // A known module with definitely unused exports should be safe
        let content = r#"module Test

open FStar.Math.Lib

let x = 42
"#;
        let analysis = analyze_opens(content);
        let safety = analyze_removal_safety(&analysis.opens[0], &analysis, content);

        // FStar.Math.Lib is not in NEVER_AUTO_REMOVE or RISKY_MODULES
        // and we have export knowledge, so should be safe
        assert!(
            safety.is_safe && safety.confidence >= FixConfidence::Medium,
            "Known module with no usage should be safe to remove"
        );
    }

    #[test]
    fn test_fix_can_auto_apply_only_high_safe() {
        use super::super::rules::Fix;

        // Test that can_auto_apply requires both high confidence and is_safe
        let edits = vec![];

        let safe_high = Fix::safe("test", edits.clone());
        assert!(safe_high.can_auto_apply(), "High confidence safe fix should auto-apply");

        let safe_medium = Fix::new("test", edits.clone());
        assert!(!safe_medium.can_auto_apply(), "Medium confidence should not auto-apply");

        let unsafe_high = Fix::unsafe_fix("test", edits.clone(), FixConfidence::High, "reason");
        assert!(!unsafe_high.can_auto_apply(), "Unsafe fix should not auto-apply");

        let unsafe_low = Fix::unsafe_fix("test", edits.clone(), FixConfidence::Low, "reason");
        assert!(!unsafe_low.can_auto_apply(), "Unsafe low fix should not auto-apply");
    }

    #[test]
    fn test_whitelists_comprehensive() {
        // Verify key dangerous modules are in NEVER_AUTO_REMOVE
        assert!(NEVER_AUTO_REMOVE.contains("FStar.Mul"));
        assert!(NEVER_AUTO_REMOVE.contains("FStar.Integers"));
        assert!(NEVER_AUTO_REMOVE.contains("Lib.IntTypes"));
        assert!(NEVER_AUTO_REMOVE.contains("LowStar.BufferOps"));
        assert!(NEVER_AUTO_REMOVE.contains("FStar.Tactics"));
        assert!(NEVER_AUTO_REMOVE.contains("FStar.Pervasives"));
        assert!(NEVER_AUTO_REMOVE.contains("Prims"));

        // Verify risky modules are in RISKY_MODULES
        assert!(RISKY_MODULES.contains("FStar.Classical"));
        assert!(RISKY_MODULES.contains("FStar.Ghost"));
        assert!(RISKY_MODULES.contains("FStar.Seq"));
        assert!(RISKY_MODULES.contains("FStar.List.Tot"));
        assert!(RISKY_MODULES.contains("FStar.Ref"));
        assert!(RISKY_MODULES.contains("LowStar.Buffer"));
    }

    #[test]
    fn test_diagnostic_message_includes_safety_info() {
        // The diagnostic message should include safety information for non-safe fixes
        let content = r#"module Test

open FStar.Mul

let x = 1 + 2
"#;
        let rule = UnusedOpensRule::new();
        let path = PathBuf::from("test.fst");
        let diagnostics = rule.check(&path, content);

        // FStar.Mul is unused but in NEVER_AUTO_REMOVE
        // So we should get a diagnostic (but with unsafe fix)
        // Actually, is_open_used_with_exports checks for op_Star which is not used
        // So we should get a diagnostic

        // The check should produce a diagnostic because * is not used
        // But the fix should be marked unsafe

        if !diagnostics.is_empty() {
            let diag = &diagnostics[0];
            assert!(diag.fix.is_some());
            let fix = diag.fix.as_ref().unwrap();
            assert!(
                !fix.is_safe || fix.confidence == FixConfidence::Low,
                "FStar.Mul fix should be marked unsafe or low confidence"
            );
        }
    }

    // =====================================================
    // BRRR-LANG PATTERN TESTS
    // Test patterns commonly found in production F* codebases
    // =====================================================

    #[test]
    fn test_classical_with_forall_intro() {
        // Pattern: FStar.Classical opened for proof combinators
        let content = r#"module Test

open FStar.Classical

let lemma_foo (x:int) : Lemma (x + 0 == x) =
  forall_intro (fun y -> ())
"#;
        let analysis = analyze_opens(content);

        // forall_intro should be detected as used
        assert!(
            analysis.used_identifiers.contains("forall_intro"),
            "forall_intro should be detected"
        );

        let used = is_open_used_with_exports(
            &analysis.opens[0],
            &analysis.used_identifiers,
            &analysis.used_type_constructors,
            &analysis.used_module_prefixes,
            &analysis.used_operators,
            &analysis.aliases,
        );
        assert!(used, "FStar.Classical should be detected as used");
    }

    #[test]
    fn test_ghost_with_reveal_hide() {
        // Pattern: FStar.Ghost for erased values
        let content = r#"module Test

open FStar.Ghost

let f (x: erased int) =
  reveal x + 1
"#;
        let analysis = analyze_opens(content);

        // reveal and erased should be detected
        let used = is_open_used_with_exports(
            &analysis.opens[0],
            &analysis.used_identifiers,
            &analysis.used_type_constructors,
            &analysis.used_module_prefixes,
            &analysis.used_operators,
            &analysis.aliases,
        );
        assert!(used, "FStar.Ghost should be used when reveal/erased appear");
    }

    #[test]
    fn test_squash_pattern() {
        // Pattern: FStar.Squash for squash types
        let content = r#"module Test

open FStar.Squash

let get_proof_wrapper #a (p: squash a) : a =
  get_proof p
"#;
        let analysis = analyze_opens(content);

        let used = is_open_used_with_exports(
            &analysis.opens[0],
            &analysis.used_identifiers,
            &analysis.used_type_constructors,
            &analysis.used_module_prefixes,
            &analysis.used_operators,
            &analysis.aliases,
        );
        assert!(used, "FStar.Squash should be used when squash/get_proof appear");
    }

    #[test]
    fn test_sequence_with_slice() {
        // Pattern: Using Seq functions
        let content = r#"module Test

open FStar.Seq

let take_first (s: seq int) (n: nat{n <= length s}) =
  slice s 0 n
"#;
        let analysis = analyze_opens(content);

        // seq, length, slice should be detected
        let used = is_open_used_with_exports(
            &analysis.opens[0],
            &analysis.used_identifiers,
            &analysis.used_type_constructors,
            &analysis.used_module_prefixes,
            &analysis.used_operators,
            &analysis.aliases,
        );
        assert!(used, "FStar.Seq should be used when seq functions appear");
    }

    #[test]
    fn test_multiple_opens_different_safety() {
        // Test file with multiple opens having different safety levels
        let content = r#"module Test

open FStar.Mul
open FStar.Math.Lib
open FStar.List.Tot

let x = 42
"#;
        let analysis = analyze_opens(content);
        assert_eq!(analysis.opens.len(), 3);

        // FStar.Mul - should be NEVER (in whitelist)
        let mul_safety = analyze_removal_safety(&analysis.opens[0], &analysis, content);
        assert!(!mul_safety.is_safe, "FStar.Mul should be unsafe");

        // FStar.Math.Lib - should be safe (known exports, not in lists)
        let math_safety = analyze_removal_safety(&analysis.opens[1], &analysis, content);
        assert!(math_safety.is_safe, "FStar.Math.Lib should be safe");

        // FStar.List.Tot - should be risky (in RISKY_MODULES)
        let list_safety = analyze_removal_safety(&analysis.opens[2], &analysis, content);
        assert!(
            !list_safety.is_safe || list_safety.confidence == FixConfidence::Low,
            "FStar.List.Tot should be risky"
        );
    }
}