"""The catalog: which patterns this bundle teaches, and exactly what each one claims. A card here is not a snippet to paste. Every card names a rule in ``lingologos_python.rules`` that decides whether the shape is really present in a given function and writes the text for it, plus the lock test that rule appends to the matching test file. The card is what a person reads before applying anything; the rule is what runs; ``patterns/`` holds the rows that prove the card and the rule still say the same thing. Three limits are written into the cards rather than assumed: * A card claims one shape. It says what has to be true for the pattern to apply, and the reason codes the rule answers with when it is not, so a refusal is a result with a name and not a stack trace. * A card claims a companion, not a wish. The lock test is part of the pattern because a rewrite nobody checks is a claim nobody verified, and the lock is written so that it fails when the primary edit did not land. * A card claims a minimum assurance. Applying a pattern is a commit, and the commit needs the number of independent provers the card asks for. """ from __future__ import annotations import ast from dataclasses import dataclass from pathlib import Path from typing import Callable, Dict, List, Optional, Sequence, Tuple from lingologos_python import rules from lingologos_python.ast_graph import discover_python_files from lingologos_python.reasons import AMBIGUOUS_TARGET # the refusal when a scan fits more than one target # Target syntax: a workspace-relative path, then the module level function, split by "::". TARGET_SEPARATOR = "::" FAMILIES: Tuple[str, ...] = ("contracts", "mutation", "resources", "shape", "typing") # Refusals every card can answer with before its rule looks at the shape at all: the # target or its paired test file is simply not in a shape this catalog anchors on. SHARED_REFUSALS: Tuple[str, ...] = ( rules.MISSING_TARGET_FILE, rules.NO_SUCH_FUNCTION, rules.NOT_PARSEABLE, rules.NOT_ASCII_TARGET, rules.TAB_INDENTED_TARGET, rules.CRLF_TARGET, rules.NO_TEST_FILE, rules.NO_TEST_ANCHOR, rules.AMBIGUOUS_TEST_ANCHOR, rules.INVALID_COMPANION_PATH, rules.ANCHOR_OVERLAP, ) @dataclass(frozen=True) class PatternSpec: """One card: the shape, the rule that recognises it, and what applying it claims.""" pattern_id: str family: str intent_tags: Tuple[str, ...] rule: str shape: str rationale: str preconditions: Tuple[str, ...] companions: Tuple[str, ...] lock_claims: str refuses_as: Tuple[str, ...] min_assurance: int = 3 def target_of(self, rel_posix: str, symbol: str) -> str: return "%s%s%s" % (rel_posix.replace("\\", "/"), TARGET_SEPARATOR, symbol) def to_row(self, case_id: str, target: str, edits: Sequence[rules.Edit], expect: str, reason_code: str = "") -> Dict[str, object]: """The corpus row for one run of this card against one target.""" row: Dict[str, object] = { "case_id": case_id, "language": "python", "family": self.family, "intent_tags": list(self.intent_tags), "edits": [ {"file": edit.file, "search": edit.search, "replace": edit.replace, "label": edit.label} for edit in edits ], "expect": expect, "note": self.shape, "pattern_id": self.pattern_id, "rule": self.rule, "targets": [target], "min_assurance": self.min_assurance, } if reason_code: row["reason_code"] = reason_code return row def _card( pattern_id: str, family: str, intent_tags: Sequence[str], shape: str, rationale: str, preconditions: Sequence[str], companions: Sequence[str], lock_claims: str, refuses_as: Sequence[str], ) -> PatternSpec: merged: List[str] = [] for code in tuple(refuses_as) + SHARED_REFUSALS: if code not in merged: merged.append(code) return PatternSpec( pattern_id=pattern_id, family=family, intent_tags=tuple(intent_tags), rule=pattern_id, shape=shape, rationale=rationale, preconditions=tuple(preconditions), companions=tuple(companions), lock_claims=lock_claims, refuses_as=tuple(merged), ) # Every card writes its companion in the same place: the test file this layout pairs with # the source file by name. Which function goes there differs per card, and that is what # the lock claim states. LOCK_COMPANION = ( "one test function appended to the test file paired by name, tests/test_.py, " "in the same run as the source change" ) PATTERNS: Dict[str, PatternSpec] = { spec.pattern_id: spec for spec in ( _card( "annotate-literal-defaults", "typing", ("annotate", "defaults", "types"), "a module level function whose parameter has a literal default and no annotation", "the default already states the type, and a caller reading the signature has to guess it. " "Writing it down is what lets a type checker see the boundary of the module.", ( "the function is defined at module level, not nested", "the parameter is not annotated already", "the default is a str, int, float or bool literal, so the type is readable from it", "the file is ASCII text with LF endings and spaces for indentation", "a coroutine target is claimed too: the lock reads the signature, which needs no call and waits for nothing", ), (LOCK_COMPANION,), "the signature of the function carries the annotation the pattern added and the default it started with", (rules.ALREADY_ANNOTATED, rules.NOT_A_MODULE_FUNCTION, rules.NOT_ASCII_TARGET, rules.CRLF_TARGET), ), _card( "mutable-default-to-none", "mutation", ("defaults", "aliasing", "mutation"), "a module level function whose parameter defaults to a list, dict or set built at definition time", "one default object is created once and handed to every call that omits the argument, so a call " "that mutates it changes what the next caller sees. The rewrite makes the absence explicit.", ( "the function is defined at module level, not nested", "the default is an empty list, dict or set literal, or a bare list(), dict() or set() call", "that parameter carries no annotation, because widening an annotation is a second change", "the guard is not already the first line of the body", "the file is ASCII text with LF endings and spaces for indentation", "a coroutine target is claimed too, and the lock waits for its two calls with asyncio.run", ), (LOCK_COMPANION,), "the default is None, the guard is in the source, and two calls that omit the argument answer differently", ( rules.NOT_A_MUTABLE_DEFAULT, rules.ANNOTATED_MUTABLE_DEFAULT, rules.GUARD_ALREADY_PRESENT, rules.NOT_A_MODULE_FUNCTION, ), ), _card( "chain-to-registry", "shape", ("dispatch", "registry", "extension"), "a module level function that dispatches an if/elif chain of one name compared to text literals", "adding a kind means editing the middle of a chain, and a missing branch silently falls through. " "A mapping of kind to handler makes the set of kinds one visible object and the refusal one place.", ( "every branch tests the same parameter against a text literal and returns one call", "each branch is a call of a name defined in the same module, taking plain parameters", "the last branch raises, so an unknown kind is refused rather than answered with None", "the function takes plain positional parameters only", "a coroutine target is refused with ASYNC_TARGET: the rewrite moves the calls of the chain, " "and this card carries no coroutine pair that would say whether they await", ), (LOCK_COMPANION,), "the source holds the mapping and no elif, each kind still answers as the chain answered, and an " "unknown kind is still refused", (rules.NO_DISPATCH_CHAIN, rules.BRANCH_SHAPE_MISMATCH, rules.NOT_A_MODULE_FUNCTION, rules.ASYNC_TARGET), ), _card( "open-to-context-manager", "resources", ("files", "lifetime", "resources"), "a module level function that opens a file into a name and closes that name itself", "a close that is not tied to the scope is skipped by the one path that raises on the way out, and " "the reader has to trace every exit to believe the handle is closed.", ( "the assignment is open(...) directly, with no wrapper between the call and the name", "the name is closed by an expression statement whose target is that name", "the name is used only inside that function and never stored or returned", "the function does not already open the handle inside a with block", "a coroutine target is refused with ASYNC_TARGET: this card carries no coroutine pair " "that would prove its lock test waits for one", ), (LOCK_COMPANION,), "the source opens inside a with block and never calls close, and a file written in a temporary " "directory is read back through the rewritten function", (rules.ALREADY_SCOPED, rules.NO_BARE_OPEN, rules.HANDLE_ESCAPE, rules.NOT_A_MODULE_FUNCTION, rules.ASYNC_TARGET), ), _card( "bare-assert-to-explicit-raise", "contracts", ("preconditions", "errors", "contracts"), "a module level function whose first statement is an assert guarding its arguments", "an assert is a development check that a normal run may switch off, so a precondition written with " "it is a contract that stops holding when someone passes -O. The rewrite keeps the same exception.", ( "the assert is the first statement of the function, so it is a precondition and not a check in the middle", "the message text, when there is one, is kept word for word", "the function still raises AssertionError, so a caller that catches it keeps catching it", "a coroutine target is claimed too, and the lock waits for its one call with asyncio.run", ), (LOCK_COMPANION,), "the source carries the raise and no assert line, and the call still refuses the argument the check " "refused, with the message it carried", (rules.NOT_THE_FIRST_STATEMENT, rules.NOT_A_MODULE_FUNCTION, rules.CRLF_TARGET), ), _card( "bare-except-to-narrow-exception", "contracts", ("errors", "exceptions", "contracts"), "a module level function with an except handler that names no exception class", "a bare handler also answers the exits the interpreter raises, so the one path that means to " "leave the program is answered with the fallback the handler was written for. Naming the " "class keeps the fallback and lets the exits pass.", ( "the handler carries the bare header text the rule anchors on, 'except:'", "the handler body does not end by re-raising what it caught, which is a second change", "the function text holds no other 'except:' the lock could confuse with a header", "a coroutine target is refused with ASYNC_TARGET: the lock reads the text, but the corpus " "carries no coroutine pair for this card to vouch for the read", ), (LOCK_COMPANION,), "the source names Exception in every handler that was bare and carries no bare header left; " "the lock reads the function back with inspect, so it answers about the text, not about a call", ( rules.NO_BARE_EXCEPT, rules.BARE_EXCEPT_RE_RAISES, rules.EXCEPT_HANDLER_UNREADABLE, rules.NOT_A_MODULE_FUNCTION, rules.ASYNC_TARGET, ), ), _card( "none-comparison-to-identity", "shape", ("equality", "identity", "none"), "a module level function that asks whether a value is None with == or !=", "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.", ( "the comparison is a single equality test against None, not a chained comparison", "None is written as the plain literal on one side of the test", "the file is ASCII text with LF endings and spaces for indentation", "a coroutine target is claimed too: the lock reads the text and waits for nothing", ), (LOCK_COMPANION,), "every test the pattern touched reads with is or is not, and the source carries no == None or " "!= None left; the lock reads the function back with inspect, so it answers about the text", (rules.NO_NONE_COMPARISON, rules.NONE_COMPARISON_IS_CHAINED, rules.NOT_A_MODULE_FUNCTION), ), _card( "empty-len-to-truthiness", "shape", ("collections", "truthiness", "emptiness"), "a module level function that counts a value with len and compares the count to zero", "counting a collection only to ask whether it is empty does work the answer does not need, and " "it stops working for collections that answer emptiness without giving a length. The rewrite " "asks the question directly.", ( "the value counted is a plain name, so the rewrite evaluates it no more than before", "the comparison is a single test against the number 0, not against False or a chain", "the file is ASCII text with LF endings and spaces for indentation", "a coroutine target is claimed too: the lock reads the text and waits for nothing", ), (LOCK_COMPANION,), "each check the pattern touched became a truthiness test, and its counted comparison is gone " "from the source; the lock reads the function back with inspect, so it answers about the text", (rules.NO_EMPTY_LEN_CHECK, rules.LEN_TARGET_IS_NOT_A_NAME, rules.NOT_A_MODULE_FUNCTION), ), _card( "init-missing-super", "contracts", ("construction", "inheritance", "super"), "a module level class whose '__init__' takes only self, names no base of its own, and " "does not open the constructor chain first", "a constructor that builds without calling super leaves the parts a base would have " "initialized missing, and the class only looks finished until one of those parts is " "asked for. Opening the chain first puts the base back in the path it was written to be in.", ( "the class is defined at module level and names no base or keyword argument, so super is the object itself", "the '__init__' takes self alone, so the rule has nothing to forward and changes no arguments", "the call goes after the docstring and before the first statement that builds", "a file named '__init__.py' is refused: there a line means the package, not a class", ), (LOCK_COMPANION,), "the first executable line of the constructor is 'super().__init__()', and the class " "still builds the object its tests ask for", ( rules.NO_SUCH_CLASS, rules.NOT_A_MODULE_CLASS, rules.NOT_A_METHOD, rules.NO_INIT_METHOD, rules.INIT_TAKES_MORE_THAN_SELF, rules.SUPER_CALL_ALREADY_FIRST, rules.SUPER_BASES_UNREADABLE, rules.PACKAGE_FILE_TARGET, rules.ASYNC_TARGET, ), ), _card( "drop-unused-imports", "shape", ("imports", "cleanup", "dead code"), "a module level function in a file whose top level import lines bind names that no other " "line of the file reads", "an import that binds nothing is a promise to a module nobody calls: it costs the reader a " "line to learn nothing, and it keeps a dependency alive that the file does not use. The " "rewrite removes exactly the lines the text itself shows unread.", ( "the claim reaches only top level import statements, whose effect on the file is readable from the file", "a name counts as read when another line of the file spells it, outside the import lines themselves", "the unread lines sit on consecutive lines, so one anchor removes them together", "a file with an __all__ or a star import is refused, because there a name can be carried without being spelled", "a file named '__init__.py' is refused, because there an import line can be the interface of a package", ), (LOCK_COMPANION,), "the removed import lines are gone from the module and the function that never read them " "is still callable; the lock reads the module back with inspect, so it answers about the text", ( rules.NO_UNUSED_IMPORT, rules.STAR_IMPORT_IN_FILE, rules.NAME_LISTED_IN_ALL, rules.PACKAGE_FILE_TARGET, rules.IMPORTS_NOT_CONTIGUOUS, rules.NOT_A_MODULE_FUNCTION, ), ), ) } PATTERN_IDS: Tuple[str, ...] = tuple(sorted(PATTERNS)) def pattern_card(pattern_id: str) -> PatternSpec: spec = PATTERNS.get(pattern_id) if spec is None: raise KeyError("unknown pattern: '%s'" % pattern_id) return spec def split_target(target: str) -> Tuple[str, str]: """Split ``path::function`` into a workspace-relative path and a function name.""" if TARGET_SEPARATOR not in target: raise ValueError("target must be written as 'path/to/file.py::function': '%s'" % target) rel_posix, symbol = target.split(TARGET_SEPARATOR, 1) rel_posix = rel_posix.replace("\\", "/").strip() symbol = symbol.strip() if not rel_posix or not symbol: raise ValueError("target must name both a file and a function: '%s'" % target) return rel_posix, symbol @dataclass(frozen=True) class PatternPlan: """What applying a card to one target would write, or why it refuses to.""" pattern_id: str target: str edits: Tuple[rules.Edit, ...] evidence: Tuple[str, ...] min_assurance: int refused: bool = False reason_code: str = "" detail: str = "" @property def files(self) -> Tuple[str, ...]: return tuple(edit.file for edit in self.edits) def primary(self) -> rules.Edit: if not self.edits: raise ValueError("a refused plan writes nothing") return self.edits[0] def companions(self) -> Tuple[rules.Edit, ...]: return self.edits[1:] def to_row(self, case_id: str) -> Dict[str, object]: spec = pattern_card(self.pattern_id) expect = "REFUSED" if self.refused else "VERIFIED" return spec.to_row( case_id, self.target, () if self.refused else self.edits, expect, self.reason_code if self.refused else "", ) def summary(self) -> str: if self.refused: return "%s refuses %s: %s (%s)" % (self.pattern_id, self.target, self.detail, self.reason_code) return "%s applies to %s and writes %s" % (self.pattern_id, self.target, ", ".join(self.files)) def _workspace_reader(root: Path) -> Callable[[str], Optional[str]]: def read(rel_posix: str) -> Optional[str]: path = root / Path(*rel_posix.split("/")) if not path.is_file(): return None return path.read_text(encoding="utf-8", newline="") return read def module_level_functions(text: str) -> Tuple[str, ...]: """Names defined at module level, the only functions a card in this catalog claims.""" try: tree = ast.parse(text) except SyntaxError: return () return tuple(node.name for node in tree.body if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))) def scan_pattern(root: str | Path, pattern_id: str, *, files: Optional[Sequence[str]] = None) -> List[Tuple[str, rules.RuleHit]]: """Every target under one root a card applies to, as ``path::function`` labels.""" spec = pattern_card(pattern_id) rule = rules.RULES[spec.rule] workspace = Path(root).resolve() reader = _workspace_reader(workspace) found: List[Tuple[str, rules.RuleHit]] = [] for rel in sorted(files if files is not None else discover_python_files(workspace)): text = reader(rel) if text is None: continue try: tree = ast.parse(text) except SyntaxError: continue symbols = [node.name for node in tree.body if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))] for node in tree.body: if isinstance(node, ast.ClassDef): for item in node.body: if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)): symbols.append("%s.%s" % (node.name, item.name)) for symbol in symbols: target, miss = rules.open_target_with_tree(rel, symbol, text, tree, reader) if target is None: continue outcome = rule(target) if isinstance(outcome, rules.RuleHit): found.append((rules.target_label(rel, symbol), outcome)) return found def plan_pattern(root: str | Path, pattern_id: str, target: Optional[str] = None) -> PatternPlan: """Decide what a card would write in a real workspace, or why it refuses. Without an explicit target the catalog scans the workspace, and more than one match is a refusal: the caller has to choose, because applying a pattern everywhere it happens to fit is not what a card claims. """ spec = pattern_card(pattern_id) rule = rules.RULES[spec.rule] workspace = Path(root).resolve() reader = _workspace_reader(workspace) if target is None: found = scan_pattern(workspace, pattern_id) if not found: return PatternPlan( pattern_id=pattern_id, target="", edits=(), evidence=(), min_assurance=spec.min_assurance, refused=True, reason_code=rules.NO_SUCH_FUNCTION, detail="no module level function under '%s' is in the shape this card claims" % workspace, ) if len(found) > 1: return PatternPlan( pattern_id=pattern_id, target="", edits=(), evidence=(), min_assurance=spec.min_assurance, refused=True, reason_code=AMBIGUOUS_TARGET, detail="this card fits %d targets, name one: %s" % (len(found), ", ".join(label for label, _hit in found)), ) target = found[0][0] rel_posix, symbol = split_target(target) opened, miss = rules.open_target(rel_posix, symbol, reader) if opened is None and miss is not None: return PatternPlan( pattern_id=pattern_id, target=rules.target_label(rel_posix, symbol), edits=(), evidence=(), min_assurance=spec.min_assurance, refused=True, reason_code=miss.reason_code, detail=miss.detail, ) assert opened is not None try: outcome = rule(opened) except ValueError as exc: # A rule builds text anchors; if two of them collide the rule cannot say which # one to trust, and the plan reports that as a named refusal, not a traceback. return PatternPlan( pattern_id=pattern_id, target=rules.target_label(rel_posix, symbol), edits=(), evidence=(), min_assurance=spec.min_assurance, refused=True, reason_code=rules.ANCHOR_OVERLAP, detail="the anchors this rule builds collide: %s" % exc, ) if isinstance(outcome, rules.RuleMiss): return PatternPlan( pattern_id=pattern_id, target=outcome.target, edits=(), evidence=(), min_assurance=spec.min_assurance, refused=True, reason_code=outcome.reason_code, detail=outcome.detail, ) return PatternPlan( pattern_id=pattern_id, target=outcome.target, edits=outcome.edits, evidence=outcome.evidence, min_assurance=spec.min_assurance, ) def render_card(spec: PatternSpec) -> str: """The card as a person reads it in a terminal.""" lines = [ spec.pattern_id, " family %s" % spec.family, " intent %s" % ", ".join(spec.intent_tags), " shape %s" % spec.shape, " why %s" % spec.rationale, " needs", ] lines += [" - %s" % item for item in spec.preconditions] lines.append(" companion") lines += [" - %s" % item for item in spec.companions] lines.append(" lock %s" % spec.lock_claims) lines.append(" refuses %s" % ", ".join(spec.refuses_as)) lines.append(" needs assurance >= %d to commit" % spec.min_assurance) return "\n".join(lines)