Download lingologos_thinkingpython/shapes.py from tailot/lingologos-thinkingpython: direct link, hf CLI and curl.
- Browser
- Download file 103 kB
-
https://huggingface.co/datasets/tailot/lingologos-thinkingpython/resolve/main/lingologos_thinkingpython/shapes.py
- Command line
-
hf download hf://datasets/tailot/lingologos-thinkingpython/lingologos_thinkingpython/shapes.py
-
curl -L -o shapes.py https://huggingface.co/datasets/tailot/lingologos-thinkingpython/resolve/main/lingologos_thinkingpython/shapes.py
103 kB
"""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)
"""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),