tailot's picture
thinking-python: reference implementation, corpus and gates
35d4b41 verified
Raw History Blame Contribute Delete
59 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")} ) MATCHERS = { "mutable-default": match_mutable_default, "magic-literal": match_magic_literal, "guard-clause": match_guard_clause, "dead-import": match_dead_import, "loop-comprehension": match_loop_comprehension, "concat-fstring": match_concat_fstring, "add-assertion": match_add_assertion, "unused-local": match_unused_local, "unreachable-code": match_unreachable_code, "empty-except": match_empty_except, "bare-except": match_bare_except, "bool-prefix": match_bool_prefix, "len-zero": match_len_zero, "bool-compare": match_bool_compare, "dict-get": match_dict_get, "redundant-list": match_redundant_list, "str-of-string": match_str_of_string, "open-context": match_open_context, "range-len": match_range_len, "dataclass-init": match_dataclass_init, } EDITORS = { "mutable-default": _fill_mutable_default, "magic-literal": edit_magic_literal, "guard-clause": edit_guard_clause, "dead-import": edit_dead_import, "loop-comprehension": edit_loop_comprehension, "concat-fstring": edit_concat_fstring, "add-assertion": edit_add_assertion, "unused-local": edit_unused_local, "unreachable-code": edit_unreachable_code, "empty-except": edit_empty_except, "bare-except": edit_bare_except, "bool-prefix": edit_bool_prefix, "len-zero": edit_len_zero, "bool-compare": edit_bool_compare, "dict-get": edit_dict_get, "redundant-list": edit_redundant_list, "str-of-string": edit_str_of_string, "open-context": edit_open_context, "range-len": edit_range_len, "dataclass-init": edit_dataclass_init, } LOCKS = { "mutable-default": lock_mutable_default, "magic-literal": lock_magic_literal, "guard-clause": lock_guard_clause, "dead-import": lock_dead_import, "loop-comprehension": lock_loop_comprehension, "concat-fstring": lock_concat_fstring, "add-assertion": lock_add_assertion, "unused-local": lock_unused_local, "unreachable-code": lock_unreachable_code, "empty-except": lock_empty_except, "bare-except": lock_bare_except, "bool-prefix": lock_bool_prefix, "len-zero": lock_len_zero, "bool-compare": lock_bool_compare, "dict-get": lock_dict_get, "redundant-list": lock_redundant_list, "str-of-string": lock_str_of_string, "open-context": lock_open_context, "range-len": lock_range_len, "dataclass-init": lock_dataclass_init, } def match(shape: str, source: str) -> Tuple[List[Target], Optional[str]]: try: tree = ast.parse(source) except SyntaxError: return [], "UNPARSEABLE_TARGET" fn = MATCHERS.get(shape) if fn is None: return [], "NO_SHAPE" return fn(source.splitlines(), tree) def edits(shape: str, path: str, source: str, target: Target) -> List[Edit]: editor = EDITORS.get(shape) if editor is None: return [] return editor(path, source.splitlines(), target) def lock(shape: str, target: Target) -> str: maker = LOCKS.get(shape) if maker is None: return "" return maker(target) def shapes() -> List[str]: return sorted(MATCHERS)
"""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),