File size: 73,421 Bytes
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ed2d7f
f4952b6
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ed2d7f
 
 
 
db2c7db
 
 
 
 
 
 
f4952b6
 
 
 
 
 
 
 
 
 
 
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ed2d7f
 
 
 
 
 
2a9dc4c
 
 
 
 
 
 
1ed2d7f
 
 
 
 
 
 
 
 
2a9dc4c
 
 
f4952b6
 
 
 
 
 
 
2a9dc4c
 
 
f4952b6
1ed2d7f
 
 
 
f4952b6
1ed2d7f
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ed2d7f
 
 
 
 
 
 
 
 
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ed2d7f
 
 
 
 
 
 
 
 
 
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ed2d7f
 
 
 
 
 
 
 
 
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4952b6
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4952b6
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ed2d7f
 
 
 
 
 
 
 
 
 
2a9dc4c
 
 
 
1ed2d7f
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ed2d7f
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4952b6
 
2a9dc4c
 
f4952b6
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4952b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ed2d7f
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4952b6
2a9dc4c
 
 
 
1ed2d7f
2a9dc4c
 
 
 
 
 
 
1ed2d7f
2a9dc4c
 
 
 
1ed2d7f
 
 
 
 
 
 
2a9dc4c
 
 
1ed2d7f
2a9dc4c
 
 
 
 
 
 
 
f4952b6
2a9dc4c
 
 
 
 
 
 
 
 
 
 
f4952b6
2a9dc4c
 
 
 
 
 
 
 
db2c7db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4952b6
db2c7db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4952b6
db2c7db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4952b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9dc4c
 
 
 
 
 
db2c7db
 
 
f4952b6
 
2a9dc4c
 
 
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
"""Structural rules: where a pattern applies in a real file, and what text it writes.

A pattern in this bundle is not a snippet to paste. It is a predicate over the syntax
tree plus a text transform that has to survive the kernel patcher, so this module does
two things and nothing else: it decides whether a named function is in the shape a
pattern claims to improve, and it builds the exact search and replace pair for it. When
the shape is not there it says why with a code, and that code is what a negative row of
``patterns/pattern_cases.jsonl`` claims, which is what the ``pattern_round_trip`` gate
re-checks by running the rule again.

Four boundaries are stated rather than assumed.

* Offsets. A syntax tree column is a byte offset. Anchors here are built from those
  offsets, so a target file that is not ASCII is refused instead of patched at the wrong
  place, and a file indented with a tab is refused instead of getting spaces mixed into
  one block.
* Endings. The catalog anchors on LF text, so a CRLF target is refused with
  ``CRLF_TARGET``. A hand written edit through the kernel patcher still preserves the
  endings of a CRLF file; that guarantee is the kernel's and is untouched here.
* Shape. A rule refuses the shapes it has not read: a handle that is stored or returned,
  a chain that falls through instead of raising, a check that is not the first statement.
  Refusing is a result, not an error, and a refusal writes nothing.
* Evidence. A rule never runs the code it reads. The lock test it appends to a test file
  is for the test gate of a run to execute, and it is written so that it fails when the
  primary edit did not land. That coupling is the whole reason a companion exists.
"""

from __future__ import annotations

import ast
import keyword
import re
from dataclasses import dataclass
from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union

# Refusal codes. A negative row names one of these and the gate re-runs the rule to check
# that the rule still answers with exactly that code for exactly that target.
MISSING_TARGET_FILE = "MISSING_TARGET_FILE"
NO_SUCH_FUNCTION = "NO_SUCH_FUNCTION"
NOT_A_MODULE_FUNCTION = "NOT_A_MODULE_FUNCTION"
NOT_PARSEABLE = "NOT_PARSEABLE"
NOT_ASCII_TARGET = "NOT_ASCII_TARGET"
TAB_INDENTED_TARGET = "TAB_INDENTED_TARGET"
CRLF_TARGET = "CRLF_TARGET"
NO_TEST_FILE = "NO_TEST_FILE"
NO_TEST_ANCHOR = "NO_TEST_ANCHOR"
AMBIGUOUS_TEST_ANCHOR = "AMBIGUOUS_TEST_ANCHOR"
ALREADY_ANNOTATED = "ALREADY_ANNOTATED"
NOT_A_MUTABLE_DEFAULT = "NOT_A_MUTABLE_DEFAULT"
ANNOTATED_MUTABLE_DEFAULT = "ANNOTATED_MUTABLE_DEFAULT"
GUARD_ALREADY_PRESENT = "GUARD_ALREADY_PRESENT"
NO_DISPATCH_CHAIN = "NO_DISPATCH_CHAIN"
BRANCH_SHAPE_MISMATCH = "BRANCH_SHAPE_MISMATCH"
ALREADY_SCOPED = "ALREADY_SCOPED"
NO_BARE_OPEN = "NO_BARE_OPEN"
HANDLE_ESCAPE = "HANDLE_ESCAPE"
NOT_THE_FIRST_STATEMENT = "NOT_THE_FIRST_STATEMENT"
ASYNC_TARGET = "ASYNC_TARGET"
NON_LITERAL_ASSERT_MESSAGE = "NON_LITERAL_ASSERT_MESSAGE"
INVALID_COMPANION_PATH = "INVALID_COMPANION_PATH"
ANCHOR_OVERLAP = "ANCHOR_OVERLAP"
NO_BARE_EXCEPT = "NO_BARE_EXCEPT"
BARE_EXCEPT_RE_RAISES = "BARE_EXCEPT_RE_RAISES"
EXCEPT_HANDLER_UNREADABLE = "EXCEPT_HANDLER_UNREADABLE"
NO_NONE_COMPARISON = "NO_NONE_COMPARISON"
NONE_COMPARISON_IS_CHAINED = "NONE_COMPARISON_IS_CHAINED"
NO_EMPTY_LEN_CHECK = "NO_EMPTY_LEN_CHECK"
LEN_TARGET_IS_NOT_A_NAME = "LEN_TARGET_IS_NOT_A_NAME"
NO_SUCH_CLASS = "NO_SUCH_CLASS"
NOT_A_MODULE_CLASS = "NOT_A_MODULE_CLASS"
NOT_A_METHOD = "NOT_A_METHOD"
NO_INIT_METHOD = "NO_INIT_METHOD"
INIT_TAKES_MORE_THAN_SELF = "INIT_TAKES_MORE_THAN_SELF"
SUPER_CALL_ALREADY_FIRST = "SUPER_CALL_ALREADY_FIRST"
SUPER_BASES_UNREADABLE = "SUPER_BASES_UNREADABLE"
NO_UNUSED_IMPORT = "NO_UNUSED_IMPORT"
STAR_IMPORT_IN_FILE = "STAR_IMPORT_IN_FILE"
NAME_LISTED_IN_ALL = "NAME_LISTED_IN_ALL"
PACKAGE_FILE_TARGET = "PACKAGE_FILE_TARGET"
IMPORTS_NOT_CONTIGUOUS = "IMPORTS_NOT_CONTIGUOUS"

INDENT = "    "
_MUTABLE_LITERALS = (ast.List, ast.Dict, ast.Set)
_MUTABLE_CALLS = ("list", "dict", "set")


@dataclass(frozen=True)
class Target:
    """One function a caller wants a pattern looked at, read from a workspace."""

    rel_posix: str
    symbol: str
    text: str
    tree: ast.Module
    read: Callable[[str], Optional[str]]


@dataclass(frozen=True)
class Edit:
    """One file the pattern would write, as a search and replace pair."""

    file: str
    search: str
    replace: str
    label: str


@dataclass(frozen=True)
class RuleHit:
    """The pattern applies: ``edits`` is the function change first, the lock test second."""

    rule: str
    target: str
    edits: Tuple[Edit, ...]
    evidence: Tuple[str, ...]
    reason_code: str = ""


@dataclass(frozen=True)
class RuleMiss:
    """The pattern does not apply, with the reason a corpus row is allowed to claim."""

    reason_code: str
    detail: str
    target: str = ""


Outcome = Union[RuleHit, RuleMiss]


def target_label(rel_posix: str, symbol: str) -> str:
    return "%s::%s" % (rel_posix, symbol)


def _miss(rel_posix: str, symbol: str, code: str, detail: str) -> RuleMiss:
    return RuleMiss(reason_code=code, detail=detail, target=target_label(rel_posix, symbol))


def _no_companion(target: Target, companion: Optional[RuleMiss]) -> RuleMiss:
    if companion is not None:
        return companion
    return _miss(target.rel_posix, target.symbol, NO_TEST_FILE, "no lock test could be written")


# ---------------------------------------------------------------------------
# Offsets, so that an anchor is the file and not an impression of it.
# ---------------------------------------------------------------------------


def line_starts(text: str) -> List[int]:
    """Absolute character offset of every line, numbered like the syntax tree."""

    starts = [0]
    for index, char in enumerate(text):
        if char == "\n":
            starts.append(index + 1)
    return starts


def node_span(text: str, starts: Sequence[int], node: ast.AST) -> Tuple[int, int]:
    """Absolute start and end offsets of a node, or (-1, -1) when it has no position."""

    lineno = getattr(node, "lineno", None)
    end_lineno = getattr(node, "end_lineno", None)
    if lineno is None or end_lineno is None or end_lineno > len(starts):
        return -1, -1
    start = starts[lineno - 1] + int(getattr(node, "col_offset", 0))
    end = starts[end_lineno - 1] + int(getattr(node, "end_col_offset", 0))
    if start < 0 or end < start or end > len(text):
        return -1, -1
    return start, end


def segment_of(text: str, starts: Sequence[int], node: ast.AST) -> str:
    """The exact text a node covers in the file it was parsed from."""

    start, end = node_span(text, starts, node)
    if start < 0:
        return ""
    return text[start:end]


@dataclass(frozen=True)
class _Splice:
    start: int
    end: int
    text: str


def apply_splices(text: str, start: int, end: int, splices: Sequence[_Splice]) -> str:
    """Rewrite ``text[start:end]`` out of spans, leaving everything else byte for byte."""

    out: List[str] = []
    cursor = start
    for splice in sorted(splices, key=lambda item: (item.start, item.end)):
        if splice.start < cursor or splice.end > end:
            raise ValueError("a splice does not fit inside the span it belongs to")
        out.append(text[cursor:splice.start])
        out.append(splice.text)
        cursor = splice.end
    out.append(text[cursor:end])
    return "".join(out)


def _shifted(text: str, starts: Sequence[int], node: ast.AST, indent: str) -> str:
    """The text of a statement placed at ``indent``, with its own lines moved with it.

    A slice of a node starts at the first token of its first line and carries the original
    indentation of every line after that, so the first line gets the whole target indent
    and the others get the one level this block is being pushed by.
    """

    raw = segment_of(text, starts, node)
    lines = raw.split("\n")
    moved = [indent + lines[0]]
    for line in lines[1:]:
        moved.append(INDENT + line if line.strip() else line)
    return "\n".join(moved)


def _gap(text: str, start: int, end: int) -> str:
    """The blank lines between two statements, never more than one of them."""

    return "\n\n" if text[start:end].count("\n") > 1 else "\n"


# ---------------------------------------------------------------------------
# Reading a target, and the shapes this module refuses to anchor on.
# ---------------------------------------------------------------------------

_SHAPE_DETAIL = {
    NOT_ASCII_TARGET: "the file is not ASCII, so a byte offset anchor is not trusted here",
    CRLF_TARGET: "the file ends its lines with CRLF and this catalog anchors on LF text",
    TAB_INDENTED_TARGET: "the file indents with a tab and the transform adds space indent",
}


def _shape_rejection(text: str) -> str:
    if not text.isascii():
        return NOT_ASCII_TARGET
    if "\r\n" in text:
        return CRLF_TARGET
    for line in text.split("\n"):
        if line.lstrip(" ").startswith("\t"):
            return TAB_INDENTED_TARGET
    return ""


def open_target(rel_posix: str, symbol: str, read: Callable[[str], Optional[str]]) -> Tuple[Optional[Target], Optional[RuleMiss]]:
    """Read and parse one target, with every refusal a corpus row may claim about it."""

    text = read(rel_posix)
    if text is None:
        return None, _miss(rel_posix, symbol, MISSING_TARGET_FILE, "no such file: '%s'" % rel_posix)
    return open_target_from_text(rel_posix, symbol, text, read)


def open_target_from_text(rel_posix: str, symbol: str, text: str, read: Callable[[str], Optional[str]]) -> Tuple[Optional[Target], Optional[RuleMiss]]:
    """The target for one file already read, with the shape refusal the reader cannot see."""

    code = _shape_rejection(text)
    if code:
        return None, _miss(rel_posix, symbol, code, _SHAPE_DETAIL[code])
    try:
        tree = ast.parse(text)
    except SyntaxError as exc:
        return None, _miss(rel_posix, symbol, NOT_PARSEABLE, "the file does not parse: %s" % exc.msg)
    return open_target_with_tree(rel_posix, symbol, text, tree, read)


def open_target_with_tree(rel_posix: str, symbol: str, text: str, tree: ast.Module, read: Callable[[str], Optional[str]]) -> Tuple[Optional[Target], Optional[RuleMiss]]:
    """The target for a caller that has already read and parsed the file."""

    code = _shape_rejection(text)
    if code:
        return None, _miss(rel_posix, symbol, code, _SHAPE_DETAIL[code])
    return Target(rel_posix=rel_posix, symbol=symbol, text=text, tree=tree, read=read), None


def module_function(target: Target, allow_async: bool = False) -> Tuple[Optional[ast.FunctionDef], Optional[RuleMiss]]:
    """The module level function the target names, or the refusal that says why not.

    A coroutine is a refusal unless the card opted in. A lock test written for a
    coroutine has to wait for it, and only the cards that do that name coroutines
    among their targets; the rest answer ASYNC_TARGET and say so on the card.
    """

    for node in target.tree.body:
        if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == target.symbol:
            if isinstance(node, ast.AsyncFunctionDef) and not allow_async:
                return None, _miss(
                    target.rel_posix,
                    target.symbol,
                    ASYNC_TARGET,
                    "'%s' is a coroutine, and this card writes its lock test for a plain def" % target.symbol,
                )
            return node, None
    for node in ast.walk(target.tree):
        if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == target.symbol:
            return None, _miss(
                target.rel_posix,
                target.symbol,
                NOT_A_MODULE_FUNCTION,
                "'%s' is not a module level function of this file" % target.symbol,
            )
    return None, _miss(
        target.rel_posix,
        target.symbol,
        NO_SUCH_FUNCTION,
        "no function named '%s' in '%s'" % (target.symbol, target.rel_posix),
    )


# ---------------------------------------------------------------------------
# The lock test that goes with a change.
# ---------------------------------------------------------------------------


def test_file_for(rel_posix: str) -> str:
    """The test file this layout pairs with a source file, by name."""

    parts = [part for part in rel_posix.split("/") if part]
    stem = parts[-1][:-3] if parts[-1].endswith(".py") else parts[-1]
    return "tests/test_%s.py" % stem


def import_statement_for(rel_posix: str) -> Tuple[str, str]:
    """The import that reaches a module without running anything, and the alias it binds."""

    parts = [part for part in rel_posix.split("/") if part]
    stem = parts[-1][:-3] if parts[-1].endswith(".py") else parts[-1]
    package = [part for part in parts[:-1] if part != "__init__.py"]
    if package:
        return "from %s import %s" % (".".join(package), stem), stem
    return "import %s" % stem, stem


def _companion_path_is_importable(rel_posix: str) -> bool:
    """True when the lock import for this path binds a module by a plain Python name."""

    parts = [part for part in rel_posix.split("/") if part]
    if not parts or not parts[-1].endswith(".py"):
        return False
    names = [part for part in parts[:-1] if part != "__init__.py"] + [parts[-1][:-3]]
    return all(part.isidentifier() and not keyword.iskeyword(part) for part in names)


def lock_source(
    rel_posix: str,
    test_name: str,
    docstring: str,
    statements: Sequence[str],
    headers: Sequence[str] = (),
) -> str:
    """One test function of ASCII, space indented text: imports, then the checks."""

    import_statement, _alias = import_statement_for(rel_posix)
    lines = ["def test_%s() -> None:" % test_name, '    """%s"""' % docstring, "    import inspect"]
    lines.extend("    %s" % line for line in headers)
    lines.append("")
    lines.append("    %s" % import_statement)
    for statement in statements:
        for line in statement.split("\n"):
            lines.append("    %s" % line if line.strip() else "")
    return "\n".join(lines) + "\n"


def _append_lock(target: Target, test_rel: str, test_name: str, lock_text: str) -> Tuple[Optional[Edit], Optional[RuleMiss]]:
    """Append one test function after the last test function of a test file."""

    text = target.read(test_rel)
    if text is None:
        return None, _miss(test_rel, target.symbol, NO_TEST_FILE, "no test file: '%s'" % test_rel)
    code = _shape_rejection(text)
    if code:
        return None, _miss(test_rel, target.symbol, code, "the test file: %s" % _SHAPE_DETAIL[code])
    if not _companion_path_is_importable(target.rel_posix):
        return None, _miss(
            test_rel,
            target.symbol,
            INVALID_COMPANION_PATH,
            "the module path of '%s' has a part that is not a plain Python identifier, "
            "so no import in a lock test could reach it" % target.rel_posix,
        )
    try:
        tree = ast.parse(text)
    except SyntaxError as exc:
        return None, _miss(test_rel, target.symbol, NOT_PARSEABLE, "the test file does not parse: %s" % exc.msg)
    last: Optional[ast.FunctionDef] = None
    for node in tree.body:
        if isinstance(node, ast.FunctionDef) and node.name.startswith("test_"):
            last = node
    if last is None:
        return None, _miss(test_rel, target.symbol, NO_TEST_ANCHOR, "no top level test function to append after")
    anchor = segment_of(text, line_starts(text), last)
    if not anchor:
        return None, _miss(test_rel, target.symbol, NO_TEST_ANCHOR, "no text for the anchor of the last test")
    times = text.count(anchor)
    if times != 1:
        return None, _miss(
            test_rel,
            target.symbol,
            AMBIGUOUS_TEST_ANCHOR,
            "the anchor text appears %d times in '%s'" % (times, test_rel),
        )
    return (
        Edit(
            file=test_rel,
            search=anchor,
            replace=anchor.rstrip("\n") + "\n\n\n" + lock_text,
            label="lock test 'test_%s' appended after '%s'" % (test_name, last.name),
        ),
        None,
    )


def _hit(rule: str, target: Target, edit: Edit, companion: Edit, evidence: Sequence[str]) -> RuleHit:
    return RuleHit(
        rule=rule,
        target=target_label(target.rel_posix, target.symbol),
        edits=(edit, companion),
        evidence=tuple(evidence),
    )


def _rewrite_function(target: Target, starts: Sequence[int], function: ast.FunctionDef, splices: Sequence[_Splice], label: str) -> Edit:
    start, end = node_span(target.text, starts, function)
    return Edit(
        file=target.rel_posix,
        search=target.text[start:end],
        replace=apply_splices(target.text, start, end, splices),
        label=label,
    )


def _parameters(function: ast.FunctionDef) -> List[ast.arg]:
    return list(function.args.posonlyargs) + list(function.args.args) + list(function.args.kwonlyargs)


def _is_string_statement(statement: ast.stmt) -> bool:
    """A statement that is one string literal: the shape of a docstring."""

    return (
        isinstance(statement, ast.Expr)
        and isinstance(statement.value, ast.Constant)
        and isinstance(statement.value.value, str)
    )


def _defaults_by_name(function: ast.FunctionDef) -> Dict[str, ast.expr]:
    """Map each plain parameter to the default expression it carries, when it has one."""

    positional = list(function.args.posonlyargs) + list(function.args.args)
    defaults: Dict[str, ast.expr] = {}
    offset = len(positional) - len(function.args.defaults)
    for index, argument in enumerate(positional):
        position = index - offset
        if position >= 0:
            defaults[argument.arg] = function.args.defaults[position]
    for argument, default in zip(function.args.kwonlyargs, function.args.kw_defaults):
        if default is not None:
            defaults[argument.arg] = default
    return defaults


# ---------------------------------------------------------------------------
# Rule 1: write down the type a literal default already states.
# ---------------------------------------------------------------------------


def _literal_type(node: ast.expr) -> Optional[str]:
    if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.UAdd, ast.USub)):
        return _literal_type(node.operand)
    if not isinstance(node, ast.Constant):
        return None
    value = node.value
    if isinstance(value, bool):
        return "bool"
    if isinstance(value, int):
        return "int"
    if isinstance(value, float):
        return "float"
    if isinstance(value, str):
        return "str"
    return None


def rule_annotate_literal_defaults(target: Target) -> Outcome:
    """Annotate a parameter with the type of the literal default it already carries.

    A parameter whose default is ``None`` is left alone on purpose: the honest annotation
    for it is an Optional, and that needs an import this transform will not add.
    """

    function, miss = module_function(target, allow_async=True)
    if function is None:
        return miss
    assert function is not None
    starts = line_starts(target.text)
    annotated = {argument.arg for argument in _parameters(function) if argument.annotation is not None}
    defaults = _defaults_by_name(function)
    position_of = {argument.arg: argument for argument in _parameters(function)}

    splices: List[_Splice] = []
    touched: List[Tuple[str, str, str]] = []
    for name in sorted(defaults):
        if name in annotated:
            continue
        inferred = _literal_type(defaults[name])
        if inferred is None:
            continue
        argument = position_of[name]
        name_end = starts[argument.lineno - 1] + argument.col_offset + len(argument.arg)
        default_start, _default_end = node_span(target.text, starts, defaults[name])
        splices.append(_Splice(start=name_end, end=default_start, text=": %s = " % inferred))
        literal = repr(defaults[name].value) if isinstance(defaults[name], ast.Constant) else segment_of(target.text, starts, defaults[name])
        touched.append((name, inferred, literal))
    if not splices:
        return _miss(
            target.rel_posix,
            target.symbol,
            ALREADY_ANNOTATED,
            "no parameter of '%s' carries a literal default without an annotation" % target.symbol,
        )

    alias = import_statement_for(target.rel_posix)[1]
    statements = ["parameters = inspect.signature(%s.%s).parameters" % (alias, target.symbol)]
    for name, inferred, literal in touched:
        statements.append("assert parameters[%r].annotation is %s" % (name, inferred))
        statements.append("assert parameters[%r].default == %s" % (name, literal))
    test_name = "%s_parameters_keep_their_defaults" % target.symbol
    lock = lock_source(
        target.rel_posix,
        test_name,
        "Lock the annotations this pattern added and the defaults it had to leave alone.",
        statements,
    )
    companion, companion_miss = _append_lock(target, test_file_for(target.rel_posix), test_name, lock)
    if companion is None:
        return _no_companion(target, companion_miss)
    evidence = tuple("parameter '%s' takes its type from its own default %s" % (name, literal) for name, _inferred, literal in touched)
    return _hit(
        "annotate-literal-defaults",
        target,
        _rewrite_function(target, starts, function, splices, "signature of '%s'" % target.symbol),
        companion,
        evidence,
    )


# ---------------------------------------------------------------------------
# Rule 2: a mutable default stops being shared.
# ---------------------------------------------------------------------------


def _is_mutable_default(node: ast.expr) -> bool:
    if isinstance(node, _MUTABLE_LITERALS):
        return True
    return (
        isinstance(node, ast.Call)
        and isinstance(node.func, ast.Name)
        and node.func.id in _MUTABLE_CALLS
        and not node.args
        and not node.keywords
    )


def rule_mutable_default_to_none(target: Target) -> Outcome:
    """Replace a mutable default with ``None`` and rebuild the value inside the call.

    This is a behaviour change by design, and the only one in the catalog: the default
    stops being shared between calls. The guard reuses the literal that was written as
    the default, so the value each call starts from is the one the author wrote.
    """

    function, miss = module_function(target, allow_async=True)
    if function is None:
        return miss
    assert function is not None
    starts = line_starts(target.text)
    named = {argument.arg: argument for argument in _parameters(function)}
    mutable = {name: node for name, node in _defaults_by_name(function).items() if _is_mutable_default(node)}
    if not mutable:
        return _miss(
            target.rel_posix,
            target.symbol,
            NOT_A_MUTABLE_DEFAULT,
            "no default of '%s' is a list, dict or set, so there is nothing shared to break" % target.symbol,
        )
    for name in sorted(mutable):
        if named[name].annotation is not None:
            return _miss(
                target.rel_posix,
                target.symbol,
                ANNOTATED_MUTABLE_DEFAULT,
                "parameter '%s' of '%s' carries an annotation this rule would have to widen" % (name, target.symbol),
            )

    # The guard goes below a docstring, never above it: a guard inserted before the
    # leading string statement would take the docstring of the function away.
    head = 1 if _is_string_statement(function.body[0]) else 0
    if head < len(function.body):
        body_start = starts[function.body[head].lineno - 1]
        guard_lead, guard_trail = "", "\n"
    else:
        # A body of nothing but a docstring: the guard takes its own line below it.
        body_start = starts[function.body[-1].end_lineno - 1] + function.body[-1].end_col_offset
        guard_lead, guard_trail = "\n", ""
    guard_indent = " " * function.body[0].col_offset
    for name in sorted(mutable):
        literal = segment_of(target.text, starts, mutable[name])
        guard = "%sif %s is None:\n%s%s%s = %s\n" % (guard_indent, name, guard_indent, INDENT, name, literal)
        if guard_trail and target.text[body_start:body_start + len(guard)] == guard:
            return _miss(
                target.rel_posix,
                target.symbol,
                GUARD_ALREADY_PRESENT,
                "'%s' already rebuilds '%s' on its first line" % (target.symbol, name),
            )

    splices: List[_Splice] = []
    for name in sorted(mutable):
        start, end = node_span(target.text, starts, mutable[name])
        splices.append(_Splice(start=start, end=end, text="None"))
    for name in sorted(mutable):
        literal = segment_of(target.text, starts, mutable[name])
        splices.append(
            _Splice(
                start=body_start,
                end=body_start,
                text="%s%sif %s is None:\n%s%s%s = %s%s"
                % (guard_lead, guard_indent, name, guard_indent, INDENT, name, literal, guard_trail),
            )
        )

    alias = import_statement_for(target.rel_posix)[1]
    statements = [
        "signature = inspect.signature(%s.%s)" % (alias, target.symbol),
        "source = inspect.getsource(%s.%s)" % (alias, target.symbol),
    ]
    for name in sorted(mutable):
        statements.append("assert signature.parameters[%r].default is None" % name)
        statements.append("assert 'if %s is None:' in source" % name)
    test_name = "%s_has_no_shared_default" % target.symbol
    lock = lock_source(
        target.rel_posix,
        test_name,
        "Lock the default this pattern unshared, the guard that replaced it, and the call that no longer shares state.",
        statements
        + [
            "first = %s" % _run_call(function, alias, target.symbol, _probe_arguments(function, mutable, "alpha")),
            "second = %s" % _run_call(function, alias, target.symbol, _probe_arguments(function, mutable, "beta")),
            "assert first != second",
        ],
        headers=_lock_headers(function),
    )
    companion, companion_miss = _append_lock(target, test_file_for(target.rel_posix), test_name, lock)
    if companion is None:
        return _no_companion(target, companion_miss)
    evidence = tuple("the default of '%s' is a value every call would share" % name for name in sorted(mutable))
    return _hit(
        "mutable-default-to-none",
        target,
        _rewrite_function(target, starts, function, splices, "shared default of '%s'" % target.symbol),
        companion,
        evidence,
    )


def _probe_arguments(function: ast.FunctionDef, mutable: Dict[str, ast.expr], word: str) -> str:
    """Arguments of one call that reaches the guard, carrying ``word`` for the rest.

    These values are placeholders, not claims about the domain. They differ between the
    two calls of the lock, so a default shared between calls cannot pass it, and the
    round trip gate runs the lock before it believes a pattern applies anywhere.
    """

    needed = [
        argument.arg
        for argument in function.args.args
        if argument.arg not in mutable and argument.arg not in _defaults_by_name(function)
    ]
    return ", ".join(repr(word) for _ in needed)


def _run_call(function: ast.FunctionDef, alias: str, symbol: str, arguments: str) -> str:
    """One lock-test call of the target: straight for a def, through asyncio for a coroutine."""

    call = "%s.%s(%s)" % (alias, symbol, arguments)
    if isinstance(function, ast.AsyncFunctionDef):
        return "asyncio.run(%s)" % call
    return call


def _lock_headers(function: ast.FunctionDef) -> Tuple[str, ...]:
    """The extra imports a lock test needs when its target is a coroutine."""

    if isinstance(function, ast.AsyncFunctionDef):
        return ("import asyncio",)
    return ()


# ---------------------------------------------------------------------------
# Rule 3: an equality chain that returns calls becomes a registry.
# ---------------------------------------------------------------------------


def _refusal_name(node: ast.Raise) -> str:
    """The exception type a raise statement names, with or without its arguments."""

    if isinstance(node.exc, ast.Name):
        return node.exc.id
    if isinstance(node.exc, ast.Call) and isinstance(node.exc.func, ast.Name):
        return node.exc.func.id
    return ""


def _chain_branches(node: ast.If) -> Optional[Tuple[List[Tuple[str, str, List[str]]], ast.Raise]]:
    """Read an if or elif chain of ``name == literal`` tests that each return one call.

    Every branch has to take exactly the same arguments and the chain has to end by
    raising: a chain that falls through returns something a registry would not, and this
    rule does not guess what the fall through was meant to produce.
    """

    branches: List[Tuple[str, str, List[str]]] = []
    current: Optional[ast.If] = node
    shared: Optional[List[str]] = None
    while current is not None:
        test = current.test
        if not isinstance(test, ast.Compare) or len(test.ops) != 1 or not isinstance(test.ops[0], ast.Eq):
            return None
        if not isinstance(test.left, ast.Name) or len(test.comparators) != 1:
            return None
        key = test.comparators[0]
        if not isinstance(key, ast.Constant) or not isinstance(key.value, str):
            return None
        if len(current.body) != 1 or not isinstance(current.body[0], ast.Return) or current.body[0].value is None:
            return None
        value = current.body[0].value
        if not isinstance(value, ast.Call) or not isinstance(value.func, ast.Name) or value.keywords:
            return None
        arguments = [argument.id for argument in value.args if isinstance(argument, ast.Name)]
        if len(arguments) != len(value.args):
            return None
        if shared is None:
            shared = arguments
        elif shared != arguments:
            return None
        branches.append((str(key.value), value.func.id, arguments))
        if len(current.orelse) != 1:
            return None
        follower = current.orelse[0]
        if isinstance(follower, ast.If):
            current = follower
            continue
        if isinstance(follower, ast.Raise) and _refusal_name(follower) and not follower.cause:
            return branches, follower
        return None
    return None


def _module_level_names(tree: ast.Module) -> set:
    """Names a caller reaches as an attribute of this module, read from its top level."""

    names: set = set()
    for node in tree.body:
        if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
            names.add(node.name)
        elif isinstance(node, ast.Assign):
            names.update(target.id for target in node.targets if isinstance(target, ast.Name))
        elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
            names.add(node.target.id)
        elif isinstance(node, (ast.Import, ast.ImportFrom)):
            for alias in node.names:
                names.add(alias.asname or alias.name.split(".")[0])
    return names


def rule_chain_to_registry(target: Target) -> Outcome:
    """Turn a chain of ``kind == literal`` returns into a dictionary and one lookup."""

    function, miss = module_function(target)
    if function is None:
        return miss
    assert function is not None
    starts = line_starts(target.text)
    if len(function.body) != 1 or not isinstance(function.body[0], ast.If):
        return _miss(target.rel_posix, target.symbol, NO_DISPATCH_CHAIN, "the body of '%s' is not one if or elif chain" % target.symbol)
    chain = function.body[0]
    read = _chain_branches(chain)
    if read is None:
        return _miss(
            target.rel_posix,
            target.symbol,
            BRANCH_SHAPE_MISMATCH,
            "the chain in '%s' tests more than one name against text literals, its branches do not "
            "take the same arguments, or its last branch does not raise" % target.symbol,
        )
    branches, tail = read
    keys = [key for key, _handler, _arguments in branches]
    if len(set(keys)) != len(keys):
        return _miss(target.rel_posix, target.symbol, BRANCH_SHAPE_MISMATCH, "two branches of '%s' test the same literal" % target.symbol)
    assert isinstance(chain.test, ast.Compare) and isinstance(chain.test.left, ast.Name)
    subject = chain.test.left.id
    if subject not in {argument.arg for argument in function.args.args + function.args.posonlyargs}:
        return _miss(target.rel_posix, target.symbol, BRANCH_SHAPE_MISMATCH, "'%s' is compared but is not a parameter" % subject)
    reachable = _module_level_names(target.tree)
    parameters = {argument.arg for argument in function.args.args}
    if function.args.vararg or function.args.kwarg or function.args.kwonlyargs or function.args.posonlyargs:
        return _miss(
            target.rel_posix,
            target.symbol,
            BRANCH_SHAPE_MISMATCH,
            "'%s' takes arguments this catalog does not know how to pass, so no lock could compare the answers" % target.symbol,
        )
    for _key, _handler, arguments in branches:
        if not set(arguments) <= parameters:
            return _miss(
                target.rel_posix,
                target.symbol,
                BRANCH_SHAPE_MISMATCH,
                "a branch of '%s' passes something that is not a plain parameter of the chain" % target.symbol,
            )
    for _key, handler, _arguments in branches:
        if handler not in reachable:
            return _miss(
                target.rel_posix,
                target.symbol,
                BRANCH_SHAPE_MISMATCH,
                "a branch of '%s' returns '%s', which is not a name of this module, so no lock could compare the answers"
                % (target.symbol, handler),
            )

    raise_text = "raise " + segment_of(target.text, starts, tail.exc)

    indent = " " * chain.col_offset
    entries = ", ".join('"%s": %s' % (key, handler) for key, handler, _arguments in branches)
    arguments = ", ".join(branches[0][2])
    block = (
        "handlers = {%s}\n" % entries
        + "%shandled = handlers.get(%s)\n" % (indent, subject)
        + "%sif handled is None:\n" % indent
        + "%s%s%s\n" % (indent, INDENT, raise_text)
        + "%sreturn handled(%s)" % (indent, arguments)
    )
    start, end = node_span(target.text, starts, chain)
    edit = _rewrite_function(target, starts, function, [_Splice(start=start, end=end, text=block)], "dispatch registry of '%s'" % target.symbol)

    alias = import_statement_for(target.rel_posix)[1]
    statements = ["source = inspect.getsource(%s.%s)" % (alias, target.symbol)]
    statements.append("assert 'handlers = {' in source")
    for key, handler, _arguments in branches:
        statements.append('assert \'"%s": %s\' in source' % (key, handler))
    statements.append("assert 'handlers.get(%s)' in source" % subject)
    statements.append("assert 'elif' not in source")
    for key, handler, arguments in branches:
        statements.append(
            "assert %s.%s(%s) == %s.%s(%s)"
            % (alias, target.symbol, _call(function, _values(function, key)), alias, handler, _call_for(function, arguments, _values(function, key)))
        )
    refusal = _refusal_name(tail)
    statements.append(
        "\n".join(
            (
                "try:",
                "    %s.%s(%s)" % (alias, target.symbol, _call(function, _values(function, "~no such kind~"))),
                "except %s:" % refusal,
                "    pass",
                "else:",
                "    raise AssertionError('%s accepted a kind no branch carries')" % target.symbol,
            )
        )
    )
    test_name = "%s_dispatches_through_a_registry" % target.symbol
    lock = lock_source(
        target.rel_posix,
        test_name,
        "Lock the registry the chain became, and the answers the chain used to give.",
        statements,
    )
    companion, companion_miss = _append_lock(target, test_file_for(target.rel_posix), test_name, lock)
    if companion is None:
        return _no_companion(target, companion_miss)
    evidence = tuple("the branch for '%s' returns %s" % (key, handler) for key, handler, _arguments in branches)
    return _hit("chain-to-registry", target, edit, companion, evidence)


def _chain_subject(function: ast.FunctionDef) -> str:
    """The name every branch of the chain is compared against."""

    first = function.body[0]
    if isinstance(first, ast.If) and isinstance(first.test, ast.Compare) and isinstance(first.test.left, ast.Name):
        return first.test.left.id
    return ""


def _values(function: ast.FunctionDef, kind: str) -> Dict[str, str]:
    """One literal per parameter: the tested name carries ``kind``, the rest carry a placeholder.

    The placeholder says nothing about the domain; it only has to be a value the handler
    accepts without complaint. The round trip gate runs the call, so a target where a
    placeholder is not accepted is a target this catalog does not claim.
    """

    subject = _chain_subject(function)
    return {argument.arg: (repr(kind) if argument.arg == subject else '""') for argument in function.args.args}


def _call(function: ast.FunctionDef, values: Dict[str, str]) -> str:
    return ", ".join(values[argument.arg] for argument in function.args.args)


def _call_for(function: ast.FunctionDef, names: Sequence[str], values: Dict[str, str]) -> str:
    return ", ".join(values[name] for name in names)


# ---------------------------------------------------------------------------
# Rule 4: a handle opened by hand gets a scope.
# ---------------------------------------------------------------------------


def _open_call(node: ast.AST) -> Optional[ast.Call]:
    if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "open" and node.args:
        return node
    return None


def _closes_handle(statement: ast.stmt, handle: str) -> bool:
    return (
        isinstance(statement, ast.Expr)
        and isinstance(statement.value, ast.Call)
        and isinstance(statement.value.func, ast.Attribute)
        and statement.value.func.attr == "close"
        and isinstance(statement.value.func.value, ast.Name)
        and statement.value.func.value.id == handle
        and not statement.value.args
    )


def rule_open_to_context_manager(target: Target) -> Outcome:
    """Give a hand opened file a ``with`` scope and drop the close it makes redundant.

    The handle may only be used by statements in the run of lines below the assignment. A
    handle that is returned, stored in another name, or used above the assignment escapes
    the scope this rule can build, and the rule says so instead of narrowing a lifetime
    quietly.
    """

    function, miss = module_function(target)
    if function is None:
        return miss
    assert function is not None
    starts = line_starts(target.text)

    for node in ast.walk(function):
        if isinstance(node, ast.With):
            for item in node.items:
                if _open_call(item.context_expr) is not None:
                    return _miss(
                        target.rel_posix,
                        target.symbol,
                        ALREADY_SCOPED,
                        "'%s' already opens its handle inside a with block" % target.symbol,
                    )

    position = None
    handle = ""
    opened: Optional[ast.Call] = None
    for index, statement in enumerate(function.body):
        if (
            isinstance(statement, ast.Assign)
            and len(statement.targets) == 1
            and isinstance(statement.targets[0], ast.Name)
            and _open_call(statement.value) is not None
        ):
            position = index
            handle = statement.targets[0].id
            opened = _open_call(statement.value)
            break
    if position is None or opened is None:
        return _miss(target.rel_posix, target.symbol, NO_BARE_OPEN, "'%s' opens no handle into a plain name" % target.symbol)

    def uses(node: ast.AST) -> bool:
        return any(isinstance(item, ast.Name) and item.id == handle for item in ast.walk(node))

    if any(uses(statement) for statement in function.body[:position]):
        return _miss(target.rel_posix, target.symbol, HANDLE_ESCAPE, "'%s' is used before it is opened" % handle)

    block: List[ast.stmt] = [function.body[position]]
    for statement in function.body[position + 1:]:
        if not uses(statement):
            break
        block.append(statement)
    last_use = max(index for index, statement in enumerate(function.body) if uses(statement))
    if last_use > position + len(block) - 1:
        return _miss(target.rel_posix, target.symbol, HANDLE_ESCAPE, "'%s' is used after the run this rule can scope" % handle)

    for statement in block[1:]:
        if isinstance(statement, ast.Return):
            return _miss(target.rel_posix, target.symbol, HANDLE_ESCAPE, "'%s' is used by a return, which outlives the scope" % handle)
        if isinstance(statement, ast.Assign) and any(isinstance(item, ast.Name) and item.id == handle for item in ast.walk(statement.value)):
            if isinstance(statement.value, ast.Name):
                return _miss(target.rel_posix, target.symbol, HANDLE_ESCAPE, "'%s' is stored in another name" % handle)
        elif not isinstance(statement, (ast.Assign, ast.Expr)):
            return _miss(
                target.rel_posix,
                target.symbol,
                HANDLE_ESCAPE,
                "a %s statement uses the handle in a way this rule cannot scope" % type(statement).__name__,
            )

    drop = [statement for statement in block if _closes_handle(statement, handle)]
    kept = [statement for statement in block if statement is not block[0] and statement not in drop]
    indent = " " * block[0].col_offset
    pieces: List[str] = ["with %s as %s:" % (segment_of(target.text, starts, opened), handle)]
    previous_end = None
    for statement in kept:
        start, end = node_span(target.text, starts, statement)
        if previous_end is not None:
            pieces.append(_gap(target.text, previous_end, start))
        pieces.append(_shifted(target.text, starts, statement, indent + INDENT))
        previous_end = end
    block_text = "\n".join(pieces)

    function_start, function_end = node_span(target.text, starts, function)
    block_start, block_end = node_span(target.text, starts, block[0])
    _unused, last_end = node_span(target.text, starts, block[-1])
    edit = Edit(
        file=target.rel_posix,
        search=target.text[function_start:function_end],
        replace=apply_splices(target.text, function_start, function_end, [_Splice(start=block_start, end=last_end, text=block_text)]),
        label="scoped handle of '%s'" % target.symbol,
    )

    alias = import_statement_for(target.rel_posix)[1]
    statements = [
        "source = inspect.getsource(%s.%s)" % (alias, target.symbol),
        "assert 'with open(' in source",
        "assert '.close()' not in source",
        "assert '%s = open(' not in source" % handle,
        "directory = tempfile.mkdtemp()",
        "try:",
        '    path = os.path.join(directory, "lock note.txt")',
        '    with open(path, "w", encoding="utf-8") as writer:',
        '        writer.write("alpha")',
        "    assert %s.%s(path) == 'alpha'" % (alias, target.symbol),
        "finally:",
        "    shutil.rmtree(directory, ignore_errors=True)",
    ]
    test_name = "%s_scopes_its_handle" % target.symbol
    lock = lock_source(
        target.rel_posix,
        test_name,
        "Lock the scope the pattern gave the handle, the close it made redundant, and the read still working.",
        statements,
        headers=("import os", "import shutil", "import tempfile"),
    )
    companion, companion_miss = _append_lock(target, test_file_for(target.rel_posix), test_name, lock)
    if companion is None:
        return _no_companion(target, companion_miss)
    evidence = ("the handle '%s' is opened outside any with block" % handle,) + tuple(
        "the close of '%s' becomes redundant inside the scope" % handle for _ in drop
    )
    return _hit("open-to-context-manager", target, edit, companion, evidence)


# ---------------------------------------------------------------------------
# Rule 5: a precondition states its own failure.
# ---------------------------------------------------------------------------


def rule_bare_assert_to_explicit_raise(target: Target) -> Outcome:
    """Rewrite the first statement of a function from an assert into a raise.

    The exception type is kept, because an assert raises ``AssertionError`` and a caller
    that catches it has to keep catching it. Only the first statement is considered: a
    check further down is not a precondition, and moving it changes what the function
    does before it refuses.
    """

    function, miss = module_function(target, allow_async=True)
    if function is None:
        return miss
    assert function is not None
    starts = line_starts(target.text)
    check = function.body[0]
    if not isinstance(check, ast.Assert):
        return _miss(
            target.rel_posix,
            target.symbol,
            NOT_THE_FIRST_STATEMENT,
            "the first statement of '%s' is not an assert, so it is not a precondition" % target.symbol,
        )
    indent = " " * check.col_offset
    test_text = segment_of(target.text, starts, check.test)
    arguments = ""
    message_evidence = "no message was written, so the raise carries none either"
    if check.msg is not None:
        if not (isinstance(check.msg, ast.Constant) and isinstance(check.msg.value, str)):
            return _miss(
                target.rel_posix,
                target.symbol,
                NON_LITERAL_ASSERT_MESSAGE,
                "the message of the assert in '%s' is built at call time, so no lock test could name its text" % target.symbol,
            )
        arguments = segment_of(target.text, starts, check.msg)
        message_evidence = "the message text is kept word for word"
    replacement = "if not %s:\n%sraise AssertionError(%s)" % (test_text, indent + INDENT, arguments)
    start, end = node_span(target.text, starts, check)
    edit = _rewrite_function(target, starts, function, [_Splice(start=start, end=end, text=replacement)], "explicit raise of '%s'" % target.symbol)

    alias = import_statement_for(target.rel_posix)[1]
    statements = [
        "source = inspect.getsource(%s.%s)" % (alias, target.symbol),
        "assert 'raise AssertionError(' in source",
        "assert not [line for line in source.splitlines() if line.strip().startswith('assert ')]",
        "try:",
        '    %s' % _run_call(function, alias, target.symbol, '""'),
        "except AssertionError as caught:",
        "    pass" if check.msg is None else "    assert %s in str(caught)" % arguments,
        "else:",
        "    raise AssertionError('%s accepted an argument its check rejects')" % target.symbol,
    ]
    test_name = "%s_raises_in_stead_of_asserting" % target.symbol
    lock = lock_source(
        target.rel_posix,
        test_name,
        "Lock the raise that replaced the assert, and the refusal the function still carries.",
        statements,
        headers=_lock_headers(function),
    )
    companion, companion_miss = _append_lock(target, test_file_for(target.rel_posix), test_name, lock)
    if companion is None:
        return _no_companion(target, companion_miss)
    evidence = ("the first statement is an assert on '%s'" % test_text, message_evidence)
    return _hit("bare-assert-to-explicit-raise", target, edit, companion, evidence)


# ---------------------------------------------------------------------------
# Rule 6: a bare handler names the class it answers to.
# ---------------------------------------------------------------------------


def rule_bare_except_to_narrow_exception(target: Target) -> Outcome:
    """Name ``Exception`` in every bare ``except:`` header of the function.

    A handler that names no class also answers the exits the interpreter raises, so the
    one path that means to leave the program is answered with the fallback written for
    an ordinary failure. Naming the class keeps the fallback and lets the exits pass.
    """

    function, miss = module_function(target)
    if function is None:
        return miss
    assert function is not None
    starts = line_starts(target.text)
    handlers = [
        node for node in ast.walk(function) if isinstance(node, ast.ExceptHandler) and node.type is None
    ]
    if not handlers:
        return _miss(
            target.rel_posix,
            target.symbol,
            NO_BARE_EXCEPT,
            "no handler of '%s' leaves out the exception class" % target.symbol,
        )
    splices: List[_Splice] = []
    for handler in sorted(handlers, key=lambda node: node.lineno):
        if any(isinstance(node, ast.Raise) and node.exc is None for node in ast.walk(handler)):
            return _miss(
                target.rel_posix,
                target.symbol,
                BARE_EXCEPT_RE_RAISES,
                "a bare handler of '%s' re-raises what it caught, so naming the class would also "
                "change which exits the re-raise can still pass" % target.symbol,
            )
        start = starts[handler.lineno - 1] + handler.col_offset
        if target.text[start : start + len("except:")] != "except:":
            return _miss(
                target.rel_posix,
                target.symbol,
                EXCEPT_HANDLER_UNREADABLE,
                "a bare handler of '%s' does not carry the header text 'except:' this rule anchors on"
                % target.symbol,
            )
        splices.append(_Splice(start=start, end=start + len("except:"), text="except Exception:"))
    function_start, function_end = node_span(target.text, starts, function)
    rewritten = apply_splices(target.text, function_start, function_end, splices)
    if "except:" in rewritten:
        return _miss(
            target.rel_posix,
            target.symbol,
            EXCEPT_HANDLER_UNREADABLE,
            "the text of '%s' carries an 'except:' outside a handler header, so the lock test this "
            "rule writes could not tell the handler from the text around it" % target.symbol,
        )
    edit = Edit(
        file=target.rel_posix,
        search=target.text[function_start:function_end],
        replace=rewritten,
        label="named handler of '%s'" % target.symbol,
    )

    alias = import_statement_for(target.rel_posix)[1]
    statements = [
        "source = inspect.getsource(%s.%s)" % (alias, target.symbol),
        "assert 'except Exception:' in source",
        "assert 'except:' not in source",
    ]
    test_name = "%s_answers_named_exceptions" % target.symbol
    lock = lock_source(
        target.rel_posix,
        test_name,
        "Lock the class every handler of this function now names.",
        statements,
    )
    companion, companion_miss = _append_lock(target, test_file_for(target.rel_posix), test_name, lock)
    if companion is None:
        return _no_companion(target, companion_miss)
    evidence = tuple(
        "the handler on line %d catches every exception the interpreter can raise" % handler.lineno
        for handler in sorted(handlers, key=lambda node: node.lineno)
    )
    return _hit("bare-except-to-narrow-exception", target, edit, companion, evidence)


# ---------------------------------------------------------------------------
# Rule 7: asking whether a value is None asks with identity.
# ---------------------------------------------------------------------------


def _is_none_literal(node: ast.expr) -> bool:
    return isinstance(node, ast.Constant) and node.value is None


def _none_comparisons(function: ast.FunctionDef) -> Tuple[List[ast.Compare], bool]:
    """The single equality tests against ``None``, and whether a test against None is chained."""

    claimed: List[ast.Compare] = []
    chained = False
    for node in ast.walk(function):
        if not isinstance(node, ast.Compare):
            continue
        operands = [node.left] + list(node.comparators)
        if not any(isinstance(op, (ast.Eq, ast.NotEq)) for op in node.ops):
            continue
        if not any(_is_none_literal(operand) for operand in operands):
            continue
        if len(node.ops) != 1 or len(operands) != 2:
            chained = True
            continue
        claimed.append(node)
    return claimed, chained


def rule_none_comparison_to_identity(target: Target) -> Outcome:
    """Replace an equality against ``None`` with ``is`` or ``is not``.

    None is one object, and an equality against it is a question most objects answer by
    their own agreement: a type with a custom equality turns a presence check into
    whatever that equality happens to say. Identity asks the question that was meant.
    """

    function, miss = module_function(target, allow_async=True)
    if function is None:
        return miss
    assert function is not None
    starts = line_starts(target.text)
    comparisons, chained = _none_comparisons(function)
    if chained:
        return _miss(
            target.rel_posix,
            target.symbol,
            NONE_COMPARISON_IS_CHAINED,
            "a test against None in '%s' is part of a chained comparison, which one identity test "
            "cannot replace" % target.symbol,
        )
    if not comparisons:
        return _miss(
            target.rel_posix,
            target.symbol,
            NO_NONE_COMPARISON,
            "no comparison of '%s' tests a value against None with equality" % target.symbol,
        )
    splices: List[_Splice] = []
    touched: List[Tuple[str, str]] = []
    for node in comparisons:
        start, end = node_span(target.text, starts, node)
        operator = "is not" if isinstance(node.ops[0], ast.NotEq) else "is"
        left = node.left
        right = node.comparators[0]
        if _is_none_literal(right) and not _is_none_literal(left):
            operand = segment_of(target.text, starts, left)
            replacement = "%s %s None" % (operand, operator)
        else:
            operand = segment_of(target.text, starts, right)
            replacement = "None %s %s" % (operator, operand)
        splices.append(_Splice(start=start, end=end, text=replacement))
        touched.append((operand, operator))
    edit = _rewrite_function(
        target, starts, function, splices, "identity comparisons of '%s'" % target.symbol
    )

    alias = import_statement_for(target.rel_posix)[1]
    statements = [
        "source = inspect.getsource(%s.%s)" % (alias, target.symbol),
        "assert '== None' not in source",
        "assert '!= None' not in source",
    ]
    for operand, operator in touched:
        statements.append("assert %s in source" % repr("%s %s None" % (operand, operator)))
    test_name = "%s_compares_none_by_identity" % target.symbol
    lock = lock_source(
        target.rel_posix,
        test_name,
        "Lock the identity tests that replaced the equality against None.",
        statements,
    )
    companion, companion_miss = _append_lock(target, test_file_for(target.rel_posix), test_name, lock)
    if companion is None:
        return _no_companion(target, companion_miss)
    evidence = tuple("the test against None reads '%s %s None'" % (operand, operator) for operand, operator in touched)
    return _hit("none-comparison-to-identity", target, edit, companion, evidence)


# ---------------------------------------------------------------------------
# Rule 8: an emptiness test stops counting the collection.
# ---------------------------------------------------------------------------


def _len_call(node: ast.expr) -> bool:
    return (
        isinstance(node, ast.Call)
        and isinstance(node.func, ast.Name)
        and node.func.id == "len"
        and len(node.args) == 1
        and not node.keywords
    )


def _is_plain_zero(node: ast.expr) -> bool:
    return (
        isinstance(node, ast.Constant)
        and isinstance(node.value, int)
        and not isinstance(node.value, bool)
        and node.value == 0
    )


def rule_empty_len_to_truthiness(target: Target) -> Outcome:
    """Ask whether a collection is empty by truthiness instead of counting it."""

    function, miss = module_function(target, allow_async=True)
    if function is None:
        return miss
    assert function is not None
    starts = line_starts(target.text)
    checks: List[Tuple[ast.Compare, str]] = []
    counted_but_not_a_name: List[ast.expr] = []
    for node in ast.walk(function):
        if not isinstance(node, ast.Compare) or len(node.ops) != 1 or not isinstance(node.ops[0], ast.Eq):
            continue
        operands = [node.left] + list(node.comparators)
        if len(operands) != 2:
            continue
        if _is_plain_zero(operands[0]) and _len_call(operands[1]):
            counted = operands[1]
        elif _is_plain_zero(operands[1]) and _len_call(operands[0]):
            counted = operands[0]
        else:
            continue
        assert isinstance(counted, ast.Call) and counted.args
        argument = counted.args[0]
        if isinstance(argument, ast.Name):
            checks.append((node, argument.id))
        else:
            counted_but_not_a_name.append(argument)
    if not checks and not counted_but_not_a_name:
        return _miss(
            target.rel_posix,
            target.symbol,
            NO_EMPTY_LEN_CHECK,
            "no comparison of '%s' counts a value with len only to ask whether it is empty" % target.symbol,
        )
    if counted_but_not_a_name:
        return _miss(
            target.rel_posix,
            target.symbol,
            LEN_TARGET_IS_NOT_A_NAME,
            "'%s' counts '%s', which is not a plain name, and this rule only rewrites a count of a "
            "name it can ask about directly"
            % (target.symbol, segment_of(target.text, starts, counted_but_not_a_name[0])),
        )
    splices: List[_Splice] = []
    names: List[str] = []
    for node, name in checks:
        start, end = node_span(target.text, starts, node)
        splices.append(_Splice(start=start, end=end, text="not %s" % name))
        if name not in names:
            names.append(name)
    edit = _rewrite_function(
        target, starts, function, splices, "truthiness emptiness test of '%s'" % target.symbol
    )

    alias = import_statement_for(target.rel_posix)[1]
    statements = ["source = inspect.getsource(%s.%s)" % (alias, target.symbol)]
    for name in names:
        statements.append("assert 'not %s' in source" % name)
        statements.append("assert 'len(%s) == 0' not in source" % name)
    test_name = "%s_asks_for_truthiness" % target.symbol
    lock = lock_source(
        target.rel_posix,
        test_name,
        "Lock the truthiness test that replaced the counted emptiness.",
        statements,
    )
    companion, companion_miss = _append_lock(target, test_file_for(target.rel_posix), test_name, lock)
    if companion is None:
        return _no_companion(target, companion_miss)
    evidence = tuple("'%s' is counted only to ask whether it is empty" % name for name in names)
    return _hit("empty-len-to-truthiness", target, edit, companion, evidence)


# ---------------------------------------------------------------------------
# Rule 9: a constructor that replaced the chain should open it first.
# ---------------------------------------------------------------------------


def module_method(target: Target) -> Tuple[Optional[ast.FunctionDef], Optional[RuleMiss]]:
    """The module level class method a ``Class.method`` target names, or the refusal."""

    class_name, separator, method_name = target.symbol.partition(".")
    if not separator or not method_name:
        return None, _miss(
            target.rel_posix,
            target.symbol,
            NOT_A_METHOD,
            "'%s' names no class and method split by a dot" % target.symbol,
        )
    for node in target.tree.body:
        if isinstance(node, ast.ClassDef) and node.name == class_name:
            for item in node.body:
                if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)) and item.name == method_name:
                    if isinstance(item, ast.AsyncFunctionDef):
                        return None, _miss(
                            target.rel_posix,
                            target.symbol,
                            ASYNC_TARGET,
                            "'%s.%s' is a coroutine, and no lock test of this catalog waits for one"
                            % (class_name, method_name),
                        )
                    return item, None
            if method_name == "__init__":
                return None, _miss(
                    target.rel_posix,
                    target.symbol,
                    NO_INIT_METHOD,
                    "class '%s' defines no '__init__' of its own" % class_name,
                )
            return None, _miss(
                target.rel_posix,
                target.symbol,
                NOT_A_METHOD,
                "class '%s' defines no method named '%s'" % (class_name, method_name),
            )
    for node in ast.walk(target.tree):
        if isinstance(node, ast.ClassDef) and node.name == class_name:
            return None, _miss(
                target.rel_posix,
                target.symbol,
                NOT_A_MODULE_CLASS,
                "class '%s' is not defined at module level in '%s'" % (class_name, target.rel_posix),
            )
    return None, _miss(
        target.rel_posix,
        target.symbol,
        NO_SUCH_CLASS,
        "no class named '%s' in '%s'" % (class_name, target.rel_posix),
    )


def _opens_super(statement: ast.stmt) -> bool:
    """True for a bare ``super().__init__(...)`` statement."""

    return (
        isinstance(statement, ast.Expr)
        and isinstance(statement.value, ast.Call)
        and isinstance(statement.value.func, ast.Attribute)
        and statement.value.func.attr == "__init__"
        and isinstance(statement.value.func.value, ast.Call)
        and isinstance(statement.value.func.value.func, ast.Name)
        and statement.value.func.value.func.id == "super"
    )


def rule_init_missing_super(target: Target) -> Outcome:
    """Open the constructor chain of a module level class that replaced it.

    The rule claims the narrowest shape it can state honestly: a class naming no base
    of its own, whose ``__init__`` takes only ``self``. A named base is a constructor
    with arguments this rule cannot forward, and calling super without them would
    change what the class builds, which a cleanup pattern may not do.
    """

    method, miss = module_method(target)
    if method is None:
        return miss
    assert method is not None
    if method.name != "__init__":
        return _miss(
            target.rel_posix,
            target.symbol,
            NOT_A_METHOD,
            "this card writes a constructor, and '%s' names no '__init__'" % target.symbol,
        )
    starts = line_starts(target.text)
    class_name = target.symbol.partition(".")[0]
    class_node: Optional[ast.ClassDef] = None
    for node in target.tree.body:
        if isinstance(node, ast.ClassDef) and node.name == class_name:
            class_node = node
            break
    assert class_node is not None
    if class_node.bases or class_node.keywords:
        return _miss(
            target.rel_posix,
            target.symbol,
            SUPER_BASES_UNREADABLE,
            "class '%s' names base classes, and this rule cannot say which constructor super reaches "
            "or what arguments it takes" % class_name,
        )
    if (
        [argument.arg for argument in method.args.posonlyargs + method.args.args] != ["self"]
        or method.args.kwonlyargs
        or method.args.vararg
        or method.args.kwarg
    ):
        return _miss(
            target.rel_posix,
            target.symbol,
            INIT_TAKES_MORE_THAN_SELF,
            "'%s' takes arguments this rule cannot forward, and calling super without them "
            "would change what the class builds" % target.symbol,
        )
    real = [statement for statement in method.body if not _is_string_statement(statement)]
    if real and _opens_super(real[0]):
        return _miss(
            target.rel_posix,
            target.symbol,
            SUPER_CALL_ALREADY_FIRST,
            "class '%s' already opens its constructor chain first" % class_name,
        )
    has_docstring = bool(method.body and _is_string_statement(method.body[0]))
    if real:
        body_start = starts[real[0].lineno - 1] + real[0].col_offset
        indent = " " * real[0].col_offset
    else:
        docstring = method.body[0]
        body_start = starts[docstring.end_lineno - 1] + docstring.end_col_offset + 1
        indent = " " * docstring.col_offset
    splices = [_Splice(start=body_start, end=body_start, text="super().__init__()\n%s" % indent)]
    edit = _rewrite_function(target, starts, method, splices, "constructor chain of '%s' opened" % target.symbol)

    alias = import_statement_for(target.rel_posix)[1]
    statements = [
        "source = inspect.getsource(%s.%s)" % (alias, target.symbol),
        "assert 'super().__init__()' in source",
        "lines = [line.strip() for line in source.splitlines() if line.strip()]",
        "assert lines[0].startswith('def __init__')",
        "assert lines[%d] == 'super().__init__()'" % (2 if has_docstring else 1),
        "created = %s.%s()" % (alias, class_name),
        "assert isinstance(created, %s.%s)" % (alias, class_name),
    ]
    test_name = "%s_init_calls_super_first" % class_name
    lock = lock_source(
        target.rel_posix,
        test_name,
        "Lock the super call this rule put first in the constructor, and the class that still builds.",
        statements,
    )
    companion, companion_miss = _append_lock(target, test_file_for(target.rel_posix), test_name, lock)
    if companion is None:
        return _no_companion(target, companion_miss)
    evidence = ("'%s.__init__' builds its object without opening the constructor chain first" % class_name,)
    return _hit("init-missing-super", target, edit, companion, evidence)


# ---------------------------------------------------------------------------
# Rule 10: an import that binds nothing is a promise to a module nobody calls.
# ---------------------------------------------------------------------------


def rule_drop_unused_imports(target: Target) -> Outcome:
    """Remove top level imports that bind a name no other line of the file reads.

    A name that appears nowhere else in the text is decidable from the file alone, and
    that is exactly the limit of the rule: ``__all__``, a star import, and a package
    ``__init__.py`` all let one line of a file mean more than the names it spells, and
    the rule refuses them rather than guess what a reader of the package expects.
    """

    function, miss = module_function(target, allow_async=True)
    if function is None:
        return miss
    assert function is not None
    starts = line_starts(target.text)
    if target.rel_posix == "__init__.py" or target.rel_posix.endswith("/__init__.py"):
        return _miss(
            target.rel_posix,
            target.symbol,
            PACKAGE_FILE_TARGET,
            "'%s' is a package interface, where an import line can be the name the package publishes"
            % target.rel_posix,
        )
    import_nodes = [node for node in target.tree.body if isinstance(node, (ast.Import, ast.ImportFrom))]
    if not import_nodes:
        return _miss(
            target.rel_posix, target.symbol, NO_UNUSED_IMPORT,
            "'%s' imports nothing at top level, so nothing there can go unread" % target.rel_posix,
        )
    if any(
        isinstance(node, ast.ImportFrom) and any(alias.name == "*" for alias in node.names)
        for node in import_nodes
    ):
        return _miss(
            target.rel_posix,
            target.symbol,
            STAR_IMPORT_IN_FILE,
            "'%s' takes names through a star import, so the file can read names its text never writes"
            % target.rel_posix,
        )
    for node in target.tree.body:
        if isinstance(node, (ast.Assign, ast.AnnAssign)):
            for assignment in getattr(node, "targets", [node.target]):
                if isinstance(assignment, ast.Name) and assignment.id == "__all__":
                    return _miss(
                        target.rel_posix,
                        target.symbol,
                        NAME_LISTED_IN_ALL,
                        "'%s' publishes an __all__, and a name the text never reads can still carry that promise"
                        % target.rel_posix,
                    )
    covered = set()
    for node in import_nodes:
        covered.update(range(node.lineno, node.end_lineno + 1))
    other_text = "\n".join(
        line
        for index, line in enumerate(target.text.split("\n"), start=1)
        if index not in covered
    )
    unused_nodes: List[ast.stmt] = []
    unused_names: List[str] = []
    for node in import_nodes:
        names = [
            alias.asname or (alias.name.split(".")[0] if isinstance(node, ast.Import) else alias.name)
            for alias in node.names
        ]
        if all(re.search(r"\b%s\b" % re.escape(name), other_text) is None for name in names):
            unused_nodes.append(node)
            unused_names.extend(names)
    if not unused_nodes:
        return _miss(
            target.rel_posix,
            target.symbol,
            NO_UNUSED_IMPORT,
            "every top level import of '%s' binds a name another line of the file reads" % target.rel_posix,
        )
    unused_nodes.sort(key=lambda node: node.lineno)
    for previous, following in zip(unused_nodes, unused_nodes[1:]):
        if following.lineno != previous.end_lineno + 1:
            return _miss(
                target.rel_posix,
                target.symbol,
                IMPORTS_NOT_CONTIGUOUS,
                "the unread imports of '%s' are not on consecutive lines, so one anchor cannot remove them together"
                % target.rel_posix,
            )
    block_start = starts[unused_nodes[0].lineno - 1]
    last_node = unused_nodes[-1]
    block_end = starts[last_node.end_lineno - 1] + last_node.end_col_offset + 1
    block = target.text[block_start:block_end]
    if target.text.count(block) != 1:
        return _miss(
            target.rel_posix,
            target.symbol,
            ANCHOR_OVERLAP,
            "the import block this rule would remove appears more than once in '%s'" % target.rel_posix,
        )
    edit = Edit(
        file=target.rel_posix,
        search=block,
        replace="",
        label="unread imports of '%s' removed" % target.rel_posix,
    )

    alias = import_statement_for(target.rel_posix)[1]
    statements = [
        "source = inspect.getsource(%s)" % alias,
        "import_lines = [line.strip() for line in source.splitlines() if line.strip().startswith(('import ', 'from '))]",
    ]
    for name in sorted(set(unused_names)):
        statements.append("assert not [line for line in import_lines if %r in line.split()]" % name)
    statements.append("assert callable(%s.%s)" % (alias, function.name))
    test_name = "%s_keeps_no_unread_imports" % function.name
    lock = lock_source(
        target.rel_posix,
        test_name,
        "Lock the import lines this rule removed from the module and the function they never reached.",
        statements,
    )
    companion, companion_miss = _append_lock(target, test_file_for(target.rel_posix), test_name, lock)
    if companion is None:
        return _no_companion(target, companion_miss)
    evidence = tuple(
        "the import of '%s' binds a name no other line of '%s' reads" % (name, target.rel_posix)
        for name in sorted(set(unused_names))
    )
    return _hit("drop-unused-imports", target, edit, companion, evidence)


RULES: Dict[str, Callable[[Target], Outcome]] = {
    "annotate-literal-defaults": rule_annotate_literal_defaults,
    "mutable-default-to-none": rule_mutable_default_to_none,
    "chain-to-registry": rule_chain_to_registry,
    "open-to-context-manager": rule_open_to_context_manager,
    "bare-assert-to-explicit-raise": rule_bare_assert_to_explicit_raise,
    "bare-except-to-narrow-exception": rule_bare_except_to_narrow_exception,
    "none-comparison-to-identity": rule_none_comparison_to_identity,
    "empty-len-to-truthiness": rule_empty_len_to_truthiness,
    "init-missing-super": rule_init_missing_super,
    "drop-unused-imports": rule_drop_unused_imports,
}

RULE_IDS: Tuple[str, ...] = tuple(sorted(RULES))