tailot's picture
Upload folder using huggingface_hub
f4952b6 verified
Raw History Blame Contribute Delete
73.4 kB
"""Structural rules: where a pattern applies in a real file, and what text it writes. A pattern in this bundle is not a snippet to paste. It is a predicate over the syntax tree plus a text transform that has to survive the kernel patcher, so this module does two things and nothing else: it decides whether a named function is in the shape a pattern claims to improve, and it builds the exact search and replace pair for it. When the shape is not there it says why with a code, and that code is what a negative row of ``patterns/pattern_cases.jsonl`` claims, which is what the ``pattern_round_trip`` gate re-checks by running the rule again. Four boundaries are stated rather than assumed. * Offsets. A syntax tree column is a byte offset. Anchors here are built from those offsets, so a target file that is not ASCII is refused instead of patched at the wrong place, and a file indented with a tab is refused instead of getting spaces mixed into one block. * Endings. The catalog anchors on LF text, so a CRLF target is refused with ``CRLF_TARGET``. A hand written edit through the kernel patcher still preserves the endings of a CRLF file; that guarantee is the kernel's and is untouched here. * Shape. A rule refuses the shapes it has not read: a handle that is stored or returned, a chain that falls through instead of raising, a check that is not the first statement. Refusing is a result, not an error, and a refusal writes nothing. * Evidence. A rule never runs the code it reads. The lock test it appends to a test file is for the test gate of a run to execute, and it is written so that it fails when the primary edit did not land. That coupling is the whole reason a companion exists. """ from __future__ import annotations import ast import keyword import re from dataclasses import dataclass from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union # Refusal codes. A negative row names one of these and the gate re-runs the rule to check # that the rule still answers with exactly that code for exactly that target. MISSING_TARGET_FILE = "MISSING_TARGET_FILE" NO_SUCH_FUNCTION = "NO_SUCH_FUNCTION" NOT_A_MODULE_FUNCTION = "NOT_A_MODULE_FUNCTION" NOT_PARSEABLE = "NOT_PARSEABLE" NOT_ASCII_TARGET = "NOT_ASCII_TARGET" TAB_INDENTED_TARGET = "TAB_INDENTED_TARGET" CRLF_TARGET = "CRLF_TARGET" NO_TEST_FILE = "NO_TEST_FILE" NO_TEST_ANCHOR = "NO_TEST_ANCHOR" AMBIGUOUS_TEST_ANCHOR = "AMBIGUOUS_TEST_ANCHOR" ALREADY_ANNOTATED = "ALREADY_ANNOTATED" NOT_A_MUTABLE_DEFAULT = "NOT_A_MUTABLE_DEFAULT" ANNOTATED_MUTABLE_DEFAULT = "ANNOTATED_MUTABLE_DEFAULT" GUARD_ALREADY_PRESENT = "GUARD_ALREADY_PRESENT" NO_DISPATCH_CHAIN = "NO_DISPATCH_CHAIN" BRANCH_SHAPE_MISMATCH = "BRANCH_SHAPE_MISMATCH" ALREADY_SCOPED = "ALREADY_SCOPED" NO_BARE_OPEN = "NO_BARE_OPEN" HANDLE_ESCAPE = "HANDLE_ESCAPE" NOT_THE_FIRST_STATEMENT = "NOT_THE_FIRST_STATEMENT" ASYNC_TARGET = "ASYNC_TARGET" NON_LITERAL_ASSERT_MESSAGE = "NON_LITERAL_ASSERT_MESSAGE" INVALID_COMPANION_PATH = "INVALID_COMPANION_PATH" ANCHOR_OVERLAP = "ANCHOR_OVERLAP" NO_BARE_EXCEPT = "NO_BARE_EXCEPT" BARE_EXCEPT_RE_RAISES = "BARE_EXCEPT_RE_RAISES" EXCEPT_HANDLER_UNREADABLE = "EXCEPT_HANDLER_UNREADABLE" NO_NONE_COMPARISON = "NO_NONE_COMPARISON" NONE_COMPARISON_IS_CHAINED = "NONE_COMPARISON_IS_CHAINED" NO_EMPTY_LEN_CHECK = "NO_EMPTY_LEN_CHECK" LEN_TARGET_IS_NOT_A_NAME = "LEN_TARGET_IS_NOT_A_NAME" NO_SUCH_CLASS = "NO_SUCH_CLASS" NOT_A_MODULE_CLASS = "NOT_A_MODULE_CLASS" NOT_A_METHOD = "NOT_A_METHOD" NO_INIT_METHOD = "NO_INIT_METHOD" INIT_TAKES_MORE_THAN_SELF = "INIT_TAKES_MORE_THAN_SELF" SUPER_CALL_ALREADY_FIRST = "SUPER_CALL_ALREADY_FIRST" SUPER_BASES_UNREADABLE = "SUPER_BASES_UNREADABLE" NO_UNUSED_IMPORT = "NO_UNUSED_IMPORT" STAR_IMPORT_IN_FILE = "STAR_IMPORT_IN_FILE" NAME_LISTED_IN_ALL = "NAME_LISTED_IN_ALL" PACKAGE_FILE_TARGET = "PACKAGE_FILE_TARGET" IMPORTS_NOT_CONTIGUOUS = "IMPORTS_NOT_CONTIGUOUS" INDENT = " " _MUTABLE_LITERALS = (ast.List, ast.Dict, ast.Set) _MUTABLE_CALLS = ("list", "dict", "set") @dataclass(frozen=True) class Target: """One function a caller wants a pattern looked at, read from a workspace.""" rel_posix: str symbol: str text: str tree: ast.Module read: Callable[[str], Optional[str]] @dataclass(frozen=True) class Edit: """One file the pattern would write, as a search and replace pair.""" file: str search: str replace: str label: str @dataclass(frozen=True) class RuleHit: """The pattern applies: ``edits`` is the function change first, the lock test second.""" rule: str target: str edits: Tuple[Edit, ...] evidence: Tuple[str, ...] reason_code: str = "" @dataclass(frozen=True) class RuleMiss: """The pattern does not apply, with the reason a corpus row is allowed to claim.""" reason_code: str detail: str target: str = "" Outcome = Union[RuleHit, RuleMiss] def target_label(rel_posix: str, symbol: str) -> str: return "%s::%s" % (rel_posix, symbol) def _miss(rel_posix: str, symbol: str, code: str, detail: str) -> RuleMiss: return RuleMiss(reason_code=code, detail=detail, target=target_label(rel_posix, symbol)) def _no_companion(target: Target, companion: Optional[RuleMiss]) -> RuleMiss: if companion is not None: return companion return _miss(target.rel_posix, target.symbol, NO_TEST_FILE, "no lock test could be written") # --------------------------------------------------------------------------- # Offsets, so that an anchor is the file and not an impression of it. # --------------------------------------------------------------------------- def line_starts(text: str) -> List[int]: """Absolute character offset of every line, numbered like the syntax tree.""" starts = [0] for index, char in enumerate(text): if char == "\n": starts.append(index + 1) return starts def node_span(text: str, starts: Sequence[int], node: ast.AST) -> Tuple[int, int]: """Absolute start and end offsets of a node, or (-1, -1) when it has no position.""" lineno = getattr(node, "lineno", None) end_lineno = getattr(node, "end_lineno", None) if lineno is None or end_lineno is None or end_lineno > len(starts): return -1, -1 start = starts[lineno - 1] + int(getattr(node, "col_offset", 0)) end = starts[end_lineno - 1] + int(getattr(node, "end_col_offset", 0)) if start < 0 or end < start or end > len(text): return -1, -1 return start, end def segment_of(text: str, starts: Sequence[int], node: ast.AST) -> str: """The exact text a node covers in the file it was parsed from.""" start, end = node_span(text, starts, node) if start < 0: return "" return text[start:end] @dataclass(frozen=True) class _Splice: start: int end: int text: str def apply_splices(text: str, start: int, end: int, splices: Sequence[_Splice]) -> str: """Rewrite ``text[start:end]`` out of spans, leaving everything else byte for byte.""" out: List[str] = [] cursor = start for splice in sorted(splices, key=lambda item: (item.start, item.end)): if splice.start < cursor or splice.end > end: raise ValueError("a splice does not fit inside the span it belongs to") out.append(text[cursor:splice.start]) out.append(splice.text) cursor = splice.end out.append(text[cursor:end]) return "".join(out) def _shifted(text: str, starts: Sequence[int], node: ast.AST, indent: str) -> str: """The text of a statement placed at ``indent``, with its own lines moved with it. A slice of a node starts at the first token of its first line and carries the original indentation of every line after that, so the first line gets the whole target indent and the others get the one level this block is being pushed by. """ raw = segment_of(text, starts, node) lines = raw.split("\n") moved = [indent + lines[0]] for line in lines[1:]: moved.append(INDENT + line if line.strip() else line) return "\n".join(moved) def _gap(text: str, start: int, end: int) -> str: """The blank lines between two statements, never more than one of them.""" return "\n\n" if text[start:end].count("\n") > 1 else "\n" # --------------------------------------------------------------------------- # Reading a target, and the shapes this module refuses to anchor on. # --------------------------------------------------------------------------- _SHAPE_DETAIL = { NOT_ASCII_TARGET: "the file is not ASCII, so a byte offset anchor is not trusted here", CRLF_TARGET: "the file ends its lines with CRLF and this catalog anchors on LF text", TAB_INDENTED_TARGET: "the file indents with a tab and the transform adds space indent", } def _shape_rejection(text: str) -> str: if not text.isascii(): return NOT_ASCII_TARGET if "\r\n" in text: return CRLF_TARGET for line in text.split("\n"): if line.lstrip(" ").startswith("\t"): return TAB_INDENTED_TARGET return "" def open_target(rel_posix: str, symbol: str, read: Callable[[str], Optional[str]]) -> Tuple[Optional[Target], Optional[RuleMiss]]: """Read and parse one target, with every refusal a corpus row may claim about it.""" text = read(rel_posix) if text is None: return None, _miss(rel_posix, symbol, MISSING_TARGET_FILE, "no such file: '%s'" % rel_posix) return open_target_from_text(rel_posix, symbol, text, read) def open_target_from_text(rel_posix: str, symbol: str, text: str, read: Callable[[str], Optional[str]]) -> Tuple[Optional[Target], Optional[RuleMiss]]: """The target for one file already read, with the shape refusal the reader cannot see.""" code = _shape_rejection(text) if code: return None, _miss(rel_posix, symbol, code, _SHAPE_DETAIL[code]) try: tree = ast.parse(text) except SyntaxError as exc: return None, _miss(rel_posix, symbol, NOT_PARSEABLE, "the file does not parse: %s" % exc.msg) return open_target_with_tree(rel_posix, symbol, text, tree, read) def open_target_with_tree(rel_posix: str, symbol: str, text: str, tree: ast.Module, read: Callable[[str], Optional[str]]) -> Tuple[Optional[Target], Optional[RuleMiss]]: """The target for a caller that has already read and parsed the file.""" code = _shape_rejection(text) if code: return None, _miss(rel_posix, symbol, code, _SHAPE_DETAIL[code]) return Target(rel_posix=rel_posix, symbol=symbol, text=text, tree=tree, read=read), None def module_function(target: Target, allow_async: bool = False) -> Tuple[Optional[ast.FunctionDef], Optional[RuleMiss]]: """The module level function the target names, or the refusal that says why not. A coroutine is a refusal unless the card opted in. A lock test written for a coroutine has to wait for it, and only the cards that do that name coroutines among their targets; the rest answer ASYNC_TARGET and say so on the card. """ for node in target.tree.body: if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == target.symbol: if isinstance(node, ast.AsyncFunctionDef) and not allow_async: return None, _miss( target.rel_posix, target.symbol, ASYNC_TARGET, "'%s' is a coroutine, and this card writes its lock test for a plain def" % target.symbol, ) return node, None for node in ast.walk(target.tree): if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == target.symbol: return None, _miss( target.rel_posix, target.symbol, NOT_A_MODULE_FUNCTION, "'%s' is not a module level function of this file" % target.symbol, ) return None, _miss( target.rel_posix, target.symbol, NO_SUCH_FUNCTION, "no function named '%s' in '%s'" % (target.symbol, target.rel_posix), ) # --------------------------------------------------------------------------- # The lock test that goes with a change. # --------------------------------------------------------------------------- def test_file_for(rel_posix: str) -> str: """The test file this layout pairs with a source file, by name.""" parts = [part for part in rel_posix.split("/") if part] stem = parts[-1][:-3] if parts[-1].endswith(".py") else parts[-1] return "tests/test_%s.py" % stem def import_statement_for(rel_posix: str) -> Tuple[str, str]: """The import that reaches a module without running anything, and the alias it binds.""" parts = [part for part in rel_posix.split("/") if part] stem = parts[-1][:-3] if parts[-1].endswith(".py") else parts[-1] package = [part for part in parts[:-1] if part != "__init__.py"] if package: return "from %s import %s" % (".".join(package), stem), stem return "import %s" % stem, stem def _companion_path_is_importable(rel_posix: str) -> bool: """True when the lock import for this path binds a module by a plain Python name.""" parts = [part for part in rel_posix.split("/") if part] if not parts or not parts[-1].endswith(".py"): return False names = [part for part in parts[:-1] if part != "__init__.py"] + [parts[-1][:-3]] return all(part.isidentifier() and not keyword.iskeyword(part) for part in names) def lock_source( rel_posix: str, test_name: str, docstring: str, statements: Sequence[str], headers: Sequence[str] = (), ) -> str: """One test function of ASCII, space indented text: imports, then the checks.""" import_statement, _alias = import_statement_for(rel_posix) lines = ["def test_%s() -> None:" % test_name, ' """%s"""' % docstring, " import inspect"] lines.extend(" %s" % line for line in headers) lines.append("") lines.append(" %s" % import_statement) for statement in statements: for line in statement.split("\n"): lines.append(" %s" % line if line.strip() else "") return "\n".join(lines) + "\n" def _append_lock(target: Target, test_rel: str, test_name: str, lock_text: str) -> Tuple[Optional[Edit], Optional[RuleMiss]]: """Append one test function after the last test function of a test file.""" text = target.read(test_rel) if text is None: return None, _miss(test_rel, target.symbol, NO_TEST_FILE, "no test file: '%s'" % test_rel) code = _shape_rejection(text) if code: return None, _miss(test_rel, target.symbol, code, "the test file: %s" % _SHAPE_DETAIL[code]) if not _companion_path_is_importable(target.rel_posix): return None, _miss( test_rel, target.symbol, INVALID_COMPANION_PATH, "the module path of '%s' has a part that is not a plain Python identifier, " "so no import in a lock test could reach it" % target.rel_posix, ) try: tree = ast.parse(text) except SyntaxError as exc: return None, _miss(test_rel, target.symbol, NOT_PARSEABLE, "the test file does not parse: %s" % exc.msg) last: Optional[ast.FunctionDef] = None for node in tree.body: if isinstance(node, ast.FunctionDef) and node.name.startswith("test_"): last = node if last is None: return None, _miss(test_rel, target.symbol, NO_TEST_ANCHOR, "no top level test function to append after") anchor = segment_of(text, line_starts(text), last) if not anchor: return None, _miss(test_rel, target.symbol, NO_TEST_ANCHOR, "no text for the anchor of the last test") times = text.count(anchor) if times != 1: return None, _miss( test_rel, target.symbol, AMBIGUOUS_TEST_ANCHOR, "the anchor text appears %d times in '%s'" % (times, test_rel), ) return ( Edit( file=test_rel, search=anchor, replace=anchor.rstrip("\n") + "\n\n\n" + lock_text, label="lock test 'test_%s' appended after '%s'" % (test_name, last.name), ), None, ) def _hit(rule: str, target: Target, edit: Edit, companion: Edit, evidence: Sequence[str]) -> RuleHit: return RuleHit( rule=rule, target=target_label(target.rel_posix, target.symbol), edits=(edit, companion), evidence=tuple(evidence), ) def _rewrite_function(target: Target, starts: Sequence[int], function: ast.FunctionDef, splices: Sequence[_Splice], label: str) -> Edit: start, end = node_span(target.text, starts, function) return Edit( file=target.rel_posix, search=target.text[start:end], replace=apply_splices(target.text, start, end, splices), label=label, ) def _parameters(function: ast.FunctionDef) -> List[ast.arg]: return list(function.args.posonlyargs) + list(function.args.args) + list(function.args.kwonlyargs) def _is_string_statement(statement: ast.stmt) -> bool: """A statement that is one string literal: the shape of a docstring.""" return ( isinstance(statement, ast.Expr) and isinstance(statement.value, ast.Constant) and isinstance(statement.value.value, str) ) def _defaults_by_name(function: ast.FunctionDef) -> Dict[str, ast.expr]: """Map each plain parameter to the default expression it carries, when it has one.""" positional = list(function.args.posonlyargs) + list(function.args.args) defaults: Dict[str, ast.expr] = {} offset = len(positional) - len(function.args.defaults) for index, argument in enumerate(positional): position = index - offset if position >= 0: defaults[argument.arg] = function.args.defaults[position] for argument, default in zip(function.args.kwonlyargs, function.args.kw_defaults): if default is not None: defaults[argument.arg] = default return defaults # --------------------------------------------------------------------------- # Rule 1: write down the type a literal default already states. # --------------------------------------------------------------------------- def _literal_type(node: ast.expr) -> Optional[str]: if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.UAdd, ast.USub)): return _literal_type(node.operand) if not isinstance(node, ast.Constant): return None value = node.value if isinstance(value, bool): return "bool" if isinstance(value, int): return "int" if isinstance(value, float): return "float" if isinstance(value, str): return "str" return None def rule_annotate_literal_defaults(target: Target) -> Outcome: """Annotate a parameter with the type of the literal default it already carries. A parameter whose default is ``None`` is left alone on purpose: the honest annotation for it is an Optional, and that needs an import this transform will not add. """ function, miss = module_function(target, allow_async=True) if function is None: return miss assert function is not None starts = line_starts(target.text) annotated = {argument.arg for argument in _parameters(function) if argument.annotation is not None} defaults = _defaults_by_name(function) position_of = {argument.arg: argument for argument in _parameters(function)} splices: List[_Splice] = [] touched: List[Tuple[str, str, str]] = [] for name in sorted(defaults): if name in annotated: continue inferred = _literal_type(defaults[name]) if inferred is None: continue argument = position_of[name] name_end = starts[argument.lineno - 1] + argument.col_offset + len(argument.arg) default_start, _default_end = node_span(target.text, starts, defaults[name]) splices.append(_Splice(start=name_end, end=default_start, text=": %s = " % inferred)) literal = repr(defaults[name].value) if isinstance(defaults[name], ast.Constant) else segment_of(target.text, starts, defaults[name]) touched.append((name, inferred, literal)) if not splices: return _miss( target.rel_posix, target.symbol, ALREADY_ANNOTATED, "no parameter of '%s' carries a literal default without an annotation" % target.symbol, ) alias = import_statement_for(target.rel_posix)[1] statements = ["parameters = inspect.signature(%s.%s).parameters" % (alias, target.symbol)] for name, inferred, literal in touched: statements.append("assert parameters[%r].annotation is %s" % (name, inferred)) statements.append("assert parameters[%r].default == %s" % (name, literal)) test_name = "%s_parameters_keep_their_defaults" % target.symbol lock = lock_source( target.rel_posix, test_name, "Lock the annotations this pattern added and the defaults it had to leave alone.", statements, ) companion, companion_miss = _append_lock(target, test_file_for(target.rel_posix), test_name, lock) if companion is None: return _no_companion(target, companion_miss) evidence = tuple("parameter '%s' takes its type from its own default %s" % (name, literal) for name, _inferred, literal in touched) return _hit( "annotate-literal-defaults", target, _rewrite_function(target, starts, function, splices, "signature of '%s'" % target.symbol), companion, evidence, ) # --------------------------------------------------------------------------- # Rule 2: a mutable default stops being shared. # --------------------------------------------------------------------------- def _is_mutable_default(node: ast.expr) -> bool: if isinstance(node, _MUTABLE_LITERALS): return True return ( isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id in _MUTABLE_CALLS and not node.args and not node.keywords ) def rule_mutable_default_to_none(target: Target) -> Outcome: """Replace a mutable default with ``None`` and rebuild the value inside the call. This is a behaviour change by design, and the only one in the catalog: the default stops being shared between calls. The guard reuses the literal that was written as the default, so the value each call starts from is the one the author wrote. """ function, miss = module_function(target, allow_async=True) if function is None: return miss assert function is not None starts = line_starts(target.text) named = {argument.arg: argument for argument in _parameters(function)} mutable = {name: node for name, node in _defaults_by_name(function).items() if _is_mutable_default(node)} if not mutable: return _miss( target.rel_posix, target.symbol, NOT_A_MUTABLE_DEFAULT, "no default of '%s' is a list, dict or set, so there is nothing shared to break" % target.symbol, ) for name in sorted(mutable): if named[name].annotation is not None: return _miss( target.rel_posix, target.symbol, ANNOTATED_MUTABLE_DEFAULT, "parameter '%s' of '%s' carries an annotation this rule would have to widen" % (name, target.symbol), ) # The guard goes below a docstring, never above it: a guard inserted before the # leading string statement would take the docstring of the function away. head = 1 if _is_string_statement(function.body[0]) else 0 if head < len(function.body): body_start = starts[function.body[head].lineno - 1] guard_lead, guard_trail = "", "\n" else: # A body of nothing but a docstring: the guard takes its own line below it. body_start = starts[function.body[-1].end_lineno - 1] + function.body[-1].end_col_offset guard_lead, guard_trail = "\n", "" guard_indent = " " * function.body[0].col_offset for name in sorted(mutable): literal = segment_of(target.text, starts, mutable[name]) guard = "%sif %s is None:\n%s%s%s = %s\n" % (guard_indent, name, guard_indent, INDENT, name, literal) if guard_trail and target.text[body_start:body_start + len(guard)] == guard: return _miss( target.rel_posix, target.symbol, GUARD_ALREADY_PRESENT, "'%s' already rebuilds '%s' on its first line" % (target.symbol, name), ) splices: List[_Splice] = [] for name in sorted(mutable): start, end = node_span(target.text, starts, mutable[name]) splices.append(_Splice(start=start, end=end, text="None")) for name in sorted(mutable): literal = segment_of(target.text, starts, mutable[name]) splices.append( _Splice( start=body_start, end=body_start, text="%s%sif %s is None:\n%s%s%s = %s%s" % (guard_lead, guard_indent, name, guard_indent, INDENT, name, literal, guard_trail), ) ) alias = import_statement_for(target.rel_posix)[1] statements = [ "signature = inspect.signature(%s.%s)" % (alias, target.symbol), "source = inspect.getsource(%s.%s)" % (alias, target.symbol), ] for name in sorted(mutable): statements.append("assert signature.parameters[%r].default is None" % name) statements.append("assert 'if %s is None:' in source" % name) test_name = "%s_has_no_shared_default" % target.symbol lock = lock_source( target.rel_posix, test_name, "Lock the default this pattern unshared, the guard that replaced it, and the call that no longer shares state.", statements + [ "first = %s" % _run_call(function, alias, target.symbol, _probe_arguments(function, mutable, "alpha")), "second = %s" % _run_call(function, alias, target.symbol, _probe_arguments(function, mutable, "beta")), "assert first != second", ], headers=_lock_headers(function), ) companion, companion_miss = _append_lock(target, test_file_for(target.rel_posix), test_name, lock) if companion is None: return _no_companion(target, companion_miss) evidence = tuple("the default of '%s' is a value every call would share" % name for name in sorted(mutable)) return _hit( "mutable-default-to-none", target, _rewrite_function(target, starts, function, splices, "shared default of '%s'" % target.symbol), companion, evidence, ) def _probe_arguments(function: ast.FunctionDef, mutable: Dict[str, ast.expr], word: str) -> str: """Arguments of one call that reaches the guard, carrying ``word`` for the rest. These values are placeholders, not claims about the domain. They differ between the two calls of the lock, so a default shared between calls cannot pass it, and the round trip gate runs the lock before it believes a pattern applies anywhere. """ needed = [ argument.arg for argument in function.args.args if argument.arg not in mutable and argument.arg not in _defaults_by_name(function) ] return ", ".join(repr(word) for _ in needed) def _run_call(function: ast.FunctionDef, alias: str, symbol: str, arguments: str) -> str: """One lock-test call of the target: straight for a def, through asyncio for a coroutine.""" call = "%s.%s(%s)" % (alias, symbol, arguments) if isinstance(function, ast.AsyncFunctionDef): return "asyncio.run(%s)" % call return call def _lock_headers(function: ast.FunctionDef) -> Tuple[str, ...]: """The extra imports a lock test needs when its target is a coroutine.""" if isinstance(function, ast.AsyncFunctionDef): return ("import asyncio",) return () # --------------------------------------------------------------------------- # Rule 3: an equality chain that returns calls becomes a registry. # --------------------------------------------------------------------------- def _refusal_name(node: ast.Raise) -> str: """The exception type a raise statement names, with or without its arguments.""" if isinstance(node.exc, ast.Name): return node.exc.id if isinstance(node.exc, ast.Call) and isinstance(node.exc.func, ast.Name): return node.exc.func.id return "" def _chain_branches(node: ast.If) -> Optional[Tuple[List[Tuple[str, str, List[str]]], ast.Raise]]: """Read an if or elif chain of ``name == literal`` tests that each return one call. Every branch has to take exactly the same arguments and the chain has to end by raising: a chain that falls through returns something a registry would not, and this rule does not guess what the fall through was meant to produce. """ branches: List[Tuple[str, str, List[str]]] = [] current: Optional[ast.If] = node shared: Optional[List[str]] = None while current is not None: test = current.test if not isinstance(test, ast.Compare) or len(test.ops) != 1 or not isinstance(test.ops[0], ast.Eq): return None if not isinstance(test.left, ast.Name) or len(test.comparators) != 1: return None key = test.comparators[0] if not isinstance(key, ast.Constant) or not isinstance(key.value, str): return None if len(current.body) != 1 or not isinstance(current.body[0], ast.Return) or current.body[0].value is None: return None value = current.body[0].value if not isinstance(value, ast.Call) or not isinstance(value.func, ast.Name) or value.keywords: return None arguments = [argument.id for argument in value.args if isinstance(argument, ast.Name)] if len(arguments) != len(value.args): return None if shared is None: shared = arguments elif shared != arguments: return None branches.append((str(key.value), value.func.id, arguments)) if len(current.orelse) != 1: return None follower = current.orelse[0] if isinstance(follower, ast.If): current = follower continue if isinstance(follower, ast.Raise) and _refusal_name(follower) and not follower.cause: return branches, follower return None return None def _module_level_names(tree: ast.Module) -> set: """Names a caller reaches as an attribute of this module, read from its top level.""" names: set = set() for node in tree.body: if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): names.add(node.name) elif isinstance(node, ast.Assign): names.update(target.id for target in node.targets if isinstance(target, ast.Name)) elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name): names.add(node.target.id) elif isinstance(node, (ast.Import, ast.ImportFrom)): for alias in node.names: names.add(alias.asname or alias.name.split(".")[0]) return names def rule_chain_to_registry(target: Target) -> Outcome: """Turn a chain of ``kind == literal`` returns into a dictionary and one lookup.""" function, miss = module_function(target) if function is None: return miss assert function is not None starts = line_starts(target.text) if len(function.body) != 1 or not isinstance(function.body[0], ast.If): return _miss(target.rel_posix, target.symbol, NO_DISPATCH_CHAIN, "the body of '%s' is not one if or elif chain" % target.symbol) chain = function.body[0] read = _chain_branches(chain) if read is None: return _miss( target.rel_posix, target.symbol, BRANCH_SHAPE_MISMATCH, "the chain in '%s' tests more than one name against text literals, its branches do not " "take the same arguments, or its last branch does not raise" % target.symbol, ) branches, tail = read keys = [key for key, _handler, _arguments in branches] if len(set(keys)) != len(keys): return _miss(target.rel_posix, target.symbol, BRANCH_SHAPE_MISMATCH, "two branches of '%s' test the same literal" % target.symbol) assert isinstance(chain.test, ast.Compare) and isinstance(chain.test.left, ast.Name) subject = chain.test.left.id if subject not in {argument.arg for argument in function.args.args + function.args.posonlyargs}: return _miss(target.rel_posix, target.symbol, BRANCH_SHAPE_MISMATCH, "'%s' is compared but is not a parameter" % subject) reachable = _module_level_names(target.tree) parameters = {argument.arg for argument in function.args.args} if function.args.vararg or function.args.kwarg or function.args.kwonlyargs or function.args.posonlyargs: return _miss( target.rel_posix, target.symbol, BRANCH_SHAPE_MISMATCH, "'%s' takes arguments this catalog does not know how to pass, so no lock could compare the answers" % target.symbol, ) for _key, _handler, arguments in branches: if not set(arguments) <= parameters: return _miss( target.rel_posix, target.symbol, BRANCH_SHAPE_MISMATCH, "a branch of '%s' passes something that is not a plain parameter of the chain" % target.symbol, ) for _key, handler, _arguments in branches: if handler not in reachable: return _miss( target.rel_posix, target.symbol, BRANCH_SHAPE_MISMATCH, "a branch of '%s' returns '%s', which is not a name of this module, so no lock could compare the answers" % (target.symbol, handler), ) raise_text = "raise " + segment_of(target.text, starts, tail.exc) indent = " " * chain.col_offset entries = ", ".join('"%s": %s' % (key, handler) for key, handler, _arguments in branches) arguments = ", ".join(branches[0][2]) block = ( "handlers = {%s}\n" % entries + "%shandled = handlers.get(%s)\n" % (indent, subject) + "%sif handled is None:\n" % indent + "%s%s%s\n" % (indent, INDENT, raise_text) + "%sreturn handled(%s)" % (indent, arguments) ) start, end = node_span(target.text, starts, chain) edit = _rewrite_function(target, starts, function, [_Splice(start=start, end=end, text=block)], "dispatch registry of '%s'" % target.symbol) alias = import_statement_for(target.rel_posix)[1] statements = ["source = inspect.getsource(%s.%s)" % (alias, target.symbol)] statements.append("assert 'handlers = {' in source") for key, handler, _arguments in branches: statements.append('assert \'"%s": %s\' in source' % (key, handler)) statements.append("assert 'handlers.get(%s)' in source" % subject) statements.append("assert 'elif' not in source") for key, handler, arguments in branches: statements.append( "assert %s.%s(%s) == %s.%s(%s)" % (alias, target.symbol, _call(function, _values(function, key)), alias, handler, _call_for(function, arguments, _values(function, key))) ) refusal = _refusal_name(tail) statements.append( "\n".join( ( "try:", " %s.%s(%s)" % (alias, target.symbol, _call(function, _values(function, "~no such kind~"))), "except %s:" % refusal, " pass", "else:", " raise AssertionError('%s accepted a kind no branch carries')" % target.symbol, ) ) ) test_name = "%s_dispatches_through_a_registry" % target.symbol lock = lock_source( target.rel_posix, test_name, "Lock the registry the chain became, and the answers the chain used to give.", statements, ) companion, companion_miss = _append_lock(target, test_file_for(target.rel_posix), test_name, lock) if companion is None: return _no_companion(target, companion_miss) evidence = tuple("the branch for '%s' returns %s" % (key, handler) for key, handler, _arguments in branches) return _hit("chain-to-registry", target, edit, companion, evidence) def _chain_subject(function: ast.FunctionDef) -> str: """The name every branch of the chain is compared against.""" first = function.body[0] if isinstance(first, ast.If) and isinstance(first.test, ast.Compare) and isinstance(first.test.left, ast.Name): return first.test.left.id return "" def _values(function: ast.FunctionDef, kind: str) -> Dict[str, str]: """One literal per parameter: the tested name carries ``kind``, the rest carry a placeholder. The placeholder says nothing about the domain; it only has to be a value the handler accepts without complaint. The round trip gate runs the call, so a target where a placeholder is not accepted is a target this catalog does not claim. """ subject = _chain_subject(function) return {argument.arg: (repr(kind) if argument.arg == subject else '""') for argument in function.args.args} def _call(function: ast.FunctionDef, values: Dict[str, str]) -> str: return ", ".join(values[argument.arg] for argument in function.args.args) def _call_for(function: ast.FunctionDef, names: Sequence[str], values: Dict[str, str]) -> str: return ", ".join(values[name] for name in names) # --------------------------------------------------------------------------- # Rule 4: a handle opened by hand gets a scope. # --------------------------------------------------------------------------- def _open_call(node: ast.AST) -> Optional[ast.Call]: if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "open" and node.args: return node return None def _closes_handle(statement: ast.stmt, handle: str) -> bool: return ( isinstance(statement, ast.Expr) and isinstance(statement.value, ast.Call) and isinstance(statement.value.func, ast.Attribute) and statement.value.func.attr == "close" and isinstance(statement.value.func.value, ast.Name) and statement.value.func.value.id == handle and not statement.value.args ) def rule_open_to_context_manager(target: Target) -> Outcome: """Give a hand opened file a ``with`` scope and drop the close it makes redundant. The handle may only be used by statements in the run of lines below the assignment. A handle that is returned, stored in another name, or used above the assignment escapes the scope this rule can build, and the rule says so instead of narrowing a lifetime quietly. """ function, miss = module_function(target) if function is None: return miss assert function is not None starts = line_starts(target.text) for node in ast.walk(function): if isinstance(node, ast.With): for item in node.items: if _open_call(item.context_expr) is not None: return _miss( target.rel_posix, target.symbol, ALREADY_SCOPED, "'%s' already opens its handle inside a with block" % target.symbol, ) position = None handle = "" opened: Optional[ast.Call] = None for index, statement in enumerate(function.body): if ( isinstance(statement, ast.Assign) and len(statement.targets) == 1 and isinstance(statement.targets[0], ast.Name) and _open_call(statement.value) is not None ): position = index handle = statement.targets[0].id opened = _open_call(statement.value) break if position is None or opened is None: return _miss(target.rel_posix, target.symbol, NO_BARE_OPEN, "'%s' opens no handle into a plain name" % target.symbol) def uses(node: ast.AST) -> bool: return any(isinstance(item, ast.Name) and item.id == handle for item in ast.walk(node)) if any(uses(statement) for statement in function.body[:position]): return _miss(target.rel_posix, target.symbol, HANDLE_ESCAPE, "'%s' is used before it is opened" % handle) block: List[ast.stmt] = [function.body[position]] for statement in function.body[position + 1:]: if not uses(statement): break block.append(statement) last_use = max(index for index, statement in enumerate(function.body) if uses(statement)) if last_use > position + len(block) - 1: return _miss(target.rel_posix, target.symbol, HANDLE_ESCAPE, "'%s' is used after the run this rule can scope" % handle) for statement in block[1:]: if isinstance(statement, ast.Return): return _miss(target.rel_posix, target.symbol, HANDLE_ESCAPE, "'%s' is used by a return, which outlives the scope" % handle) if isinstance(statement, ast.Assign) and any(isinstance(item, ast.Name) and item.id == handle for item in ast.walk(statement.value)): if isinstance(statement.value, ast.Name): return _miss(target.rel_posix, target.symbol, HANDLE_ESCAPE, "'%s' is stored in another name" % handle) elif not isinstance(statement, (ast.Assign, ast.Expr)): return _miss( target.rel_posix, target.symbol, HANDLE_ESCAPE, "a %s statement uses the handle in a way this rule cannot scope" % type(statement).__name__, ) drop = [statement for statement in block if _closes_handle(statement, handle)] kept = [statement for statement in block if statement is not block[0] and statement not in drop] indent = " " * block[0].col_offset pieces: List[str] = ["with %s as %s:" % (segment_of(target.text, starts, opened), handle)] previous_end = None for statement in kept: start, end = node_span(target.text, starts, statement) if previous_end is not None: pieces.append(_gap(target.text, previous_end, start)) pieces.append(_shifted(target.text, starts, statement, indent + INDENT)) previous_end = end block_text = "\n".join(pieces) function_start, function_end = node_span(target.text, starts, function) block_start, block_end = node_span(target.text, starts, block[0]) _unused, last_end = node_span(target.text, starts, block[-1]) edit = Edit( file=target.rel_posix, search=target.text[function_start:function_end], replace=apply_splices(target.text, function_start, function_end, [_Splice(start=block_start, end=last_end, text=block_text)]), label="scoped handle of '%s'" % target.symbol, ) alias = import_statement_for(target.rel_posix)[1] statements = [ "source = inspect.getsource(%s.%s)" % (alias, target.symbol), "assert 'with open(' in source", "assert '.close()' not in source", "assert '%s = open(' not in source" % handle, "directory = tempfile.mkdtemp()", "try:", ' path = os.path.join(directory, "lock note.txt")', ' with open(path, "w", encoding="utf-8") as writer:', ' writer.write("alpha")', " assert %s.%s(path) == 'alpha'" % (alias, target.symbol), "finally:", " shutil.rmtree(directory, ignore_errors=True)", ] test_name = "%s_scopes_its_handle" % target.symbol lock = lock_source( target.rel_posix, test_name, "Lock the scope the pattern gave the handle, the close it made redundant, and the read still working.", statements, headers=("import os", "import shutil", "import tempfile"), ) companion, companion_miss = _append_lock(target, test_file_for(target.rel_posix), test_name, lock) if companion is None: return _no_companion(target, companion_miss) evidence = ("the handle '%s' is opened outside any with block" % handle,) + tuple( "the close of '%s' becomes redundant inside the scope" % handle for _ in drop ) return _hit("open-to-context-manager", target, edit, companion, evidence) # --------------------------------------------------------------------------- # Rule 5: a precondition states its own failure. # --------------------------------------------------------------------------- def rule_bare_assert_to_explicit_raise(target: Target) -> Outcome: """Rewrite the first statement of a function from an assert into a raise. The exception type is kept, because an assert raises ``AssertionError`` and a caller that catches it has to keep catching it. Only the first statement is considered: a check further down is not a precondition, and moving it changes what the function does before it refuses. """ function, miss = module_function(target, allow_async=True) if function is None: return miss assert function is not None starts = line_starts(target.text) check = function.body[0] if not isinstance(check, ast.Assert): return _miss( target.rel_posix, target.symbol, NOT_THE_FIRST_STATEMENT, "the first statement of '%s' is not an assert, so it is not a precondition" % target.symbol, ) indent = " " * check.col_offset test_text = segment_of(target.text, starts, check.test) arguments = "" message_evidence = "no message was written, so the raise carries none either" if check.msg is not None: if not (isinstance(check.msg, ast.Constant) and isinstance(check.msg.value, str)): return _miss( target.rel_posix, target.symbol, NON_LITERAL_ASSERT_MESSAGE, "the message of the assert in '%s' is built at call time, so no lock test could name its text" % target.symbol, ) arguments = segment_of(target.text, starts, check.msg) message_evidence = "the message text is kept word for word" replacement = "if not %s:\n%sraise AssertionError(%s)" % (test_text, indent + INDENT, arguments) start, end = node_span(target.text, starts, check) edit = _rewrite_function(target, starts, function, [_Splice(start=start, end=end, text=replacement)], "explicit raise of '%s'" % target.symbol) alias = import_statement_for(target.rel_posix)[1] statements = [ "source = inspect.getsource(%s.%s)" % (alias, target.symbol), "assert 'raise AssertionError(' in source", "assert not [line for line in source.splitlines() if line.strip().startswith('assert ')]", "try:", ' %s' % _run_call(function, alias, target.symbol, '""'), "except AssertionError as caught:", " pass" if check.msg is None else " assert %s in str(caught)" % arguments, "else:", " raise AssertionError('%s accepted an argument its check rejects')" % target.symbol, ] test_name = "%s_raises_in_stead_of_asserting" % target.symbol lock = lock_source( target.rel_posix, test_name, "Lock the raise that replaced the assert, and the refusal the function still carries.", statements, headers=_lock_headers(function), ) companion, companion_miss = _append_lock(target, test_file_for(target.rel_posix), test_name, lock) if companion is None: return _no_companion(target, companion_miss) evidence = ("the first statement is an assert on '%s'" % test_text, message_evidence) return _hit("bare-assert-to-explicit-raise", target, edit, companion, evidence) # --------------------------------------------------------------------------- # Rule 6: a bare handler names the class it answers to. # --------------------------------------------------------------------------- def rule_bare_except_to_narrow_exception(target: Target) -> Outcome: """Name ``Exception`` in every bare ``except:`` header of the function. A handler that names no class also answers the exits the interpreter raises, so the one path that means to leave the program is answered with the fallback written for an ordinary failure. Naming the class keeps the fallback and lets the exits pass. """ function, miss = module_function(target) if function is None: return miss assert function is not None starts = line_starts(target.text) handlers = [ node for node in ast.walk(function) if isinstance(node, ast.ExceptHandler) and node.type is None ] if not handlers: return _miss( target.rel_posix, target.symbol, NO_BARE_EXCEPT, "no handler of '%s' leaves out the exception class" % target.symbol, ) splices: List[_Splice] = [] for handler in sorted(handlers, key=lambda node: node.lineno): if any(isinstance(node, ast.Raise) and node.exc is None for node in ast.walk(handler)): return _miss( target.rel_posix, target.symbol, BARE_EXCEPT_RE_RAISES, "a bare handler of '%s' re-raises what it caught, so naming the class would also " "change which exits the re-raise can still pass" % target.symbol, ) start = starts[handler.lineno - 1] + handler.col_offset if target.text[start : start + len("except:")] != "except:": return _miss( target.rel_posix, target.symbol, EXCEPT_HANDLER_UNREADABLE, "a bare handler of '%s' does not carry the header text 'except:' this rule anchors on" % target.symbol, ) splices.append(_Splice(start=start, end=start + len("except:"), text="except Exception:")) function_start, function_end = node_span(target.text, starts, function) rewritten = apply_splices(target.text, function_start, function_end, splices) if "except:" in rewritten: return _miss( target.rel_posix, target.symbol, EXCEPT_HANDLER_UNREADABLE, "the text of '%s' carries an 'except:' outside a handler header, so the lock test this " "rule writes could not tell the handler from the text around it" % target.symbol, ) edit = Edit( file=target.rel_posix, search=target.text[function_start:function_end], replace=rewritten, label="named handler of '%s'" % target.symbol, ) alias = import_statement_for(target.rel_posix)[1] statements = [ "source = inspect.getsource(%s.%s)" % (alias, target.symbol), "assert 'except Exception:' in source", "assert 'except:' not in source", ] test_name = "%s_answers_named_exceptions" % target.symbol lock = lock_source( target.rel_posix, test_name, "Lock the class every handler of this function now names.", statements, ) companion, companion_miss = _append_lock(target, test_file_for(target.rel_posix), test_name, lock) if companion is None: return _no_companion(target, companion_miss) evidence = tuple( "the handler on line %d catches every exception the interpreter can raise" % handler.lineno for handler in sorted(handlers, key=lambda node: node.lineno) ) return _hit("bare-except-to-narrow-exception", target, edit, companion, evidence) # --------------------------------------------------------------------------- # Rule 7: asking whether a value is None asks with identity. # --------------------------------------------------------------------------- def _is_none_literal(node: ast.expr) -> bool: return isinstance(node, ast.Constant) and node.value is None def _none_comparisons(function: ast.FunctionDef) -> Tuple[List[ast.Compare], bool]: """The single equality tests against ``None``, and whether a test against None is chained.""" claimed: List[ast.Compare] = [] chained = False for node in ast.walk(function): if not isinstance(node, ast.Compare): continue operands = [node.left] + list(node.comparators) if not any(isinstance(op, (ast.Eq, ast.NotEq)) for op in node.ops): continue if not any(_is_none_literal(operand) for operand in operands): continue if len(node.ops) != 1 or len(operands) != 2: chained = True continue claimed.append(node) return claimed, chained def rule_none_comparison_to_identity(target: Target) -> Outcome: """Replace an equality against ``None`` with ``is`` or ``is not``. None is one object, and an equality against it is a question most objects answer by their own agreement: a type with a custom equality turns a presence check into whatever that equality happens to say. Identity asks the question that was meant. """ function, miss = module_function(target, allow_async=True) if function is None: return miss assert function is not None starts = line_starts(target.text) comparisons, chained = _none_comparisons(function) if chained: return _miss( target.rel_posix, target.symbol, NONE_COMPARISON_IS_CHAINED, "a test against None in '%s' is part of a chained comparison, which one identity test " "cannot replace" % target.symbol, ) if not comparisons: return _miss( target.rel_posix, target.symbol, NO_NONE_COMPARISON, "no comparison of '%s' tests a value against None with equality" % target.symbol, ) splices: List[_Splice] = [] touched: List[Tuple[str, str]] = [] for node in comparisons: start, end = node_span(target.text, starts, node) operator = "is not" if isinstance(node.ops[0], ast.NotEq) else "is" left = node.left right = node.comparators[0] if _is_none_literal(right) and not _is_none_literal(left): operand = segment_of(target.text, starts, left) replacement = "%s %s None" % (operand, operator) else: operand = segment_of(target.text, starts, right) replacement = "None %s %s" % (operator, operand) splices.append(_Splice(start=start, end=end, text=replacement)) touched.append((operand, operator)) edit = _rewrite_function( target, starts, function, splices, "identity comparisons of '%s'" % target.symbol ) alias = import_statement_for(target.rel_posix)[1] statements = [ "source = inspect.getsource(%s.%s)" % (alias, target.symbol), "assert '== None' not in source", "assert '!= None' not in source", ] for operand, operator in touched: statements.append("assert %s in source" % repr("%s %s None" % (operand, operator))) test_name = "%s_compares_none_by_identity" % target.symbol lock = lock_source( target.rel_posix, test_name, "Lock the identity tests that replaced the equality against None.", statements, ) companion, companion_miss = _append_lock(target, test_file_for(target.rel_posix), test_name, lock) if companion is None: return _no_companion(target, companion_miss) evidence = tuple("the test against None reads '%s %s None'" % (operand, operator) for operand, operator in touched) return _hit("none-comparison-to-identity", target, edit, companion, evidence) # --------------------------------------------------------------------------- # Rule 8: an emptiness test stops counting the collection. # --------------------------------------------------------------------------- def _len_call(node: ast.expr) -> bool: return ( isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "len" and len(node.args) == 1 and not node.keywords ) def _is_plain_zero(node: ast.expr) -> bool: return ( isinstance(node, ast.Constant) and isinstance(node.value, int) and not isinstance(node.value, bool) and node.value == 0 ) def rule_empty_len_to_truthiness(target: Target) -> Outcome: """Ask whether a collection is empty by truthiness instead of counting it.""" function, miss = module_function(target, allow_async=True) if function is None: return miss assert function is not None starts = line_starts(target.text) checks: List[Tuple[ast.Compare, str]] = [] counted_but_not_a_name: List[ast.expr] = [] for node in ast.walk(function): if not isinstance(node, ast.Compare) or len(node.ops) != 1 or not isinstance(node.ops[0], ast.Eq): continue operands = [node.left] + list(node.comparators) if len(operands) != 2: continue if _is_plain_zero(operands[0]) and _len_call(operands[1]): counted = operands[1] elif _is_plain_zero(operands[1]) and _len_call(operands[0]): counted = operands[0] else: continue assert isinstance(counted, ast.Call) and counted.args argument = counted.args[0] if isinstance(argument, ast.Name): checks.append((node, argument.id)) else: counted_but_not_a_name.append(argument) if not checks and not counted_but_not_a_name: return _miss( target.rel_posix, target.symbol, NO_EMPTY_LEN_CHECK, "no comparison of '%s' counts a value with len only to ask whether it is empty" % target.symbol, ) if counted_but_not_a_name: return _miss( target.rel_posix, target.symbol, LEN_TARGET_IS_NOT_A_NAME, "'%s' counts '%s', which is not a plain name, and this rule only rewrites a count of a " "name it can ask about directly" % (target.symbol, segment_of(target.text, starts, counted_but_not_a_name[0])), ) splices: List[_Splice] = [] names: List[str] = [] for node, name in checks: start, end = node_span(target.text, starts, node) splices.append(_Splice(start=start, end=end, text="not %s" % name)) if name not in names: names.append(name) edit = _rewrite_function( target, starts, function, splices, "truthiness emptiness test of '%s'" % target.symbol ) alias = import_statement_for(target.rel_posix)[1] statements = ["source = inspect.getsource(%s.%s)" % (alias, target.symbol)] for name in names: statements.append("assert 'not %s' in source" % name) statements.append("assert 'len(%s) == 0' not in source" % name) test_name = "%s_asks_for_truthiness" % target.symbol lock = lock_source( target.rel_posix, test_name, "Lock the truthiness test that replaced the counted emptiness.", statements, ) companion, companion_miss = _append_lock(target, test_file_for(target.rel_posix), test_name, lock) if companion is None: return _no_companion(target, companion_miss) evidence = tuple("'%s' is counted only to ask whether it is empty" % name for name in names) return _hit("empty-len-to-truthiness", target, edit, companion, evidence) # --------------------------------------------------------------------------- # Rule 9: a constructor that replaced the chain should open it first. # --------------------------------------------------------------------------- def module_method(target: Target) -> Tuple[Optional[ast.FunctionDef], Optional[RuleMiss]]: """The module level class method a ``Class.method`` target names, or the refusal.""" class_name, separator, method_name = target.symbol.partition(".") if not separator or not method_name: return None, _miss( target.rel_posix, target.symbol, NOT_A_METHOD, "'%s' names no class and method split by a dot" % target.symbol, ) for node in target.tree.body: if isinstance(node, ast.ClassDef) and node.name == class_name: for item in node.body: if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)) and item.name == method_name: if isinstance(item, ast.AsyncFunctionDef): return None, _miss( target.rel_posix, target.symbol, ASYNC_TARGET, "'%s.%s' is a coroutine, and no lock test of this catalog waits for one" % (class_name, method_name), ) return item, None if method_name == "__init__": return None, _miss( target.rel_posix, target.symbol, NO_INIT_METHOD, "class '%s' defines no '__init__' of its own" % class_name, ) return None, _miss( target.rel_posix, target.symbol, NOT_A_METHOD, "class '%s' defines no method named '%s'" % (class_name, method_name), ) for node in ast.walk(target.tree): if isinstance(node, ast.ClassDef) and node.name == class_name: return None, _miss( target.rel_posix, target.symbol, NOT_A_MODULE_CLASS, "class '%s' is not defined at module level in '%s'" % (class_name, target.rel_posix), ) return None, _miss( target.rel_posix, target.symbol, NO_SUCH_CLASS, "no class named '%s' in '%s'" % (class_name, target.rel_posix), ) def _opens_super(statement: ast.stmt) -> bool: """True for a bare ``super().__init__(...)`` statement.""" return ( isinstance(statement, ast.Expr) and isinstance(statement.value, ast.Call) and isinstance(statement.value.func, ast.Attribute) and statement.value.func.attr == "__init__" and isinstance(statement.value.func.value, ast.Call) and isinstance(statement.value.func.value.func, ast.Name) and statement.value.func.value.func.id == "super" ) def rule_init_missing_super(target: Target) -> Outcome: """Open the constructor chain of a module level class that replaced it. The rule claims the narrowest shape it can state honestly: a class naming no base of its own, whose ``__init__`` takes only ``self``. A named base is a constructor with arguments this rule cannot forward, and calling super without them would change what the class builds, which a cleanup pattern may not do. """ method, miss = module_method(target) if method is None: return miss assert method is not None if method.name != "__init__": return _miss( target.rel_posix, target.symbol, NOT_A_METHOD, "this card writes a constructor, and '%s' names no '__init__'" % target.symbol, ) starts = line_starts(target.text) class_name = target.symbol.partition(".")[0] class_node: Optional[ast.ClassDef] = None for node in target.tree.body: if isinstance(node, ast.ClassDef) and node.name == class_name: class_node = node break assert class_node is not None if class_node.bases or class_node.keywords: return _miss( target.rel_posix, target.symbol, SUPER_BASES_UNREADABLE, "class '%s' names base classes, and this rule cannot say which constructor super reaches " "or what arguments it takes" % class_name, ) if ( [argument.arg for argument in method.args.posonlyargs + method.args.args] != ["self"] or method.args.kwonlyargs or method.args.vararg or method.args.kwarg ): return _miss( target.rel_posix, target.symbol, INIT_TAKES_MORE_THAN_SELF, "'%s' takes arguments this rule cannot forward, and calling super without them " "would change what the class builds" % target.symbol, ) real = [statement for statement in method.body if not _is_string_statement(statement)] if real and _opens_super(real[0]): return _miss( target.rel_posix, target.symbol, SUPER_CALL_ALREADY_FIRST, "class '%s' already opens its constructor chain first" % class_name, ) has_docstring = bool(method.body and _is_string_statement(method.body[0])) if real: body_start = starts[real[0].lineno - 1] + real[0].col_offset indent = " " * real[0].col_offset else: docstring = method.body[0] body_start = starts[docstring.end_lineno - 1] + docstring.end_col_offset + 1 indent = " " * docstring.col_offset splices = [_Splice(start=body_start, end=body_start, text="super().__init__()\n%s" % indent)] edit = _rewrite_function(target, starts, method, splices, "constructor chain of '%s' opened" % target.symbol) alias = import_statement_for(target.rel_posix)[1] statements = [ "source = inspect.getsource(%s.%s)" % (alias, target.symbol), "assert 'super().__init__()' in source", "lines = [line.strip() for line in source.splitlines() if line.strip()]", "assert lines[0].startswith('def __init__')", "assert lines[%d] == 'super().__init__()'" % (2 if has_docstring else 1), "created = %s.%s()" % (alias, class_name), "assert isinstance(created, %s.%s)" % (alias, class_name), ] test_name = "%s_init_calls_super_first" % class_name lock = lock_source( target.rel_posix, test_name, "Lock the super call this rule put first in the constructor, and the class that still builds.", statements, ) companion, companion_miss = _append_lock(target, test_file_for(target.rel_posix), test_name, lock) if companion is None: return _no_companion(target, companion_miss) evidence = ("'%s.__init__' builds its object without opening the constructor chain first" % class_name,) return _hit("init-missing-super", target, edit, companion, evidence) # --------------------------------------------------------------------------- # Rule 10: an import that binds nothing is a promise to a module nobody calls. # --------------------------------------------------------------------------- def rule_drop_unused_imports(target: Target) -> Outcome: """Remove top level imports that bind a name no other line of the file reads. A name that appears nowhere else in the text is decidable from the file alone, and that is exactly the limit of the rule: ``__all__``, a star import, and a package ``__init__.py`` all let one line of a file mean more than the names it spells, and the rule refuses them rather than guess what a reader of the package expects. """ function, miss = module_function(target, allow_async=True) if function is None: return miss assert function is not None starts = line_starts(target.text) if target.rel_posix == "__init__.py" or target.rel_posix.endswith("/__init__.py"): return _miss( target.rel_posix, target.symbol, PACKAGE_FILE_TARGET, "'%s' is a package interface, where an import line can be the name the package publishes" % target.rel_posix, ) import_nodes = [node for node in target.tree.body if isinstance(node, (ast.Import, ast.ImportFrom))] if not import_nodes: return _miss( target.rel_posix, target.symbol, NO_UNUSED_IMPORT, "'%s' imports nothing at top level, so nothing there can go unread" % target.rel_posix, ) if any( isinstance(node, ast.ImportFrom) and any(alias.name == "*" for alias in node.names) for node in import_nodes ): return _miss( target.rel_posix, target.symbol, STAR_IMPORT_IN_FILE, "'%s' takes names through a star import, so the file can read names its text never writes" % target.rel_posix, ) for node in target.tree.body: if isinstance(node, (ast.Assign, ast.AnnAssign)): for assignment in getattr(node, "targets", [node.target]): if isinstance(assignment, ast.Name) and assignment.id == "__all__": return _miss( target.rel_posix, target.symbol, NAME_LISTED_IN_ALL, "'%s' publishes an __all__, and a name the text never reads can still carry that promise" % target.rel_posix, ) covered = set() for node in import_nodes: covered.update(range(node.lineno, node.end_lineno + 1)) other_text = "\n".join( line for index, line in enumerate(target.text.split("\n"), start=1) if index not in covered ) unused_nodes: List[ast.stmt] = [] unused_names: List[str] = [] for node in import_nodes: names = [ alias.asname or (alias.name.split(".")[0] if isinstance(node, ast.Import) else alias.name) for alias in node.names ] if all(re.search(r"\b%s\b" % re.escape(name), other_text) is None for name in names): unused_nodes.append(node) unused_names.extend(names) if not unused_nodes: return _miss( target.rel_posix, target.symbol, NO_UNUSED_IMPORT, "every top level import of '%s' binds a name another line of the file reads" % target.rel_posix, ) unused_nodes.sort(key=lambda node: node.lineno) for previous, following in zip(unused_nodes, unused_nodes[1:]): if following.lineno != previous.end_lineno + 1: return _miss( target.rel_posix, target.symbol, IMPORTS_NOT_CONTIGUOUS, "the unread imports of '%s' are not on consecutive lines, so one anchor cannot remove them together" % target.rel_posix, ) block_start = starts[unused_nodes[0].lineno - 1] last_node = unused_nodes[-1] block_end = starts[last_node.end_lineno - 1] + last_node.end_col_offset + 1 block = target.text[block_start:block_end] if target.text.count(block) != 1: return _miss( target.rel_posix, target.symbol, ANCHOR_OVERLAP, "the import block this rule would remove appears more than once in '%s'" % target.rel_posix, ) edit = Edit( file=target.rel_posix, search=block, replace="", label="unread imports of '%s' removed" % target.rel_posix, ) alias = import_statement_for(target.rel_posix)[1] statements = [ "source = inspect.getsource(%s)" % alias, "import_lines = [line.strip() for line in source.splitlines() if line.strip().startswith(('import ', 'from '))]", ] for name in sorted(set(unused_names)): statements.append("assert not [line for line in import_lines if %r in line.split()]" % name) statements.append("assert callable(%s.%s)" % (alias, function.name)) test_name = "%s_keeps_no_unread_imports" % function.name lock = lock_source( target.rel_posix, test_name, "Lock the import lines this rule removed from the module and the function they never reached.", statements, ) companion, companion_miss = _append_lock(target, test_file_for(target.rel_posix), test_name, lock) if companion is None: return _no_companion(target, companion_miss) evidence = tuple( "the import of '%s' binds a name no other line of '%s' reads" % (name, target.rel_posix) for name in sorted(set(unused_names)) ) return _hit("drop-unused-imports", target, edit, companion, evidence) RULES: Dict[str, Callable[[Target], Outcome]] = { "annotate-literal-defaults": rule_annotate_literal_defaults, "mutable-default-to-none": rule_mutable_default_to_none, "chain-to-registry": rule_chain_to_registry, "open-to-context-manager": rule_open_to_context_manager, "bare-assert-to-explicit-raise": rule_bare_assert_to_explicit_raise, "bare-except-to-narrow-exception": rule_bare_except_to_narrow_exception, "none-comparison-to-identity": rule_none_comparison_to_identity, "empty-len-to-truthiness": rule_empty_len_to_truthiness, "init-missing-super": rule_init_missing_super, "drop-unused-imports": rule_drop_unused_imports, } RULE_IDS: Tuple[str, ...] = tuple(sorted(RULES))
"""Structural rules: where a pattern applies in a real file, and what text it writes.
A pattern in this bundle is not a snippet to paste. It is a predicate over the syntax
tree plus a text transform that has to survive the kernel patcher, so this module does
two things and nothing else: it decides whether a named function is in the shape a
pattern claims to improve, and it builds the exact search and replace pair for it. When
the shape is not there it says why with a code, and that code is what a negative row of
``patterns/pattern_cases.jsonl`` claims, which is what the ``pattern_round_trip`` gate
re-checks by running the rule again.
Four boundaries are stated rather than assumed.
* Offsets. A syntax tree column is a byte offset. Anchors here are built from those
offsets, so a target file that is not ASCII is refused instead of patched at the wrong
place, and a file indented with a tab is refused instead of getting spaces mixed into
one block.
* Endings. The catalog anchors on LF text, so a CRLF target is refused with
``CRLF_TARGET``. A hand written edit through the kernel patcher still preserves the
endings of a CRLF file; that guarantee is the kernel's and is untouched here.
* Shape. A rule refuses the shapes it has not read: a handle that is stored or returned,
a chain that falls through instead of raising, a check that is not the first statement.
Refusing is a result, not an error, and a refusal writes nothing.
* Evidence. A rule never runs the code it reads. The lock test it appends to a test file
is for the test gate of a run to execute, and it is written so that it fails when the
primary edit did not land. That coupling is the whole reason a companion exists.
"""
from __future__ import annotations
import ast
import keyword
import re
from dataclasses import dataclass
from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union
# Refusal codes. A negative row names one of these and the gate re-runs the rule to check
# that the rule still answers with exactly that code for exactly that target.
MISSING_TARGET_FILE = "MISSING_TARGET_FILE"
NO_SUCH_FUNCTION = "NO_SUCH_FUNCTION"
NOT_A_MODULE_FUNCTION = "NOT_A_MODULE_FUNCTION"
NOT_PARSEABLE = "NOT_PARSEABLE"
NOT_ASCII_TARGET = "NOT_ASCII_TARGET"
TAB_INDENTED_TARGET = "TAB_INDENTED_TARGET"
CRLF_TARGET = "CRLF_TARGET"
NO_TEST_FILE = "NO_TEST_FILE"
NO_TEST_ANCHOR = "NO_TEST_ANCHOR"
AMBIGUOUS_TEST_ANCHOR = "AMBIGUOUS_TEST_ANCHOR"
ALREADY_ANNOTATED = "ALREADY_ANNOTATED"
NOT_A_MUTABLE_DEFAULT = "NOT_A_MUTABLE_DEFAULT"
ANNOTATED_MUTABLE_DEFAULT = "ANNOTATED_MUTABLE_DEFAULT"
GUARD_ALREADY_PRESENT = "GUARD_ALREADY_PRESENT"
NO_DISPATCH_CHAIN = "NO_DISPATCH_CHAIN"
BRANCH_SHAPE_MISMATCH = "BRANCH_SHAPE_MISMATCH"
ALREADY_SCOPED = "ALREADY_SCOPED"
NO_BARE_OPEN = "NO_BARE_OPEN"
HANDLE_ESCAPE = "HANDLE_ESCAPE"
NOT_THE_FIRST_STATEMENT = "NOT_THE_FIRST_STATEMENT"
ASYNC_TARGET = "ASYNC_TARGET"
NON_LITERAL_ASSERT_MESSAGE = "NON_LITERAL_ASSERT_MESSAGE"
INVALID_COMPANION_PATH = "INVALID_COMPANION_PATH"
ANCHOR_OVERLAP = "ANCHOR_OVERLAP"
NO_BARE_EXCEPT = "NO_BARE_EXCEPT"
BARE_EXCEPT_RE_RAISES = "BARE_EXCEPT_RE_RAISES"
EXCEPT_HANDLER_UNREADABLE = "EXCEPT_HANDLER_UNREADABLE"
NO_NONE_COMPARISON = "NO_NONE_COMPARISON"
NONE_COMPARISON_IS_CHAINED = "NONE_COMPARISON_IS_CHAINED"
NO_EMPTY_LEN_CHECK = "NO_EMPTY_LEN_CHECK"
LEN_TARGET_IS_NOT_A_NAME = "LEN_TARGET_IS_NOT_A_NAME"
NO_SUCH_CLASS = "NO_SUCH_CLASS"
NOT_A_MODULE_CLASS = "NOT_A_MODULE_CLASS"
NOT_A_METHOD = "NOT_A_METHOD"
NO_INIT_METHOD = "NO_INIT_METHOD"
INIT_TAKES_MORE_THAN_SELF = "INIT_TAKES_MORE_THAN_SELF"
SUPER_CALL_ALREADY_FIRST = "SUPER_CALL_ALREADY_FIRST"
SUPER_BASES_UNREADABLE = "SUPER_BASES_UNREADABLE"
NO_UNUSED_IMPORT = "NO_UNUSED_IMPORT"
STAR_IMPORT_IN_FILE = "STAR_IMPORT_IN_FILE"
NAME_LISTED_IN_ALL = "NAME_LISTED_IN_ALL"
PACKAGE_FILE_TARGET = "PACKAGE_FILE_TARGET"
IMPORTS_NOT_CONTIGUOUS = "IMPORTS_NOT_CONTIGUOUS"
INDENT = " "
_MUTABLE_LITERALS = (ast.List, ast.Dict, ast.Set)
_MUTABLE_CALLS = ("list", "dict", "set")
@dataclass(frozen=True)
class Target:
"""One function a caller wants a pattern looked at, read from a workspace."""
rel_posix: str
symbol: str
text: str
tree: ast.Module
read: Callable[[str], Optional[str]]
@dataclass(frozen=True)
class Edit:
"""One file the pattern would write, as a search and replace pair."""