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
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
"""Matchers and transforms over the syntax tree.

Every catalog entry names a shape here. A matcher returns candidates with the evidence
that justifies them, or a refusal code; a transform returns the text of the edit pair.
Nothing here writes to disk: the session layer owns the transaction.
"""

import ast
import re
import textwrap
from typing import Any, Dict, List, Optional, Tuple

Target = Dict[str, Any]
Edit = Dict[str, str]


def functions(tree: ast.Module) -> List[ast.AST]:
    return [n for n in ast.walk(tree)
            if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))]


def _enclosing(tree: ast.Module, node: ast.AST) -> Optional[str]:
    for parent in ast.walk(tree):
        for _, value in ast.iter_fields(parent):
            if value is node:
                return getattr(parent, "name", None)
    return None


# ---------------------------------------------------------------- mutable default

def match_mutable_default(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
    out: List[Target] = []
    for fn in functions(tree):
        for default in list(fn.args.defaults) + [d for d in fn.args.kw_defaults if d]:
            if isinstance(default, (ast.List, ast.Dict, ast.Set)):
                out.append({
                    "symbol": fn.name,
                    "line": fn.lineno,
                    "end": max(fn.end_lineno, default.end_lineno),
                    "evidence": "default argument built at call time",
                })
                break
    if not out:
        return [], "NO_SHAPE"
    return out, None


def _fill_mutable_default(path: str, lines: List[str], target: Target) -> List[Edit]:
    idx = target["line"] - 1
    old = lines[idx]
    match = re.search(r"(\w+)\s*=\s*(\[\]|\{\}|\(\))", old)
    if not match:
        return []
    name, literal = match.group(1), match.group(2)
    replacement = {"[]": "[]", "{}": "{}", "()": "()"}[literal]
    new_head = re.sub(r"=\s*(\[\]|\{\}|\(\))", "=None", old, count=1)
    body_indent = " " * 4
    guard = "%sif %s is None:\n%s    %s = %s" % (body_indent, name, body_indent, name, replacement)
    nxt = lines[idx + 1] if idx + 1 < len(lines) else ""
    nxt_indent = len(nxt) - len(nxt.lstrip())
    if nxt.strip().startswith('"""') or nxt.strip().startswith("'''"):
        # Insert the guard after the docstring of the function, not right after the def.
        end = idx + 1
        quote = '"""' if '"""' in nxt else "'''"
        if nxt.count(quote) < 2:
            while end < len(lines) and quote not in lines[end]:
                end += 1
        return [{"file": path, "search": lines[end], "replace": guard + "\n" + lines[end],
                 "label": "guard"}]
    if nxt_indent < 4 or not nxt.strip():
        return []
    return [{"file": path, "search": old, "replace": new_head + "\n" + guard}]


def lock_mutable_default(target: Target) -> str:
    return (
        "def test_%(symbol)s_default_is_not_built_at_definition():\n"
        "    fn = _function(%(symbol)r)\n"
        "    defaults = list(fn.args.defaults) + [d for d in fn.args.kw_defaults if d]\n"
        "    assert not [d for d in defaults if isinstance(d, (ast.List, ast.Dict, ast.Set))]\n"
        % {"symbol": target["symbol"]}
    )


# ---------------------------------------------------------------- magic literal

def match_magic_literal(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
    out: List[Target] = []
    for fn in functions(tree):
        for node in ast.walk(fn):
            if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)) \
                    and node.value not in (0, 1, -1, 2, True, False, None):
                if _is_annotation_context(tree, node):
                    continue
                out.append({
                    "symbol": fn.name,
                    "line": node.lineno,
                    "end": node.end_lineno,
                    "value": repr(node.value),
                    "evidence": "bare numeric constant inside a function body",
                })
                break
    if not out:
        return [], "NO_SHAPE"
    return out, None


def _is_annotation_context(tree: ast.Module, node: ast.AST) -> bool:
    for fn in functions(tree):
        for arg in list(fn.args.args) + list(fn.args.kwonlyargs):
            if arg.annotation is not None and node in ast.walk(arg.annotation):
                return True
    return False


def edit_magic_literal(path: str, lines: List[str], target: Target) -> List[Edit]:
    value = target["value"]
    idx = target["line"] - 1
    old = lines[idx]
    name = "LIMIT_%s" % re.sub(r"\W", "_", value).strip("_").upper()
    new = old.replace(value, name)
    if new == old:
        return []
    return [{"file": path, "search": old, "replace": new, "label": "use"},
            {"file": path, "search": _first_import_block(lines), "replace":
             _first_import_block(lines) + "\n\n%s = %s\n" % (name, value), "label": "constant"}]


def _first_import_block(lines: List[str]) -> str:
    for i, line in enumerate(lines):
        if line.startswith("import ") or line.startswith("from "):
            j = i
            while j < len(lines) and (lines[j].startswith("import ") or lines[j].startswith("from ")):
                j += 1
            return "\n".join(lines[i:j])
    return ""


def lock_magic_literal(target: Target) -> str:
    name = re.sub(r"\W", "_", target["value"]).strip("_").upper()
    return (
        "def test_%s_names_its_limit():\n"
        "    tree = _tree()\n"
        "    names = [n.targets[0].id for n in ast.walk(tree)\n"
        "             if isinstance(n, ast.Assign) and isinstance(n.targets[0], ast.Name)]\n"
        "    assert 'LIMIT_%s' in names\n" % (target["symbol"], name)
    )


# ---------------------------------------------------------------- guard clause

def match_guard_clause(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
    out: List[Target] = []
    for fn in functions(tree):
        body = [s for s in fn.body if not _is_docstring(s)]
        if not body or not isinstance(body[0], ast.If) or isinstance(body[0].test, ast.Constant):
            continue
        if isinstance(body[0].test, ast.UnaryOp) and isinstance(body[0].test.op, ast.Not):
            continue  # already a guard clause
        if len(body) == 2 and not body[0].orelse and isinstance(body[1], ast.Return):
            out.append({"symbol": fn.name, "line": body[0].lineno, "end": body[0].end_lineno,
                        "evidence": "one if before the fallback return"})
        elif len(body) == 1:
            out.append({"symbol": fn.name, "line": body[0].lineno, "end": body[0].end_lineno,
                        "evidence": "whole body wrapped in one if"})
    if not out:
        return [], "NO_SHAPE"
    return out, None


def _is_docstring(stmt: ast.stmt) -> bool:
    return (isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Constant)
            and isinstance(stmt.value.value, str))


def edit_guard_clause(path: str, lines: List[str], target: Target) -> List[Edit]:
    start, end = target["line"] - 1, target["end"] - 1
    head = lines[start]
    stripped = head.strip()
    cond = stripped[len("if "):-1].strip() if stripped.startswith("if ") else None
    if cond is None:
        return []
    # The fallback the early return must reproduce: the trailing return of the function.
    fallback = "None"
    stop = end
    indent = head[:len(head) - len(head.lstrip())]
    for index in range(end + 1, len(lines)):
        row = lines[index]
        if not row.strip():
            continue
        if row.startswith(indent + "return "):
            fallback = row[len(indent) + len("return "):]
            stop = index
            break
        break
    new_block = ("    if not (%s):\n        return %s\n" % (cond, fallback)
                 + "\n".join(ln[4:] if ln.startswith("    ") else ln
                             for ln in lines[start + 1:end + 1]))
    old_block = "\n".join(lines[start:stop + 1])
    return [{"file": path, "search": old_block, "replace": new_block}]


def lock_guard_clause(target: Target) -> str:
    return (
        "def test_%(symbol)s_returns_early():\n"
        "    fn = _function(%(symbol)r)\n"
        "    body = [s for s in fn.body if not _is_doc(s)]\n"
        "    assert isinstance(body[0], ast.If) and isinstance(body[0].test, ast.UnaryOp)\n"
        "    assert isinstance(body[0].test.op, ast.Not)\n" % {"symbol": target["symbol"]}
    )


# ---------------------------------------------------------------- dead import

def match_dead_import(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
    used = {n.id for n in ast.walk(tree) if isinstance(n, ast.Name)}
    used |= {n.attr for n in ast.walk(tree) if isinstance(n, ast.Attribute)}
    for node in ast.walk(tree):
        if isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name):
            used.add(node.value.id)
    out: List[Target] = []
    for node in ast.walk(tree):
        if isinstance(node, ast.Import):
            for alias in node.names:
                bound = (alias.asname or alias.name).split(".")[0]
                if bound not in used:
                    out.append({"symbol": bound, "line": node.lineno, "end": node.end_lineno,
                                "evidence": "imported name never used", "text": alias.name,
                                "asname": alias.asname})
        elif isinstance(node, ast.ImportFrom):
            for alias in node.names:
                if alias.name == "*":
                    continue
                bound = alias.asname or alias.name
                if bound not in used:
                    out.append({"symbol": bound, "line": node.lineno, "end": node.end_lineno,
                                "evidence": "imported name never used", "text": alias.name,
                                "asname": alias.asname})
    if not out:
        return [], "NO_SHAPE"
    return out, None


def edit_dead_import(path: str, lines: List[str], target: Target) -> List[Edit]:
    idx = target["line"] - 1
    old = lines[idx]
    stripped = old.strip()
    if stripped.startswith("import "):
        parts = [p.strip() for p in stripped[len("import "):].split(",")]
        kept = [p for p in parts if p.split(" as ")[-1].split(".")[0] != target["symbol"]]
        if not kept:
            new_line = None
        else:
            new_line = "import " + ", ".join(kept)
    elif stripped.startswith("from "):
        head, rest = stripped.split(" import ", 1)
        parts = [p.strip() for p in rest.split(",")]
        kept = [p for p in parts if p.split(" as ")[-1] != target["symbol"]]
        if not kept:
            new_line = None
        else:
            new_line = "%s import %s" % (head, ", ".join(kept))
    else:
        return []
    if new_line is None:
        return [{"file": path, "search": old, "replace": "", "label": "drop"}]
    return [{"file": path, "search": old, "replace": new_line}]


def lock_dead_import(target: Target) -> str:
    return (
        "def test_%(symbol)s_is_not_imported():\n"
        "    src = _source()\n"
        "    assert not _imports_name(src, %(symbol)r)\n" % {"symbol": target["symbol"]}
    )


# ---------------------------------------------------------------- loop to comprehension

def match_loop_comprehension(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
    out: List[Target] = []
    for fn in functions(tree):
        for stmt in fn.body:
            if isinstance(stmt, ast.For) and len(stmt.body) == 1 and isinstance(stmt.body[0], ast.Expr) \
                    and isinstance(stmt.body[0].value, ast.Call) \
                    and isinstance(stmt.body[0].value.func, ast.Attribute) \
                    and stmt.body[0].value.func.attr == "append" and not stmt.orelse:
                out.append({"symbol": fn.name, "line": stmt.lineno, "end": stmt.end_lineno,
                            "evidence": "for loop whose only statement is an append"})
    if not out:
        return [], "NO_SHAPE"
    return out, None


def edit_loop_comprehension(path: str, lines: List[str], target: Target) -> List[Edit]:
    start, end = target["line"] - 1, target["end"] - 1
    block = "\n".join(lines[start:end + 1])
    m_target = re.search(r"^\s*(\w+)\.append\((.*)\)\s*$", lines[end], flags=re.M)
    m_for = re.match(r"^(\s*)for\s+(.+?)\s+in\s+(.+?):\s*$", lines[start])
    if not (m_target and m_for):
        return []
    indent, var, iterable = m_for.group(1), m_for.group(2), m_for.group(3)
    expr = m_target.group(2)
    new = "%s%s = [%s for %s in %s]" % (indent, m_target.group(1), expr, var, iterable)
    return [{"file": path, "search": block, "replace": new}]


def lock_loop_comprehension(target: Target) -> str:
    return (
        "def test_%(symbol)s_has_no_appending_loop():\n"
        "    fn = _function(%(symbol)r)\n"
        "    for node in ast.walk(fn):\n"
        "        if isinstance(node, ast.For):\n"
        "            for stmt in node.body:\n"
        "                call = getattr(stmt, 'value', None)\n"
        "                assert not (isinstance(call, ast.Call)\n"
        "                            and getattr(call.func, 'attr', '') == 'append')\n"
        % {"symbol": target["symbol"]}
    )


# ---------------------------------------------------------------- f-string

def match_concat_fstring(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
    parents: Dict[ast.AST, ast.AST] = {}
    for parent in ast.walk(tree):
        for _, value in ast.iter_fields(parent):
            if isinstance(value, ast.AST):
                parents[value] = parent
    out: List[Target] = []
    for node in ast.walk(tree):
        if not isinstance(node, ast.BinOp) or not isinstance(node.op, ast.Add):
            continue
        if isinstance(parents.get(node), ast.BinOp):
            continue
        parts = _flatten_add(node)
        if len(parts) < 2:
            continue
        if not any(isinstance(p, ast.Constant) and isinstance(p.value, str) for p in parts):
            continue
        out.append({"symbol": _enclosing(tree, node) or "module", "line": node.lineno,
                    "end": node.end_lineno, "col": node.col_offset,
                    "end_col": node.end_col_offset,
                    "evidence": "string built with plus"})
    if not out:
        return [], "NO_SHAPE"
    return out, None


def _flatten_add(node: ast.AST) -> List[ast.AST]:
    if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
        return _flatten_add(node.left) + _flatten_add(node.right)
    return [node]


def edit_concat_fstring(path: str, lines: List[str], target: Target) -> List[Edit]:
    if target.get("line") != target.get("end"):
        return []
    idx = target["line"] - 1
    old = lines[idx]
    segment = old[target["col"]:target["end_col"]].strip()
    if not segment:
        return []
    try:
        expr = ast.parse(segment, mode="eval").body
    except SyntaxError:
        return []
    pieces = []
    for part in _flatten_add(expr):
        if isinstance(part, ast.Constant) and isinstance(part.value, str):
            text = part.value.replace("{", "{{").replace("}", "}}").replace('"', "'")
            pieces.append(text)
        else:
            pieces.append("{" + ast.unparse(part) + "}")
    rendered = "f" + chr(34) + "".join(pieces) + chr(34)
    new = old[:target["col"]] + rendered + old[target["end_col"]:]
    if new == old:
        return []
    return [{"file": path, "search": old, "replace": new}]


def lock_concat_fstring(target: Target) -> str:
    return (
        "def test_%(symbol)s_has_no_concatenation_left():\n"
        "    for node in ast.walk(_tree()):\n"
        "        if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add) \\\n"
        "                and isinstance(node.left, ast.Constant) \\\n"
        "                and isinstance(node.left.value, str):\n"
        "            assert False, 'string still built with plus'\n"
        % {"symbol": target["symbol"]}
    )


# ---------------------------------------------------------------- assertion

def match_add_assertion(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
    out: List[Target] = []
    for fn in functions(tree):
        body = [s for s in fn.body if not _is_docstring(s)]
        if not body:
            continue
        if any(isinstance(s, ast.Assert) for s in body):
            continue
        if len(fn.args.args) == 1 and fn.args.args[0].annotation is not None:
            first = body[0]
            out.append({"symbol": fn.name, "line": first.lineno, "end": first.lineno,
                        "evidence": "typed parameter with no guard",
                        "param": fn.args.args[0].arg,
                        "type": getattr(fn.args.args[0].annotation, "id", "object")})
    if not out:
        return [], "NO_SHAPE"
    return out, None


def edit_add_assertion(path: str, lines: List[str], target: Target) -> List[Edit]:
    idx = target["line"] - 1
    old = lines[idx]
    indent = " " * (len(old) - len(old.lstrip()))
    guard = "%sassert isinstance(%s, %s), 'bad %s'" % (indent, target["param"], target["type"],
                                                       target["param"])
    return [{"file": path, "search": old, "replace": guard + "\n" + old}]


def lock_add_assertion(target: Target) -> str:
    return (
        "def test_%(symbol)s_guards_its_argument():\n"
        "    fn = _function(%(symbol)r)\n"
        "    guards = [s for s in fn.body if isinstance(s, ast.Assert)]\n"
        "    assert guards, 'no guard at the boundary'\n"
        "    names = [n.id for n in ast.walk(guards[0]) if isinstance(n, ast.Name)]\n"
        "    assert %(param)r in names\n" % {"symbol": target["symbol"], "param": target["param"]}
    )


# ---------------------------------------------------------------- shared helpers

def _source(lines: List[str]) -> str:
    return "\n".join(lines)


def _home(tree: ast.Module, node: ast.AST) -> str:
    """Nearest function or class around a node, so a target names a symbol."""
    best = None
    for fn in functions(tree):
        if fn.lineno <= node.lineno <= fn.end_lineno:
            if best is None or fn.lineno > best.lineno:
                best = fn
    if best is not None:
        return best.name
    for cls in [n for n in ast.walk(tree) if isinstance(n, ast.ClassDef)]:
        if cls.lineno <= node.lineno <= cls.end_lineno:
            return cls.name
    return "?"


def _is_len_zero(node: ast.AST) -> bool:
    return (isinstance(node, ast.Compare) and len(node.comparators) == 1
            and isinstance(node.left, ast.Call) and isinstance(node.left.func, ast.Name)
            and node.left.func.id == "len" and len(node.left.args) == 1
            and isinstance(node.comparators[0], ast.Constant)
            and isinstance(node.comparators[0].value, int)
            and not isinstance(node.comparators[0].value, bool)
            and node.comparators[0].value == 0)


def _is_bare_bool(node: ast.AST) -> bool:
    return (isinstance(node, ast.Compare) and len(node.comparators) == 1
            and isinstance(node.comparators[0], ast.Constant)
            and isinstance(node.comparators[0].value, bool))


#: Methods that answer with a string, so str(...) around them is noise.
STR_METHODS = ("capitalize", "casefold", "format", "join", "lower", "removeprefix",
               "removesuffix", "replace", "rstrip", "strip", "title", "upper", "zfill")


def _is_str_value(node: ast.AST) -> bool:
    if isinstance(node, ast.Constant) and isinstance(node.value, str):
        return True
    if isinstance(node, ast.JoinedStr):
        return True
    return (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
            and node.func.attr in STR_METHODS)


def _unwrap_call(line: str, target: Target, wrapper: str) -> Optional[str]:
    """Drop one wrapper call in place, using the columns the matcher recorded."""
    col, end = target.get("col"), target.get("end_col")
    if col is None or end is None or end > len(line):
        return None
    segment = line[col:end]
    prefix = wrapper + "("
    if not segment.startswith(prefix) or not segment.endswith(")"):
        return None
    inner = segment[len(prefix):-1]
    if not inner:
        return None
    rebuilt = line[:col] + inner + line[end:]
    return None if rebuilt == line else rebuilt


# ---------------------------------------------------------------- unused local

def match_unused_local(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
    out: List[Target] = []
    for fn in functions(tree):
        read = {n.id for n in ast.walk(fn) if isinstance(n, ast.Name)
                and not isinstance(n.ctx, ast.Store)}
        for stmt in ast.walk(fn):
            if not isinstance(stmt, ast.Assign):
                continue
            for tgt in stmt.targets:
                if not isinstance(tgt, ast.Name) or tgt.id in read or tgt.id == "_":
                    continue
                out.append({"symbol": fn.name, "line": stmt.lineno, "end": stmt.end_lineno,
                            "name": tgt.id, "evidence": "local name never read"})
    if not out:
        return [], "NO_SHAPE"
    return out, None


def edit_unused_local(path: str, lines: List[str], target: Target) -> List[Edit]:
    start, end = target["line"] - 1, target["end"] - 1
    if start < 0 or end >= len(lines):
        return []
    old = "\n".join(lines[start:end + 1])
    if not old.strip():
        return []
    head = lines[start]
    width = len(head) - len(head.lstrip())

    def sibling(row: str) -> bool:
        return bool(row.strip()) and (len(row) - len(row.lstrip())) == width

    above = lines[start - 1] if start > 0 else ""
    below = lines[end + 1] if end + 1 < len(lines) else ""
    if not sibling(above) and not sibling(below):
        return []  # the statement is alone in its block, so it cannot just go away
    return [{"file": path, "search": old + "\n", "replace": ""}]


def lock_unused_local(target: Target) -> str:
    return (
        "def test_%(symbol)s_has_no_dead_local():\n"
        "    fn = _function(%(symbol)r)\n"
        "    stored = [n.id for n in ast.walk(fn)\n"
        "              if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Store)]\n"
        "    assert %(name)r not in stored\n"
        % {"symbol": target.get("symbol", "demo"), "name": target.get("name", "value")}
    )


# ---------------------------------------------------------------- unreachable code

def _blocks(node: ast.AST):
    for field in ("body", "orelse", "finalbody"):
        block = getattr(node, field, None)
        if isinstance(block, list) and block and isinstance(block[0], ast.stmt):
            yield block
    for handler in getattr(node, "handlers", None) or []:
        if isinstance(handler.body, list) and handler.body:
            yield handler.body


def match_unreachable_code(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
    out: List[Target] = []
    for node in ast.walk(tree):
        for block in _blocks(node):
            for index, stmt in enumerate(block):
                if isinstance(stmt, (ast.Return, ast.Raise)) and index + 1 < len(block):
                    after = block[index + 1]
                    out.append({"symbol": _home(tree, node), "line": after.lineno,
                                "end": block[-1].end_lineno,
                                "evidence": "statement after a return or a raise"})
                    break
    if not out:
        return [], "NO_SHAPE"
    return out, None


def edit_unreachable_code(path: str, lines: List[str], target: Target) -> List[Edit]:
    start, end = target["line"] - 1, target["end"] - 1
    if start < 0 or end >= len(lines):
        return []
    old = "\n".join(lines[start:end + 1])
    if not old.strip():
        return []
    return [{"file": path, "search": old + "\n", "replace": ""}]


def lock_unreachable_code(target: Target) -> str:
    return (
        "def test_%(symbol)s_has_no_dead_statement():\n"
        "    for node in ast.walk(_function(%(symbol)r)):\n"
        "        for field in ('body', 'orelse', 'finalbody'):\n"
        "            block = getattr(node, field, None)\n"
        "            if not isinstance(block, list) or not block:\n"
        "                continue\n"
        "            for index, stmt in enumerate(block):\n"
        "                if isinstance(stmt, (ast.Return, ast.Raise)) \\\n"
        "                        and index + 1 < len(block):\n"
        "                    assert False, 'statement after a return'\n"
        % {"symbol": target.get("symbol", "demo")}
    )


# ---------------------------------------------------------------- empty except

def _swallows(handler: ast.ExceptHandler) -> bool:
    return bool(handler.body) and all(isinstance(s, ast.Pass) for s in handler.body)


def match_empty_except(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
    out: List[Target] = []
    for node in ast.walk(tree):
        if isinstance(node, ast.ExceptHandler) and _swallows(node):
            out.append({"symbol": _home(tree, node), "line": node.lineno,
                        "end": node.end_lineno,
                        "name": getattr(node.type, "id", "Exception") if node.type else "",
                        "evidence": "handler whose whole body is pass"})
    if not out:
        return [], "NO_SHAPE"
    return out, None


def edit_empty_except(path: str, lines: List[str], target: Target) -> List[Edit]:
    head = target["line"] - 1
    for index in range(head, target["end"]):
        if lines[index].strip() != "pass":
            continue
        indent = lines[index][:len(lines[index]) - len(lines[index].lstrip())]
        old = lines[head] + "\n" + lines[index]
        new = lines[head] + "\n" + indent + "raise"
        return [{"file": path, "search": old, "replace": new}]
    return []


def lock_empty_except(target: Target) -> str:
    return (
        "def test_%(symbol)s_does_not_swallow():\n"
        "    for node in ast.walk(_function(%(symbol)r)):\n"
        "        if isinstance(node, ast.ExceptHandler) and node.body \\\n"
        "                and all(isinstance(s, ast.Pass) for s in node.body):\n"
        "            assert False, 'handler that does nothing'\n"
        % {"symbol": target.get("symbol", "demo")}
    )


# ---------------------------------------------------------------- bare except

def match_bare_except(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
    out: List[Target] = []
    for node in ast.walk(tree):
        if isinstance(node, ast.ExceptHandler) and node.type is None:
            out.append({"symbol": _home(tree, node), "line": node.lineno,
                        "end": node.end_lineno, "name": "Exception",
                        "evidence": "handler that names no exception"})
    if not out:
        return [], "NO_SHAPE"
    return out, None


def edit_bare_except(path: str, lines: List[str], target: Target) -> List[Edit]:
    head = target["line"] - 1
    old = lines[head]
    if old.strip() != "except:":
        return []
    indent = old[:len(old) - len(old.lstrip())]
    return [{"file": path, "search": old, "replace": indent + "except Exception:"}]


def lock_bare_except(target: Target) -> str:
    return (
        "def test_%(symbol)s_names_what_it_catches():\n"
        "    for node in ast.walk(_function(%(symbol)r)):\n"
        "        if isinstance(node, ast.ExceptHandler) and node.type is None:\n"
        "            assert False, 'bare except'\n"
        % {"symbol": target.get("symbol", "demo")}
    )


# ---------------------------------------------------------------- test mapped to a bool

def _bool_of(node: ast.AST):
    """The value of a True or False literal, otherwise None."""
    if isinstance(node, ast.Constant) and isinstance(node.value, bool):
        return node.value
    return None


def _bool_map(node: ast.AST, following: ast.AST):
    """An if that maps a test onto True and False: with an else, or with a return after it.

    Returns the polarity (True when the true branch comes first) and the last line the
    map covers, or None when the node is not such a map.
    """
    if not isinstance(node, ast.If) or len(node.body) != 1:
        return None
    if not isinstance(node.body[0], ast.Return):
        return None
    first = _bool_of(node.body[0].value)
    if first is None:
        return None
    tails = node.orelse if len(node.orelse) == 1 else [following]
    if len(tails) != 1 or not isinstance(tails[0], ast.Return):
        return None
    second = _bool_of(tails[0].value)
    if second is None or second == first:
        return None
    return first, tails[0].end_lineno


def match_bool_prefix(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
    out: List[Target] = []
    for fn in functions(tree):
        if fn.name.startswith("test_"):
            continue
        for parent in ast.walk(fn):
            for name in ("body", "orelse", "finalbody"):
                statements = getattr(parent, name, None)
                if not isinstance(statements, list):
                    continue
                for index, node in enumerate(statements):
                    following = statements[index + 1] if index + 1 < len(statements) else None
                    mapped = _bool_map(node, following)
                    if mapped:
                        out.append({"symbol": fn.name, "line": node.lineno,
                                    "end": mapped[1],
                                    "evidence": "a test mapped onto True and False"})
    if not out:
        return [], "NO_SHAPE"
    return out, None


def edit_bool_prefix(path: str, lines: List[str], target: Target) -> List[Edit]:
    start, end = target["line"] - 1, target["end"]
    if start < 0 or end > len(lines):
        return []
    # The dispatcher hands out lines without their endings: put them back.
    block = [line if line.endswith("\n") else line + "\n" for line in lines[start:end]]
    stripped = textwrap.dedent("".join(block))
    # A return outside a function is a syntax error, so the block goes into a probe.
    probe = "def _probe_():\n" + "".join("    " + line for line in stripped.splitlines(True))
    try:
        parsed = ast.parse(probe)
    except SyntaxError:
        return []
    if not parsed.body or not isinstance(parsed.body[0], ast.FunctionDef):
        return []
    statements = parsed.body[0].body
    node = statements[0]
    following = statements[1] if len(statements) > 1 else None
    mapped = _bool_map(node, following)
    if not mapped:
        return []
    polarity, _ = mapped
    test = ast.get_source_segment(probe, node.test)
    if not test:
        return []
    indent = block[0][:len(block[0]) - len(block[0].lstrip())]
    replacement = "%sreturn %s\n" % (indent, test if polarity else "not " + test)
    return [{"file": path, "search": "".join(block), "replace": replacement}]


def lock_bool_prefix(target: Target) -> str:
    return (
        "def test_%(symbol)s_does_not_map_a_test_to_a_bool():\n"
        "    tree = _function(%(symbol)r)\n"
        "    for parent in ast.walk(tree):\n"
        "        for name in ('body', 'orelse', 'finalbody'):\n"
        "            statements = getattr(parent, name, None)\n"
        "            if not isinstance(statements, list):\n"
        "                continue\n"
        "            for index, node in enumerate(statements):\n"
        "                if not isinstance(node, ast.If) or len(node.body) != 1:\n"
        "                    continue\n"
        "                head = node.body[0]\n"
        "                if not isinstance(head, ast.Return) or not isinstance(head.value,\n"
        "                                                                       ast.Constant):\n"
        "                    continue\n"
        "                if not isinstance(head.value.value, bool):\n"
        "                    continue\n"
        "                tails = node.orelse if len(node.orelse) == 1 \\\n"
        "                        else statements[index + 1:index + 2]\n"
        "                if len(tails) != 1 or not isinstance(tails[0], ast.Return):\n"
        "                    continue\n"
        "                tail = tails[0].value\n"
        "                if isinstance(tail, ast.Constant) and isinstance(tail.value, bool):\n"
        "                    assert False, 'the test is still mapped onto True and False'\n"
        % {"symbol": target.get("symbol", "demo")}
    )


# ---------------------------------------------------------------- len compared with zero

def match_len_zero(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
    out: List[Target] = []
    for node in ast.walk(tree):
        if _is_len_zero(node):
            out.append({"symbol": _home(tree, node), "line": node.lineno,
                        "end": node.end_lineno, "col": node.col_offset,
                        "end_col": node.end_col_offset,
                        "evidence": "length compared with zero"})
    if not out:
        return [], "NO_SHAPE"
    return out, None


def _is_simple(node: ast.AST) -> bool:
    """An operand that is safe to read on its own: no call, no side effect."""
    return isinstance(node, (ast.Name, ast.Attribute, ast.Subscript))


def _rewrite_compare(path: str, lines: List[str], target: Target,
                     negated_ops: tuple) -> List[Edit]:
    idx = target["line"] - 1
    if idx < 0 or idx >= len(lines):
        return []
    line = lines[idx]
    col, end = target.get("col", 0), target.get("end_col", 0)
    segment = line[col:end].strip()
    try:
        node = ast.parse(segment).body[0].value
    except (SyntaxError, IndexError, AttributeError):
        return []
    if not isinstance(node, ast.Compare) or len(node.ops) != 1:
        return []
    left = node.left
    if (isinstance(left, ast.Call) and isinstance(left.func, ast.Name)
            and left.func.id == "len" and len(left.args) == 1
            and not left.keywords and _is_simple(left.args[0])):
        left = left.args[0]  # len(x) compared with zero is emptiness of x
    operand = ast.get_source_segment(segment, left)
    if not operand:
        return []
    new = ("not " + operand) if type(node.ops[0]).__name__ in negated_ops else operand
    new_line = line[:col] + new + line[end:]
    if new_line == line:
        return []
    return [{"file": path, "search": line, "replace": new_line}]


def edit_len_zero(path: str, lines: List[str], target: Target) -> List[Edit]:
    return _rewrite_compare(path, lines, target, ("Eq", "Lt"))


def lock_len_zero(target: Target) -> str:
    return (
        "def test_%(symbol)s_asks_the_object_directly():\n"
        "    for node in ast.walk(_function(%(symbol)r)):\n"
        "        if isinstance(node, ast.Compare) and len(node.comparators) == 1 \\\n"
        "                and isinstance(node.left, ast.Call) \\\n"
        "                and isinstance(node.left.func, ast.Name) \\\n"
        "                and node.left.func.id == 'len' \\\n"
        "                and isinstance(node.comparators[0], ast.Constant) \\\n"
        "                and node.comparators[0].value == 0:\n"
        "            assert False, 'length still compared with zero'\n"
        % {"symbol": target.get("symbol", "demo")}
    )


# ---------------------------------------------------------------- comparison to a bool

def match_bool_compare(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
    out: List[Target] = []
    for node in ast.walk(tree):
        if _is_bare_bool(node):
            out.append({"symbol": _home(tree, node), "line": node.lineno,
                        "end": node.end_lineno, "col": node.col_offset,
                        "end_col": node.end_col_offset,
                        "evidence": "value compared with True or False"})
    if not out:
        return [], "NO_SHAPE"
    return out, None


def edit_bool_compare(path: str, lines: List[str], target: Target) -> List[Edit]:
    idx = target["line"] - 1
    if idx < 0 or idx >= len(lines):
        return []
    line = lines[idx]
    col, end = target.get("col", 0), target.get("end_col", 0)
    segment = line[col:end].strip()
    try:
        node = ast.parse(segment).body[0].value
    except (SyntaxError, IndexError, AttributeError):
        return []
    if not isinstance(node, ast.Compare) or len(node.ops) != 1:
        return []
    operand = ast.get_source_segment(segment, node.left)
    wanted = node.comparators[0].value
    if not operand or not isinstance(wanted, bool):
        return []
    positive = (type(node.ops[0]).__name__ == "Eq") == bool(wanted)
    new = operand if positive else "not " + operand
    new_line = line[:col] + new + line[end:]
    if new_line == line:
        return []
    return [{"file": path, "search": line, "replace": new_line}]


def lock_bool_compare(target: Target) -> str:
    return (
        "def test_%(symbol)s_does_not_compare_with_a_bool():\n"
        "    for node in ast.walk(_function(%(symbol)r)):\n"
        "        if isinstance(node, ast.Compare) and len(node.comparators) == 1 \\\n"
        "                and isinstance(node.comparators[0], ast.Constant) \\\n"
        "                and isinstance(node.comparators[0].value, bool):\n"
        "            assert False, 'comparison with a bool literal'\n"
        % {"symbol": target.get("symbol", "demo")}
    )


# ---------------------------------------------------------------- KeyError into get

def match_dict_get(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
    src = _source(lines)
    out: List[Target] = []
    for node in ast.walk(tree):
        if not isinstance(node, ast.Try):
            continue
        guards = [h for h in node.handlers
                  if isinstance(h.type, ast.Name) and h.type.id == "KeyError"]
        returns = [s for s in node.body if isinstance(s, ast.Return)
                   and isinstance(s.value, ast.Subscript)]
        fallbacks = [s for s in (guards[0].body if guards else [])
                     if isinstance(s, ast.Return)]
        if len(guards) != 1 or len(node.body) != 1 or len(returns) != 1:
            continue
        if len(guards[0].body) != 1 or len(fallbacks) != 1:
            continue
        sub = returns[0].value
        if not isinstance(sub.value, ast.Name):
            continue
        out.append({"symbol": _home(tree, node), "line": node.lineno, "end": node.end_lineno,
                    "dict": sub.value.id,
                    "key": ast.get_source_segment(src, sub.slice) or "",
                    "default": ast.get_source_segment(src, fallbacks[0].value) or "None",
                    "evidence": "subscript guarded by a KeyError handler"})
    if not out:
        return [], "NO_SHAPE"
    return out, None


def edit_dict_get(path: str, lines: List[str], target: Target) -> List[Edit]:
    start, end = target["line"] - 1, target["end"] - 1
    if start < 0 or end >= len(lines) or not target.get("key"):
        return []
    old = "\n".join(lines[start:end + 1])
    if not old.strip():
        return []
    head = lines[start]
    indent = head[:len(head) - len(head.lstrip())]
    new = "%sreturn %s.get(%s, %s)" % (indent, target["dict"], target["key"],
                                       target["default"])
    return [{"file": path, "search": old, "replace": new}]


def lock_dict_get(target: Target) -> str:
    return (
        "def test_%(symbol)s_asks_the_dict_for_it():\n"
        "    for node in ast.walk(_function(%(symbol)r)):\n"
        "        if isinstance(node, ast.Try):\n"
        "            for handler in node.handlers:\n"
        "                if isinstance(handler.type, ast.Name) \\\n"
        "                        and handler.type.id == 'KeyError':\n"
        "                    assert False, 'KeyError still caught by hand'\n"
        % {"symbol": target.get("symbol", "demo")}
    )


# ---------------------------------------------------------------- list around a comprehension

def match_redundant_list(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
    out: List[Target] = []
    for node in ast.walk(tree):
        if (isinstance(node, ast.Call) and isinstance(node.func, ast.Name)
                and node.func.id == "list" and len(node.args) == 1
                and not node.keywords
                and isinstance(node.args[0], (ast.ListComp, ast.SetComp, ast.DictComp))):
            out.append({"symbol": _home(tree, node), "line": node.lineno,
                        "end": node.end_lineno, "col": node.col_offset,
                        "end_col": node.end_col_offset,
                        "evidence": "list() wrapped around a comprehension"})
    if not out:
        return [], "NO_SHAPE"
    return out, None


def edit_redundant_list(path: str, lines: List[str], target: Target) -> List[Edit]:
    idx = target["line"] - 1
    if idx < 0 or idx >= len(lines):
        return []
    new_line = _unwrap_call(lines[idx], target, "list")
    if new_line is None:
        return []
    return [{"file": path, "search": lines[idx], "replace": new_line}]


def lock_redundant_list(target: Target) -> str:
    return (
        "def test_%(symbol)s_builds_the_list_once():\n"
        "    for node in ast.walk(_tree()):\n"
        "        if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) \\\n"
        "                and node.func.id == 'list' and len(node.args) == 1 \\\n"
        "                and isinstance(node.args[0], (ast.ListComp, ast.SetComp, ast.DictComp)):\n"
        "            assert False, 'list() around a comprehension'\n"
        % {"symbol": target.get("symbol", "demo")}
    )


# ---------------------------------------------------------------- str around a string

def match_str_of_string(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
    out: List[Target] = []
    for node in ast.walk(tree):
        if (isinstance(node, ast.Call) and isinstance(node.func, ast.Name)
                and node.func.id == "str" and len(node.args) == 1 and not node.keywords
                and _is_str_value(node.args[0])):
            out.append({"symbol": _home(tree, node), "line": node.lineno,
                        "end": node.end_lineno, "col": node.col_offset,
                        "end_col": node.end_col_offset,
                        "evidence": "str() wrapped around a value that is already text"})
    if not out:
        return [], "NO_SHAPE"
    return out, None


def edit_str_of_string(path: str, lines: List[str], target: Target) -> List[Edit]:
    idx = target["line"] - 1
    if idx < 0 or idx >= len(lines):
        return []
    new_line = _unwrap_call(lines[idx], target, "str")
    if new_line is None:
        return []
    return [{"file": path, "search": lines[idx], "replace": new_line}]


def lock_str_of_string(target: Target) -> str:
    return (
        "def test_%(symbol)s_does_not_wrap_text():\n"
        "    text_methods = set(%(methods)r)\n"
        "    for node in ast.walk(_tree()):\n"
        "        if not (isinstance(node, ast.Call) and isinstance(node.func, ast.Name)\n"
        "                and node.func.id == 'str' and len(node.args) == 1):\n"
        "            continue\n"
        "        arg = node.args[0]\n"
        "        already = (isinstance(arg, ast.Constant) and isinstance(arg.value, str)) \\\n"
        "                or isinstance(arg, ast.JoinedStr) \\\n"
        "                or (isinstance(arg, ast.Call)\n"
        "                    and isinstance(arg.func, ast.Attribute)\n"
        "                    and arg.func.attr in text_methods)\n"
        "        assert not already, 'str() around a value that is already text'\n"
        % {"symbol": target.get("symbol", "demo"), "methods": list(STR_METHODS)}
    )


# ---------------------------------------------------------------- open without a with

def match_open_context(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
    src = _source(lines)
    out: List[Target] = []
    for fn in functions(tree):
        bounded: set = set()
        for node in ast.walk(fn):
            if isinstance(node, (ast.With, ast.AsyncWith)):
                for item in node.items:
                    if isinstance(item.optional_vars, ast.Name):
                        bounded.add(item.optional_vars.id)
        for stmt in ast.walk(fn):
            if not isinstance(stmt, ast.Assign) or len(stmt.targets) != 1:
                continue
            tgt = stmt.targets[0]
            value = stmt.value
            if not isinstance(tgt, ast.Name):
                continue
            if not (isinstance(value, ast.Call) and isinstance(value.func, ast.Name)
                    and value.func.id == "open"):
                continue
            if tgt.id in bounded:
                continue
            out.append({"symbol": fn.name, "line": stmt.lineno, "end": stmt.end_lineno,
                        "handle": tgt.id,
                        "call": ast.get_source_segment(src, value) or "",
                        "evidence": "file opened outside a with block"})
    if not out:
        return [], "NO_SHAPE"
    return out, None


def edit_open_context(path: str, lines: List[str], target: Target) -> List[Edit]:
    start = target["line"] - 1
    handle, call = target.get("handle", ""), target.get("call", "")
    if start < 0 or start >= len(lines) or not handle or not call:
        return []
    head = lines[start]
    indent = head[:len(head) - len(head.lstrip())]
    body: List[str] = []
    index = start + 1
    while index < len(lines):
        row = lines[index]
        if not row.strip():
            break  # a blank line ends the run of statements that use the handle
        width = len(row) - len(row.lstrip())
        if width < len(indent):
            break  # the enclosing block ends here
        if width == len(indent) and handle not in row:
            break  # a statement that never names the handle stays outside the with
        if row.strip() == handle + ".close()":
            index += 1  # the with block closes the handle on its own
            continue
        body.append(row)
        index += 1
    if not body:
        return []  # nothing uses the handle below, so a with block cannot be formed
    new_block = indent + "with " + call + " as " + handle + ":\n" \
        + "\n".join(indent + "    " + row.lstrip() for row in body)
    return [{"file": path, "search": "\n".join(lines[start:index]), "replace": new_block}]


def lock_open_context(target: Target) -> str:
    return (
        "def test_%(symbol)s_opens_inside_a_with():\n"
        "    fn = _function(%(symbol)r)\n"
        "    guarded = set()\n"
        "    for parent in ast.walk(fn):\n"
        "        if isinstance(parent, (ast.With, ast.AsyncWith)):\n"
        "            for item in parent.items:\n"
        "                for sub in ast.walk(item.context_expr):\n"
        "                    guarded.add(id(sub))\n"
        "    for node in ast.walk(fn):\n"
        "        if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) \\\n"
        "                and node.func.id == 'open':\n"
        "            assert id(node) in guarded, 'open outside a with block'\n"
        % {"symbol": target.get("symbol", "demo")}
    )


# ---------------------------------------------------------------- range(len(x)) loop

def match_range_len(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
    src = _source(lines)
    out: List[Target] = []
    for node in ast.walk(tree):
        if not isinstance(node, ast.For) or node.orelse:
            continue
        loop = node.iter
        if not (isinstance(loop, ast.Call) and isinstance(loop.func, ast.Name)
                and loop.func.id == "range" and len(loop.args) == 1):
            continue
        inner = loop.args[0]
        if not (isinstance(inner, ast.Call) and isinstance(inner.func, ast.Name)
                and inner.func.id == "len" and len(inner.args) == 1):
            continue
        if not isinstance(node.target, ast.Name):
            continue
        sequence = ast.get_source_segment(src, inner.args[0]) or ""
        if not sequence:
            continue
        index_name = node.target.id
        item = sequence[:-1] if sequence.endswith("s") and len(sequence) > 3 \
            else sequence + "_item"
        taken = {n.id for n in ast.walk(node) if isinstance(n, ast.Name)}
        if item in taken:
            item = item + "_value"
        out.append({"symbol": _home(tree, node), "line": node.lineno,
                    "end": node.end_lineno, "index": index_name, "item": item,
                    "sequence": sequence,
                    "evidence": "index loop over range of a length"})
    if not out:
        return [], "NO_SHAPE"
    return out, None


def edit_range_len(path: str, lines: List[str], target: Target) -> List[Edit]:
    start = target["line"] - 1
    head = lines[start] if 0 <= start < len(lines) else ""
    index_name, item = target.get("index", ""), target.get("item", "")
    sequence = target.get("sequence", "")
    if not head.strip().startswith("for ") or not index_name or not sequence:
        return []
    new_head = re.sub(r"\b%s\s*\(\s*len\(\s*%s\s*\)\s*\)" % (re.escape("range"),
                                                             re.escape(sequence)),
                      "enumerate(%s)" % sequence, head, count=1)
    new_head = new_head.replace("for %s in " % index_name,
                                "for %s, %s in " % (index_name, item), 1)
    if new_head == head:
        return []
    out: List[Edit] = [{"file": path, "search": head, "replace": new_head}]
    width = len(head) - len(head.lstrip())
    use = re.compile(r"%s\s*\[\s*%s\s*\](?!\s*=)" % (re.escape(sequence),
                                                     re.escape(index_name)))
    assign = re.compile(r"^\s*%s\s*\[\s*%s\s*\]\s*=" % (re.escape(sequence),
                                                        re.escape(index_name)))
    for index in range(start + 1, len(lines)):
        row = lines[index]
        if not row.strip():
            continue
        if len(row) - len(row.lstrip()) <= width:
            break
        if assign.match(row):
            # The assigned side keeps the subscript: only what is read becomes the item.
            out.append({"file": path, "search": row, "replace": use.sub(item, row)})
    return out


def lock_range_len(target: Target) -> str:
    return (
        "def test_%(symbol)s_walks_the_sequence():\n"
        "    for node in ast.walk(_tree()):\n"
        "        if isinstance(node, ast.For) and isinstance(node.iter, ast.Call) \\\n"
        "                and isinstance(node.iter.func, ast.Name) \\\n"
        "                and node.iter.func.id == 'range' and node.iter.args:\n"
        "            first = node.iter.args[0]\n"
        "            if isinstance(first, ast.Call) \\\n"
        "                    and isinstance(first.func, ast.Name) \\\n"
        "                    and first.func.id == 'len':\n"
        "                assert False, 'range over a length'\n"
        % {"symbol": target.get("symbol", "demo")}
    )


# ---------------------------------------------------------------- constructor of a dataclass

def match_dataclass_init(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
    src = _source(lines)
    out: List[Target] = []
    for cls in [n for n in ast.walk(tree) if isinstance(n, ast.ClassDef)]:
        methods = [s for s in cls.body if isinstance(s, ast.FunctionDef)]
        if len(methods) != 1 or methods[0].name != "__init__":
            continue
        init = methods[0]
        given = init.args.args[1:]
        if (not init.args.args or init.args.args[0].arg != "self" or not given
                or any(a.annotation is None for a in given)
                or init.args.defaults or init.args.kwonlyargs):
            continue
        kept = [s for s in init.body if not _is_docstring(s)]
        if len(kept) != len(given):
            continue
        honest = True
        for stmt, arg in zip(kept, given):
            if not isinstance(stmt, ast.Assign) or len(stmt.targets) != 1:
                honest = False
                break
            tgt, value = stmt.targets[0], stmt.value
            if not (isinstance(tgt, ast.Attribute) and isinstance(tgt.value, ast.Name)
                    and tgt.value.id == "self" and tgt.attr == arg.arg
                    and isinstance(value, ast.Name) and value.id == arg.arg):
                honest = False
                break
        if not honest:
            continue
        out.append({"symbol": cls.name, "line": cls.lineno, "end": cls.end_lineno,
                    "fields": ["%s: %s" % (a.arg, ast.get_source_segment(src, a.annotation)
                                           or "object") for a in given],
                    "evidence": "constructor only copies its arguments into attributes"})
    if not out:
        return [], "NO_SHAPE"
    return out, None


def edit_dataclass_init(path: str, lines: List[str], target: Target) -> List[Edit]:
    imports = _first_import_block(lines)
    fields = target.get("fields") or []
    start, end = target["line"] - 1, target["end"] - 1
    if not imports or not fields or start < 0 or end >= len(lines):
        return []
    head = lines[start]
    match = re.match(r"class\s+(\w+)\s*(\([^)]*\))?\s*:$", head.strip())
    if not match:
        return []
    init_start = None
    for index in range(start, end + 1):
        if lines[index].strip().startswith("def __init__"):
            init_start = index
            break
    if init_start is None:
        return []
    width = len(lines[init_start]) - len(lines[init_start].lstrip())
    init_end = init_start
    for index in range(init_start + 1, end + 1):
        row = lines[index]
        if not row.strip():
            continue
        if len(row) - len(row.lstrip()) <= width:
            break
        init_end = index
    block = "\n".join(lines[init_start:init_end + 1])
    replacement = "\n".join(" " * width + field for field in fields)
    return [{"file": path, "search": imports,
             "replace": imports + "\nfrom dataclasses import dataclass"},
            {"file": path, "search": head,
             "replace": "@dataclass\nclass %s:" % match.group(1)},
            {"file": path, "search": block, "replace": replacement}]


def lock_dataclass_init(target: Target) -> str:
    return (
        "def test_%(symbol)s_is_a_dataclass():\n"
        "    found = [n for n in ast.walk(_tree())\n"
        "             if isinstance(n, ast.ClassDef) and n.name == %(symbol)r]\n"
        "    assert found, 'the class is gone'\n"
        "    marks = [getattr(d, 'id', getattr(d, 'attr', ''))\n"
        "             for d in found[0].decorator_list]\n"
        "    assert 'dataclass' in marks, 'no dataclass decorator'\n"
        "    assert not any(isinstance(s, ast.FunctionDef) and s.name == '__init__'\n"
        "                   for s in found[0].body), 'the constructor is still written'\n"
        % {"symbol": target.get("symbol", "demo")}
    )


MATCHERS = {
    "mutable-default": match_mutable_default,
    "magic-literal": match_magic_literal,
    "guard-clause": match_guard_clause,
    "dead-import": match_dead_import,
    "loop-comprehension": match_loop_comprehension,
    "concat-fstring": match_concat_fstring,
    "add-assertion": match_add_assertion,
    "unused-local": match_unused_local,
    "unreachable-code": match_unreachable_code,
    "empty-except": match_empty_except,
    "bare-except": match_bare_except,
    "bool-prefix": match_bool_prefix,
    "len-zero": match_len_zero,
    "bool-compare": match_bool_compare,
    "dict-get": match_dict_get,
    "redundant-list": match_redundant_list,
    "str-of-string": match_str_of_string,
    "open-context": match_open_context,
    "range-len": match_range_len,
    "dataclass-init": match_dataclass_init,
}

EDITORS = {
    "mutable-default": _fill_mutable_default,
    "magic-literal": edit_magic_literal,
    "guard-clause": edit_guard_clause,
    "dead-import": edit_dead_import,
    "loop-comprehension": edit_loop_comprehension,
    "concat-fstring": edit_concat_fstring,
    "add-assertion": edit_add_assertion,
    "unused-local": edit_unused_local,
    "unreachable-code": edit_unreachable_code,
    "empty-except": edit_empty_except,
    "bare-except": edit_bare_except,
    "bool-prefix": edit_bool_prefix,
    "len-zero": edit_len_zero,
    "bool-compare": edit_bool_compare,
    "dict-get": edit_dict_get,
    "redundant-list": edit_redundant_list,
    "str-of-string": edit_str_of_string,
    "open-context": edit_open_context,
    "range-len": edit_range_len,
    "dataclass-init": edit_dataclass_init,
}

LOCKS = {
    "mutable-default": lock_mutable_default,
    "magic-literal": lock_magic_literal,
    "guard-clause": lock_guard_clause,
    "dead-import": lock_dead_import,
    "loop-comprehension": lock_loop_comprehension,
    "concat-fstring": lock_concat_fstring,
    "add-assertion": lock_add_assertion,
    "unused-local": lock_unused_local,
    "unreachable-code": lock_unreachable_code,
    "empty-except": lock_empty_except,
    "bare-except": lock_bare_except,
    "bool-prefix": lock_bool_prefix,
    "len-zero": lock_len_zero,
    "bool-compare": lock_bool_compare,
    "dict-get": lock_dict_get,
    "redundant-list": lock_redundant_list,
    "str-of-string": lock_str_of_string,
    "open-context": lock_open_context,
    "range-len": lock_range_len,
    "dataclass-init": lock_dataclass_init,
}


def match(shape: str, source: str) -> Tuple[List[Target], Optional[str]]:
    try:
        tree = ast.parse(source)
    except SyntaxError:
        return [], "UNPARSEABLE_TARGET"
    fn = MATCHERS.get(shape)
    if fn is None:
        return [], "NO_SHAPE"
    return fn(source.splitlines(), tree)


def edits(shape: str, path: str, source: str, target: Target) -> List[Edit]:
    editor = EDITORS.get(shape)
    if editor is None:
        return []
    return editor(path, source.splitlines(), target)


def lock(shape: str, target: Target) -> str:
    maker = LOCKS.get(shape)
    if maker is None:
        return ""
    return maker(target)


def shapes() -> List[str]:
    return sorted(MATCHERS)