File size: 102,835 Bytes
4bc63c7 35d4b41 4bc63c7 35d4b41 74acaf8 4bc63c7 35d4b41 74acaf8 4bc63c7 35d4b41 74acaf8 4bc63c7 35d4b41 74acaf8 4bc63c7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 | """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")}
)
# ------------------------------------------------------- the second growth wave
#
# Five entries added after the first twenty, each with a witness in the lab, an edit
# that applies to it, and a lock that holds once the edit is in. They follow the same
# contract as the modules above: match returns targets or NO_SHAPE, edit returns an
# honest search and replace, lock returns a test that fails on the old shape.
NONE_COMPARE = re.compile(r"([!<>=]=\s*None|!=\s*None)")
SORTED_FIRST = re.compile(r"sorted\(([^()]*)\)\[0\]")
def match_none_compare(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
"""Equality against None, where identity is what the author means."""
out: List[Target] = []
for node in ast.walk(tree):
if not isinstance(node, ast.Compare):
continue
for op, comparator in zip(node.ops, node.comparators):
if isinstance(op, (ast.Eq, ast.NotEq)) and isinstance(comparator, ast.Constant) \
and comparator.value is None:
out.append({"symbol": _home(tree, node), "line": node.lineno,
"end": node.end_lineno, "col": node.col_offset,
"end_col": node.end_col_offset,
"evidence": "compared to None with =="})
break
if not out:
return [], "NO_SHAPE"
return out, None
def edit_none_compare(path: str, lines: List[str], target: Target) -> List[Edit]:
idx = target["line"] - 1
if idx < 0 or idx >= len(lines):
return []
old = lines[idx]
new = old.replace("!= None", "is not None").replace("== None", "is None")
new = re.sub(r"!=\s*None", "is not None", new)
new = re.sub(r"==\s*None", "is None", new)
if new == old:
return []
return [{"file": path, "search": old, "replace": new}]
def lock_none_compare(target: Target) -> str:
return (
"def test_%(symbol)s_compares_none_by_identity():\n"
" for node in ast.walk(_tree()):\n"
" if not isinstance(node, ast.Compare):\n"
" continue\n"
" for op, other in zip(node.ops, node.comparators):\n"
" if isinstance(op, (ast.Eq, ast.NotEq)) \\\n"
" and isinstance(other, ast.Constant) and other.value is None:\n"
" assert False, 'None compared with == or !='\n"
% {"symbol": target.get("symbol", "demo")}
)
def match_dict_keys_in(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
"""Membership tested over .keys(), which the container already answers."""
out: List[Target] = []
for node in ast.walk(tree):
if not isinstance(node, ast.Compare):
continue
for op, comparator in zip(node.ops, node.comparators):
if not isinstance(op, (ast.In, ast.NotIn)):
continue
if (isinstance(comparator, ast.Call) and isinstance(comparator.func, ast.Attribute)
and comparator.func.attr == "keys" and not comparator.args
and not comparator.keywords):
out.append({"symbol": _home(tree, node), "line": node.lineno,
"end": node.end_lineno, "col": node.col_offset,
"end_col": node.end_col_offset,
"evidence": "membership tested on .keys()"})
break
if not out:
return [], "NO_SHAPE"
return out, None
def edit_dict_keys_in(path: str, lines: List[str], target: Target) -> List[Edit]:
idx = target["line"] - 1
if idx < 0 or idx >= len(lines):
return []
old = lines[idx]
new = re.sub(r"\.keys\(\)", "", old)
if new == old:
return []
return [{"file": path, "search": old, "replace": new}]
def lock_dict_keys_in(target: Target) -> str:
return (
"def test_%(symbol)s_tests_membership_on_the_mapping():\n"
" for node in ast.walk(_tree()):\n"
" if not isinstance(node, ast.Compare):\n"
" continue\n"
" for op, other in zip(node.ops, node.comparators):\n"
" if isinstance(op, (ast.In, ast.NotIn)) \\\n"
" and isinstance(other, ast.Call) \\\n"
" and isinstance(other.func, ast.Attribute) \\\n"
" and other.func.attr == 'keys':\n"
" assert False, 'in tested over .keys()'\n"
% {"symbol": target.get("symbol", "demo")}
)
def match_useless_pass(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
"""A pass that survives in a block which already does something."""
out: List[Target] = []
for node in ast.walk(tree):
for field in ("body", "orelse", "finalbody"):
block = getattr(node, field, None)
if not isinstance(block, list) or len(block) < 2:
continue
for stmt in block:
if isinstance(stmt, ast.Pass):
out.append({"symbol": getattr(node, "name", _home(tree, stmt)) or "module",
"line": stmt.lineno, "end": stmt.end_lineno,
"col": stmt.col_offset, "end_col": stmt.end_col_offset,
"evidence": "pass inside a block that is not empty"})
if not out:
return [], "NO_SHAPE"
return out, None
def edit_useless_pass(path: str, lines: List[str], target: Target) -> List[Edit]:
idx = target["line"] - 1
if idx < 1 or idx >= len(lines):
return []
if lines[idx].strip() != "pass":
return []
anchor = lines[idx - 1]
if not anchor.strip():
return []
search = anchor + "\n" + lines[idx]
if search not in "\n".join(lines):
return []
return [{"file": path, "search": search, "replace": anchor}]
def lock_useless_pass(target: Target) -> str:
return (
"def test_%(symbol)s_has_no_stray_pass():\n"
" for node in ast.walk(_tree()):\n"
" for field in ('body', 'orelse', 'finalbody'):\n"
" block = getattr(node, field, None)\n"
" if not isinstance(block, list) or len(block) < 2:\n"
" continue\n"
" assert not any(isinstance(s, ast.Pass) for s in block), 'stray pass'\n"
% {"symbol": target.get("symbol", "demo")}
)
def match_no_else_return(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
"""An else after a branch that already returned, so the else is decoration."""
out: List[Target] = []
for fn in functions(tree):
for stmt in ast.walk(fn):
if not isinstance(stmt, ast.If) or not stmt.orelse:
continue
if not any(isinstance(s, ast.Return) for s in stmt.body):
continue
last = stmt.body[-1]
if not isinstance(last, ast.Return):
continue
out.append({"symbol": fn.name, "line": stmt.lineno, "end": stmt.end_lineno,
"col": stmt.col_offset, "end_col": stmt.end_col_offset,
"evidence": "else after a branch that ends in return"})
if not out:
return [], "NO_SHAPE"
return out, None
def edit_no_else_return(path: str, lines: List[str], target: Target) -> List[Edit]:
start, end = target["line"] - 1, target["end"] - 1
else_index = None
indent = ""
for index in range(start, end + 1):
row = lines[index]
if row.strip() == "else:":
else_index = index
indent = row[:len(row) - len(row.lstrip())]
break
if else_index is None:
return []
block = lines[else_index + 1:end + 1]
dedented = []
for row in block:
if row.strip() and row.startswith(indent + " "):
dedented.append(row[4:])
elif row.strip():
return []
else:
dedented.append(row)
new_block = "\n".join(lines[start:else_index] + dedented)
old_block = "\n".join(lines[start:end + 1])
return [{"file": path, "search": old_block, "replace": new_block}]
def lock_no_else_return(target: Target) -> str:
return (
"def test_%(symbol)s_does_not_wrap_a_return_in_else():\n"
" for node in ast.walk(_tree()):\n"
" if not isinstance(node, ast.If) or not node.orelse:\n"
" continue\n"
" assert not any(isinstance(s, ast.Return) for s in node.body), \\\n"
" 'else after a returning branch'\n"
% {"symbol": target.get("symbol", "demo")}
)
def match_sorted_first(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
"""A whole sort paid for to read the smallest value."""
out: List[Target] = []
for node in ast.walk(tree):
if (isinstance(node, ast.Subscript) and isinstance(node.value, ast.Call)
and isinstance(node.value.func, ast.Name) and node.value.func.id == "sorted"
and len(node.value.args) == 1 and not node.value.keywords
and isinstance(node.slice, ast.Constant) and node.slice.value == 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": "sorted(...) taken at index 0"})
if not out:
return [], "NO_SHAPE"
return out, None
def edit_sorted_first(path: str, lines: List[str], target: Target) -> List[Edit]:
idx = target["line"] - 1
if idx < 0 or idx >= len(lines):
return []
old = lines[idx]
new = SORTED_FIRST.sub(r"min(\1)", old)
if new == old:
return []
return [{"file": path, "search": old, "replace": new}]
def lock_sorted_first(target: Target) -> str:
return (
"def test_%(symbol)s_asks_for_the_minimum_directly():\n"
" for node in ast.walk(_tree()):\n"
" if isinstance(node, ast.Subscript) and isinstance(node.value, ast.Call) \\\n"
" and isinstance(node.value.func, ast.Name) \\\n"
" and node.value.func.id == 'sorted':\n"
" assert False, 'sorted() indexed to find a minimum'\n"
% {"symbol": target.get("symbol", "demo")}
)
# ------------------------------------------------ batch two of the growth wave
#
# Five more entries, same contract: a matcher, an edit that applies, a lock that
# fails once the edit is in. Each one has its witness in fixtures/lab/registry.py.
CHAIN_OPS = (ast.Lt, ast.LtE, ast.Gt, ast.GtE)
def _keys_of(node: ast.AST) -> str:
return ast.dump(node)
def match_dict_keys_loop(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
"""A loop written over .keys() when the mapping iterates the same keys."""
out: List[Target] = []
for node in ast.walk(tree):
if (isinstance(node, ast.For) and isinstance(node.iter, ast.Call)
and isinstance(node.iter.func, ast.Attribute)
and node.iter.func.attr == "keys" and not node.iter.args
and not node.iter.keywords):
out.append({"symbol": _home(tree, node), "line": node.lineno,
"end": node.end_lineno, "col": node.col_offset,
"end_col": node.end_col_offset,
"evidence": "loop header walks a keys call"})
if not out:
return [], "NO_SHAPE"
return out, None
def edit_dict_keys_loop(path: str, lines: List[str], target: Target) -> List[Edit]:
idx = target["line"] - 1
if idx < 0 or idx >= len(lines):
return []
old = lines[idx]
new = re.sub(r"\.keys\(\)", "", old)
if new == old:
return []
return [{"file": path, "search": old, "replace": new}]
def lock_dict_keys_loop(target: Target) -> str:
return (
"def test_%(symbol)s_iterates_the_mapping():\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.Attribute) \\\n"
" and node.iter.func.attr == 'keys':\n"
" assert False, 'loop over a keys call'\n"
% {"symbol": target.get("symbol", "demo")}
)
def match_not_in_test(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
"""not x in y, where the language already spells it x not in y."""
out: List[Target] = []
for node in ast.walk(tree):
if not (isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not)):
continue
inner = node.operand
if not isinstance(inner, ast.Compare) or len(inner.ops) != 1:
continue
if isinstance(inner.ops[0], ast.In):
out.append({"symbol": _home(tree, node), "line": node.lineno,
"end": node.end_lineno, "col": node.col_offset,
"end_col": node.end_col_offset,
"evidence": "not applied to a membership test"})
if not out:
return [], "NO_SHAPE"
return out, None
def edit_not_in_test(path: str, lines: List[str], target: Target) -> List[Edit]:
idx = target["line"] - 1
if idx < 0 or idx >= len(lines):
return []
old = lines[idx]
new = re.sub(r"\bnot\s+([A-Za-z_][\w.\[\]()]*)\s+in\s+", r"\1 not in ", old)
if new == old:
return []
return [{"file": path, "search": old, "replace": new}]
def lock_not_in_test(target: Target) -> str:
return (
"def test_%(symbol)s_uses_not_in():\n"
" for node in ast.walk(_tree()):\n"
" if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not) \\\n"
" and isinstance(node.operand, ast.Compare) \\\n"
" and any(isinstance(op, ast.In) for op in node.operand.ops):\n"
" assert False, 'not applied to a membership test'\n"
% {"symbol": target.get("symbol", "demo")}
)
def match_redundant_slice(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
"""A whole-segment slice that copies nothing new."""
out: List[Target] = []
for node in ast.walk(tree):
if not isinstance(node, ast.Subscript):
continue
segment = node.slice
if not isinstance(segment, ast.Slice):
continue
if segment.lower is not None or segment.upper is not None or segment.step is not None:
continue
out.append({"symbol": _home(tree, node), "line": node.lineno,
"end": node.end_lineno, "col": node.col_offset,
"end_col": node.end_col_offset,
"evidence": "sliced from end to end"})
if not out:
return [], "NO_SHAPE"
return out, None
def edit_redundant_slice(path: str, lines: List[str], target: Target) -> List[Edit]:
idx = target["line"] - 1
if idx < 0 or idx >= len(lines):
return []
old = lines[idx]
new = re.sub(r"\[\s*:\s*\]", "", old)
if new == old:
return []
return [{"file": path, "search": old, "replace": new}]
def lock_redundant_slice(target: Target) -> str:
return (
"def test_%(symbol)s_is_not_sliced_whole():\n"
" for node in ast.walk(_tree()):\n"
" if isinstance(node, ast.Subscript) and isinstance(node.slice, ast.Slice) \\\n"
" and node.slice.lower is None and node.slice.upper is None \\\n"
" and node.slice.step is None:\n"
" assert False, 'value sliced from end to end'\n"
% {"symbol": target.get("symbol", "demo")}
)
def match_double_negation(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
"""Two nots in a row, which cancel out and only obscure the test."""
out: List[Target] = []
for node in ast.walk(tree):
if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not) \
and isinstance(node.operand, ast.UnaryOp) and isinstance(node.operand.op, ast.Not):
out.append({"symbol": _home(tree, node), "line": node.lineno,
"end": node.end_lineno, "col": node.col_offset,
"end_col": node.end_col_offset,
"evidence": "not applied to a not"})
if not out:
return [], "NO_SHAPE"
return out, None
def edit_double_negation(path: str, lines: List[str], target: Target) -> List[Edit]:
idx = target["line"] - 1
if idx < 0 or idx >= len(lines):
return []
old = lines[idx]
new = re.sub(r"\bnot\s+not\s+", "", old)
if new == old:
return []
return [{"file": path, "search": old, "replace": new}]
def lock_double_negation(target: Target) -> str:
return (
"def test_%(symbol)s_has_no_double_negation():\n"
" for node in ast.walk(_tree()):\n"
" if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not) \\\n"
" and isinstance(node.operand, ast.UnaryOp) \\\n"
" and isinstance(node.operand.op, ast.Not):\n"
" assert False, 'two nots in a row'\n"
% {"symbol": target.get("symbol", "demo")}
)
def match_chained_comparison(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
"""Two comparisons joined by and, where the middle value is shared."""
out: List[Target] = []
for node in ast.walk(tree):
if not (isinstance(node, ast.BoolOp) and isinstance(node.op, ast.And)):
continue
if len(node.values) != 2:
continue
left, right = node.values
if not (isinstance(left, ast.Compare) and isinstance(right, ast.Compare)):
continue
if len(left.ops) != 1 or len(right.ops) != 1:
continue
if not (isinstance(left.ops[0], CHAIN_OPS) and isinstance(right.ops[0], CHAIN_OPS)):
continue
if _keys_of(left.comparators[0]) != _keys_of(right.left):
continue
if left.lineno != left.end_lineno or right.lineno != right.end_lineno:
continue
out.append({"symbol": _home(tree, node), "line": node.lineno,
"end": node.end_lineno, "col": node.col_offset,
"end_col": node.end_col_offset,
"evidence": "two comparisons joined over the same middle value"})
if not out:
return [], "NO_SHAPE"
return out, None
def edit_chained_comparison(path: str, lines: List[str], target: Target) -> List[Edit]:
"""Rewrite the whole test on one line from the tree, so nothing is guessed."""
idx = target["line"] - 1
if idx < 0 or idx >= len(lines):
return []
old_line = lines[idx]
tree = ast.parse("\n".join(lines))
wanted = (target["col"], target["end_col"])
for node in ast.walk(tree):
if not isinstance(node, ast.BoolOp) or not isinstance(node.op, ast.And):
continue
if len(node.values) != 2:
continue
left, right = node.values
if (node.col_offset, node.end_col_offset) != wanted:
continue
if not (isinstance(left, ast.Compare) and isinstance(right, ast.Compare)):
continue
chain = ast.Compare(left=left.left, ops=[left.ops[0], right.ops[0]],
comparators=[left.comparators[0], right.comparators[0]])
chained = ast.unparse(chain)
new = old_line[:left.col_offset] + chained + old_line[right.end_col_offset:]
if new == old_line:
return []
return [{"file": path, "search": old_line, "replace": new}]
return []
def lock_chained_comparison(target: Target) -> str:
return (
"def test_%(symbol)s_chains_its_comparison():\n"
" for node in ast.walk(_tree()):\n"
" if not (isinstance(node, ast.BoolOp) and isinstance(node.op, ast.And)):\n"
" continue\n"
" if len(node.values) != 2:\n"
" continue\n"
" left, right = node.values\n"
" if not (isinstance(left, ast.Compare) and isinstance(right, ast.Compare)):\n"
" continue\n"
" assert ast.dump(left.comparators[0]) != ast.dump(right.left), \\\n"
" 'two comparisons joined over one middle value'\n"
% {"symbol": target.get("symbol", "demo")}
)
# ------------------------------------------------ batch three of the growth wave
def match_redundant_open_mode(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
"""open called with the mode it already defaults to."""
out: List[Target] = []
for node in ast.walk(tree):
if not (isinstance(node, ast.Call) and isinstance(node.func, ast.Name)
and node.func.id == "open"):
continue
if node.keywords or len(node.args) != 2:
continue
mode = node.args[1]
if isinstance(mode, ast.Constant) and mode.value == "r":
out.append({"symbol": _home(tree, node), "line": node.lineno,
"end": node.end_lineno, "col": node.col_offset,
"end_col": node.end_col_offset,
"evidence": "open given the mode it already has"})
if not out:
return [], "NO_SHAPE"
return out, None
def edit_redundant_open_mode(path: str, lines: List[str], target: Target) -> List[Edit]:
idx = target["line"] - 1
if idx < 0 or idx >= len(lines):
return []
old = lines[idx]
new = re.sub(r"(open\([^()]*)\s*,\s*[\"']r[\"']\s*\)", r"\1)", old)
if new == old:
return []
return [{"file": path, "search": old, "replace": new}]
def lock_redundant_open_mode(target: Target) -> str:
return (
"def test_%(symbol)s_opens_without_the_default_mode():\n"
" for node in ast.walk(_tree()):\n"
" if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) \\\n"
" and node.func.id == 'open' and len(node.args) >= 2:\n"
" mode = node.args[1]\n"
" assert not (isinstance(mode, ast.Constant) and mode.value == 'r'), \\\n"
" 'open given the mode it already has'\n"
% {"symbol": target.get("symbol", "demo")}
)
def match_identity_literal(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
"""Identity tested against a literal, where equality is what is asked."""
out: List[Target] = []
for node in ast.walk(tree):
if not isinstance(node, ast.Compare):
continue
for op, comparator in zip(node.ops, node.comparators):
if not isinstance(op, (ast.Is, ast.IsNot)):
continue
if isinstance(comparator, ast.Constant) and comparator.value is not None:
out.append({"symbol": _home(tree, node), "line": node.lineno,
"end": node.end_lineno, "col": node.col_offset,
"end_col": node.end_col_offset,
"evidence": "identity tested against a literal"})
break
if not out:
return [], "NO_SHAPE"
return out, None
def edit_identity_literal(path: str, lines: List[str], target: Target) -> List[Edit]:
idx = target["line"] - 1
if idx < 0 or idx >= len(lines):
return []
old = lines[idx]
new = re.sub(r"\bis\s+not\s+", "!=", old)
new = re.sub(r"\bis\s+", "== ", new)
if new == old:
return []
return [{"file": path, "search": old, "replace": new}]
def lock_identity_literal(target: Target) -> str:
return (
"def test_%(symbol)s_compares_literals_by_value():\n"
" for node in ast.walk(_tree()):\n"
" if not isinstance(node, ast.Compare):\n"
" continue\n"
" for op, other in zip(node.ops, node.comparators):\n"
" if isinstance(op, (ast.Is, ast.IsNot)) \\\n"
" and isinstance(other, ast.Constant) and other.value is not None:\n"
" assert False, 'identity tested against a literal'\n"
% {"symbol": target.get("symbol", "demo")}
)
def match_bool_in_condition(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
"""A bool call sitting where the language already asks for truth."""
out: List[Target] = []
for node in ast.walk(tree):
if not isinstance(node, (ast.If, ast.While)) or node.test is None:
continue
test = node.test
if (isinstance(test, ast.Call) and isinstance(test.func, ast.Name)
and test.func.id == "bool" and len(test.args) == 1 and not test.keywords):
out.append({"symbol": _home(tree, test), "line": test.lineno,
"end": test.end_lineno, "col": test.col_offset,
"end_col": test.end_col_offset,
"evidence": "bool called inside a test"})
if not out:
return [], "NO_SHAPE"
return out, None
def edit_bool_in_condition(path: str, lines: List[str], target: Target) -> List[Edit]:
idx = target["line"] - 1
if idx < 0 or idx >= len(lines):
return []
old = lines[idx]
new = re.sub(r"\bbool\(([^()]*)\)", r"\1", old)
if new == old:
return []
return [{"file": path, "search": old, "replace": new}]
def lock_bool_in_condition(target: Target) -> str:
return (
"def test_%(symbol)s_tests_the_value_directly():\n"
" for node in ast.walk(_tree()):\n"
" if not isinstance(node, (ast.If, ast.While)):\n"
" continue\n"
" test = node.test\n"
" assert not (isinstance(test, ast.Call) \\\n"
" and isinstance(test.func, ast.Name) and test.func.id == 'bool'), \\\n"
" 'bool called inside a test'\n"
% {"symbol": target.get("symbol", "demo")}
)
def match_lambda_assignment(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
"""A lambda bound to a name, which the language writes as a def."""
out: List[Target] = []
for node in ast.walk(tree):
if not isinstance(node, ast.Assign) or len(node.targets) != 1:
continue
name = node.targets[0]
if isinstance(name, ast.Name) and isinstance(node.value, ast.Lambda):
out.append({"symbol": name.id, "line": node.lineno,
"end": node.end_lineno, "col": node.col_offset,
"end_col": node.end_col_offset,
"evidence": "lambda bound to the name %s" % name.id})
if not out:
return [], "NO_SHAPE"
return out, None
def edit_lambda_assignment(path: str, lines: List[str], target: Target) -> List[Edit]:
idx = target["line"] - 1
if idx < 0 or idx >= len(lines):
return []
tree = ast.parse("\n".join(lines))
for node in ast.walk(tree):
if not isinstance(node, ast.Assign) or node.lineno != target["line"]:
continue
if not isinstance(node.value, ast.Lambda):
continue
body = ast.unparse(node.value.body)
header = "def %s(%s):" % (target["symbol"], ast.unparse(node.value.args))
indent = " " * node.col_offset
new = indent + header + "\n" + indent + " return " + body
return [{"file": path, "search": lines[idx], "replace": new}]
return []
def lock_lambda_assignment(target: Target) -> str:
return (
"def test_%(symbol)s_is_a_named_function():\n"
" for node in ast.walk(_tree()):\n"
" assert not (isinstance(node, ast.Assign) \\\n"
" and isinstance(node.value, ast.Lambda)), 'lambda bound to a name'\n"
% {"symbol": target.get("symbol", "demo")}
)
def match_bool_branch_assign(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
"""Two branches that only set the same flag to True or False."""
out: List[Target] = []
for node in ast.walk(tree):
if not isinstance(node, ast.If) or len(node.body) != 1 or len(node.orelse) != 1:
continue
first, second = node.body[0], node.orelse[0]
if not (isinstance(first, ast.Assign) and isinstance(second, ast.Assign)):
continue
if not (isinstance(first.targets[0], ast.Name)
and isinstance(second.targets[0], ast.Name)
and first.targets[0].id == second.targets[0].id):
continue
if not (isinstance(first.value, ast.Constant) and first.value.value is True
and isinstance(second.value, ast.Constant) and second.value.value is False):
continue
out.append({"symbol": first.targets[0].id, "line": node.lineno,
"end": node.end_lineno, "col": node.col_offset,
"end_col": node.end_col_offset,
"evidence": "both branches only set %s to True or False"
% first.targets[0].id})
if not out:
return [], "NO_SHAPE"
return out, None
def edit_bool_branch_assign(path: str, lines: List[str], target: Target) -> List[Edit]:
start, end = target["line"] - 1, target["end"] - 1
block = "\n".join(lines[start:end + 1])
node = ast.parse(textwrap.dedent(block)).body[0]
if not isinstance(node, ast.If):
return []
truth = isinstance(node.body[0].value, ast.Constant) and node.body[0].value.value is True
indent = lines[start][:len(lines[start]) - len(lines[start].lstrip())]
value = ast.unparse(node.test) if truth else "not (%s)" % ast.unparse(node.test)
new = "%s%s = %s" % (indent, target["symbol"], value)
return [{"file": path, "search": block, "replace": new}]
def lock_bool_branch_assign(target: Target) -> str:
return (
"def test_%(symbol)s_is_assigned_once():\n"
" for node in ast.walk(_tree()):\n"
" if not isinstance(node, ast.If) or len(node.body) != 1 or len(node.orelse) != 1:\n"
" continue\n"
" first, second = node.body[0], node.orelse[0]\n"
" if not (isinstance(first, ast.Assign) and isinstance(second, ast.Assign)):\n"
" continue\n"
" assert not (isinstance(first.value, ast.Constant) \\\n"
" and isinstance(second.value, ast.Constant) \\\n"
" and first.value.value is True and second.value.value is False), \\\n"
" 'the two branches only set a flag'\n"
% {"symbol": target.get("symbol", "demo")}
)
# ------------------------------------------------ batch four of the growth wave
EMPTY_CALLS = {"list": "[]", "dict": "{}", "tuple": "()"}
def match_empty_container_call(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
"""An empty container built by calling its type instead of writing it."""
out: List[Target] = []
for node in ast.walk(tree):
if not isinstance(node, ast.Call) or not isinstance(node.func, ast.Name):
continue
if node.func.id in EMPTY_CALLS and not node.args and not node.keywords:
out.append({"symbol": _home(tree, node), "line": node.lineno,
"end": node.end_lineno, "col": node.col_offset,
"end_col": node.end_col_offset,
"evidence": "an empty %s written as a call" % node.func.id})
if not out:
return [], "NO_SHAPE"
return out, None
def edit_empty_container_call(path: str, lines: List[str], target: Target) -> List[Edit]:
idx = target["line"] - 1
if idx < 0 or idx >= len(lines):
return []
old = lines[idx]
new = re.sub(r"\b(list|dict|tuple)\(\)", lambda m: EMPTY_CALLS[m.group(1)], old)
if new == old:
return []
return [{"file": path, "search": old, "replace": new}]
def lock_empty_container_call(target: Target) -> str:
return (
"def test_%(symbol)s_writes_the_empty_container():\n"
" for node in ast.walk(_tree()):\n"
" if not isinstance(node, ast.Call) or not isinstance(node.func, ast.Name):\n"
" continue\n"
" assert not (node.func.id in ('list', 'dict', 'tuple') \\\n"
" and not node.args and not node.keywords), \\\n"
" 'an empty container written as a call'\n"
% {"symbol": target.get("symbol", "demo")}
)
def match_equality_with_empty_list(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
"""Emptiness tested by comparing a value with an empty list."""
out: List[Target] = []
for node in ast.walk(tree):
if not isinstance(node, ast.Compare) or len(node.ops) != 1:
continue
if not isinstance(node.ops[0], ast.Eq):
continue
other = node.comparators[0]
if isinstance(other, ast.List) and not other.elts:
out.append({"symbol": _home(tree, node), "line": node.lineno,
"end": node.end_lineno, "col": node.col_offset,
"end_col": node.end_col_offset,
"evidence": "a value compared with an empty list"})
if not out:
return [], "NO_SHAPE"
return out, None
def edit_equality_with_empty_list(path: str, lines: List[str], target: Target) -> List[Edit]:
idx = target["line"] - 1
if idx < 0 or idx >= len(lines):
return []
old = lines[idx]
new = re.sub(r"([A-Za-z_][A-Za-z_0-9]*)\s*==\s*\[\s*\]", r"not (\1)", old)
if new == old:
return []
return [{"file": path, "search": old, "replace": new}]
def lock_equality_with_empty_list(target: Target) -> str:
return (
"def test_%(symbol)s_tests_emptiness_directly():\n"
" for node in ast.walk(_tree()):\n"
" if not isinstance(node, ast.Compare) or len(node.ops) != 1:\n"
" continue\n"
" if not isinstance(node.ops[0], ast.Eq):\n"
" continue\n"
" other = node.comparators[0]\n"
" assert not (isinstance(other, ast.List) and not other.elts), \\\n"
" 'a value compared with an empty list'\n"
% {"symbol": target.get("symbol", "demo")}
)
def match_type_equality(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
"""A type read with type() and compared, where isinstance is the question."""
out: List[Target] = []
for node in ast.walk(tree):
if not isinstance(node, ast.Compare) or len(node.ops) != 1:
continue
if not isinstance(node.ops[0], (ast.Eq, ast.NotEq)):
continue
left = node.left
if not (isinstance(left, ast.Call) and isinstance(left.func, ast.Name)
and left.func.id == "type" and len(left.args) == 1 and not left.keywords):
continue
if not isinstance(node.comparators[0], ast.Name):
continue
out.append({"symbol": _home(tree, node), "line": node.lineno,
"end": node.end_lineno, "col": node.col_offset,
"end_col": node.end_col_offset,
"evidence": "the type compared with equality instead of isinstance"})
if not out:
return [], "NO_SHAPE"
return out, None
def edit_type_equality(path: str, lines: List[str], target: Target) -> List[Edit]:
idx = target["line"] - 1
if idx < 0 or idx >= len(lines):
return []
old = lines[idx]
new = re.sub(r"type\(([^()]*)\)\s*==\s*([A-Za-z_][A-Za-z_0-9]*)", r"isinstance(\1, \2)", old)
new = re.sub(r"type\(([^()]*)\)\s*!=\s*([A-Za-z_][A-Za-z_0-9]*)",
r"not isinstance(\1, \2)", new)
if new == old:
return []
return [{"file": path, "search": old, "replace": new}]
def lock_type_equality(target: Target) -> str:
return (
"def test_%(symbol)s_asks_isinstance():\n"
" for node in ast.walk(_tree()):\n"
" if not isinstance(node, ast.Compare):\n"
" continue\n"
" left = node.left\n"
" assert not (isinstance(left, ast.Call) \\\n"
" and isinstance(left.func, ast.Name) and left.func.id == 'type'), \\\n"
" 'a type compared with equality'\n"
% {"symbol": target.get("symbol", "demo")}
)
def match_lambda_wrapper(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
"""A lambda that only forwards its single argument to another call."""
out: List[Target] = []
for node in ast.walk(tree):
if not isinstance(node, ast.Lambda) or len(node.args.args) != 1:
continue
arg = node.args.args[0].arg
body = node.body
if (isinstance(body, ast.Call) and isinstance(body.func, ast.Name)
and len(body.args) == 1 and not body.keywords
and isinstance(body.args[0], ast.Name) and body.args[0].id == arg):
out.append({"symbol": _home(tree, node), "line": node.lineno,
"end": node.end_lineno, "col": node.col_offset,
"end_col": node.end_col_offset,
"evidence": "a lambda forwarding one argument to %s" % body.func.id})
if not out:
return [], "NO_SHAPE"
return out, None
def edit_lambda_wrapper(path: str, lines: List[str], target: Target) -> List[Edit]:
idx = target["line"] - 1
if idx < 0 or idx >= len(lines):
return []
old = lines[idx]
new = re.sub(r"lambda\s+([A-Za-z_][A-Za-z_0-9]*)\s*:\s*([A-Za-z_][A-Za-z_0-9]*)\(\s*\1\s*\)",
r"\2", old)
if new == old:
return []
return [{"file": path, "search": old, "replace": new}]
def lock_lambda_wrapper(target: Target) -> str:
return (
"def test_%(symbol)s_passes_the_function_itself():\n"
" for node in ast.walk(_tree()):\n"
" if not isinstance(node, ast.Lambda) or len(node.args.args) != 1:\n"
" continue\n"
" arg = node.args.args[0].arg\n"
" body = node.body\n"
" assert not (isinstance(body, ast.Call) and isinstance(body.func, ast.Name) \\\n"
" and len(body.args) == 1 and not body.keywords \\\n"
" and isinstance(body.args[0], ast.Name) and body.args[0].id == arg), \\\n"
" 'a lambda forwarding one argument to a call'\n"
% {"symbol": target.get("symbol", "demo")}
)
def match_list_in_aggregator(lines: List[str], tree: ast.Module) -> Tuple[List[Target], Optional[str]]:
"""A list comprehension built only to be read once by sum, min or max."""
out: List[Target] = []
for node in ast.walk(tree):
if not isinstance(node, ast.Call) or not isinstance(node.func, ast.Name):
continue
if node.func.id not in ("sum", "min", "max") or len(node.args) != 1:
continue
first = node.args[0]
if isinstance(first, ast.ListComp) and first.lineno == first.end_lineno:
out.append({"symbol": _home(tree, node), "line": node.lineno,
"end": node.end_lineno, "col": node.col_offset,
"end_col": node.end_col_offset,
"evidence": "%s given a list built to be read once" % node.func.id})
if not out:
return [], "NO_SHAPE"
return out, None
def edit_list_in_aggregator(path: str, lines: List[str], target: Target) -> List[Edit]:
idx = target["line"] - 1
if idx < 0 or idx >= len(lines):
return []
old = lines[idx]
new = re.sub(r"\b(sum|min|max)\(\s*\[([^\[\]]+)\]\s*\)", r"\1(\2)", old)
if new == old:
return []
return [{"file": path, "search": old, "replace": new}]
def lock_list_in_aggregator(target: Target) -> str:
return (
"def test_%(symbol)s_reads_the_generator():\n"
" for node in ast.walk(_tree()):\n"
" if not isinstance(node, ast.Call) or not isinstance(node.func, ast.Name):\n"
" continue\n"
" if node.func.id not in ('sum', 'min', 'max') or len(node.args) != 1:\n"
" continue\n"
" first = node.args[0]\n"
" assert not isinstance(first, ast.ListComp), \\\n"
" 'an aggregator given a list built to be read once'\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,
"none-compare": match_none_compare,
"dict-keys-in": match_dict_keys_in,
"useless-pass": match_useless_pass,
"no-else-return": match_no_else_return,
"sorted-first": match_sorted_first,
"dict-keys-loop": match_dict_keys_loop,
"not-in-test": match_not_in_test,
"redundant-slice": match_redundant_slice,
"double-negation": match_double_negation,
"chained-comparison": match_chained_comparison,
"redundant-open-mode": match_redundant_open_mode,
"identity-literal": match_identity_literal,
"bool-in-condition": match_bool_in_condition,
"lambda-assignment": match_lambda_assignment,
"bool-branch-assign": match_bool_branch_assign,
"empty-container-call": match_empty_container_call,
"equality-with-empty-list": match_equality_with_empty_list,
"type-equality": match_type_equality,
"lambda-wrapper": match_lambda_wrapper,
"list-in-aggregator": match_list_in_aggregator,
}
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,
"none-compare": edit_none_compare,
"dict-keys-in": edit_dict_keys_in,
"useless-pass": edit_useless_pass,
"no-else-return": edit_no_else_return,
"sorted-first": edit_sorted_first,
"dict-keys-loop": edit_dict_keys_loop,
"not-in-test": edit_not_in_test,
"redundant-slice": edit_redundant_slice,
"double-negation": edit_double_negation,
"chained-comparison": edit_chained_comparison,
"redundant-open-mode": edit_redundant_open_mode,
"identity-literal": edit_identity_literal,
"bool-in-condition": edit_bool_in_condition,
"lambda-assignment": edit_lambda_assignment,
"bool-branch-assign": edit_bool_branch_assign,
"empty-container-call": edit_empty_container_call,
"equality-with-empty-list": edit_equality_with_empty_list,
"type-equality": edit_type_equality,
"lambda-wrapper": edit_lambda_wrapper,
"list-in-aggregator": edit_list_in_aggregator,
}
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,
"none-compare": lock_none_compare,
"dict-keys-in": lock_dict_keys_in,
"useless-pass": lock_useless_pass,
"no-else-return": lock_no_else_return,
"sorted-first": lock_sorted_first,
"dict-keys-loop": lock_dict_keys_loop,
"not-in-test": lock_not_in_test,
"redundant-slice": lock_redundant_slice,
"double-negation": lock_double_negation,
"chained-comparison": lock_chained_comparison,
"redundant-open-mode": lock_redundant_open_mode,
"identity-literal": lock_identity_literal,
"bool-in-condition": lock_bool_in_condition,
"lambda-assignment": lock_lambda_assignment,
"bool-branch-assign": lock_bool_branch_assign,
"empty-container-call": lock_empty_container_call,
"equality-with-empty-list": lock_equality_with_empty_list,
"type-equality": lock_type_equality,
"lambda-wrapper": lock_lambda_wrapper,
"list-in-aggregator": lock_list_in_aggregator,
}
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)
|