Download lingologos_python/rules.py from tailot/codex-python: direct link, hf CLI and curl.
- Browser
- Download file 43.3 kB
-
https://huggingface.co/datasets/tailot/codex-python/resolve/62eac4a1ea04f1b5d5aed88a1992a781a462174f/lingologos_python/rules.py
- Command line
-
hf download hf://datasets/tailot/codex-python@62eac4a1ea04f1b5d5aed88a1992a781a462174f/lingologos_python/rules.py
-
curl -L -o rules.py https://huggingface.co/datasets/tailot/codex-python/resolve/62eac4a1ea04f1b5d5aed88a1992a781a462174f/lingologos_python/rules.py
43.3 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
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"
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)
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 Target(rel_posix=rel_posix, symbol=symbol, text=text, tree=tree, read=read), None
def module_function(target: Target) -> Tuple[Optional[ast.FunctionDef], Optional[RuleMiss]]:
"""The module level function the target names, or the refusal that says why not."""
for node in target.tree.body:
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == 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 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)
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 _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)
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)
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),
)
body_start = starts[function.body[0].lineno - 1]
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 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="%sif %s is None:\n%s%s%s = %s\n" % (guard_indent, name, guard_indent, INDENT, name, literal),
)
)
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.%s(%s)" % (alias, target.symbol, _probe_arguments(function, mutable, "alpha")),
"second = %s.%s(%s)" % (alias, target.symbol, _probe_arguments(function, mutable, "beta")),
"assert first != second",
],
)
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)
# ---------------------------------------------------------------------------
# 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 any(uses(statement) for statement in function.body[last_use + 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)
if function is None:
return miss
assert function is not None
starts = line_starts(target.text)
first = function.body[0]
check = first.value if isinstance(first, ast.Expr) else first
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 = " " * first.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:
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, first)
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.%s("")' % (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,
)
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)
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,
}
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
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"
INDENT = " "
_MUTABLE_LITERALS = (ast.List, ast.Dict, ast.Set)
_MUTABLE_CALLS = ("list", "dict", "set")
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]]
class Edit:
"""One file the pattern would write, as a search and replace pair."""
file: str
search: str
replace: str
label: str
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 = ""
class RuleMiss:
"""The pattern does not apply, with the reason a corpus row is allowed to claim."""
reason_code: str
detail: str
target: str = ""