diff --git a/nominal_refactor_advisor/class_index.py b/nominal_refactor_advisor/class_index.py index 9e5f7621..05b5e2d9 100644 --- a/nominal_refactor_advisor/class_index.py +++ b/nominal_refactor_advisor/class_index.py @@ -4755,12 +4755,68 @@ def _of_statement( reads_its_class=bool(class_scope_names) or reads_class_cell_or_private_name(statement), ) + _ANNOTATION_INDEPENDENT_METHOD_DECORATORS = frozenset( + { + "property", + "cached_property", + "classmethod", + "staticmethod", + "override", + "final", + } + ) + + @classmethod + def _is_annotation_independent_method_decorator(cls, decorator: ast.expr) -> bool: + return ( + isinstance(decorator, (ast.Name, ast.Attribute)) + and _terminal_reference_name(decorator) + in cls._ANNOTATION_INDEPENDENT_METHOD_DECORATORS + ) + + @classmethod + def _strip_method_header_annotations( + cls, + method: ast.FunctionDef | ast.AsyncFunctionDef, + ) -> ast.FunctionDef | ast.AsyncFunctionDef: + """Clear parameter and return annotations on methods whose decorators never + inspect `__annotations__` at runtime (`property`, `classmethod`, etc.). + + Abstract stubs (`@abstractmethod`), `@overload`, and custom decorators keep + their annotations intact because their signatures are part of the contract. + """ + + if not all( + cls._is_annotation_independent_method_decorator(decorator) + for decorator in method.decorator_list + ): + return method + args = copy.copy(method.args) + args.posonlyargs = [ + replace_arg + for arg in args.posonlyargs + for replace_arg in (copy.copy(arg),) + ] + args.args = [copy.copy(arg) for arg in args.args] + args.kwonlyargs = [copy.copy(arg) for arg in args.kwonlyargs] + for arg in (*args.posonlyargs, *args.args, *args.kwonlyargs): + arg.annotation = None + if args.vararg is not None: + args.vararg = copy.copy(args.vararg) + args.vararg.annotation = None + if args.kwarg is not None: + args.kwarg = copy.copy(args.kwarg) + args.kwarg.annotation = None + method.args = args + method.returns = None + return method + @classmethod def _normalized_method( cls, method: ast.FunctionDef | ast.AsyncFunctionDef, ) -> ast.FunctionDef | ast.AsyncFunctionDef: - normalized = copy.copy(method) + normalized = cls._strip_method_header_annotations(copy.copy(method)) normalized.body = _trim_leading_docstring(list(method.body)) or [ast.Pass()] positional = (*normalized.args.posonlyargs, *normalized.args.args) receiver_name = positional[0].arg if positional else None diff --git a/nominal_refactor_advisor/refactors/restated_overrides.py b/nominal_refactor_advisor/refactors/restated_overrides.py index 6cad4d48..a28c27d1 100644 --- a/nominal_refactor_advisor/refactors/restated_overrides.py +++ b/nominal_refactor_advisor/refactors/restated_overrides.py @@ -857,6 +857,31 @@ def unproved(self) -> str: return f"NRA needs a proof that deleting {self.proof.owner_name} leaves it unchanged" +def method_header_annotations(statement: ast.stmt) -> dict[str, str]: + """Non-empty parameter and return annotations spelled on one method header.""" + + if not isinstance(statement, (ast.FunctionDef, ast.AsyncFunctionDef)): + return {} + annotations: dict[str, str] = {} + args = statement.args + for index, arg in enumerate(args.posonlyargs): + if arg.annotation is not None: + annotations[f"posonly:{index}"] = ast.unparse(arg.annotation) + for index, arg in enumerate(args.args): + if arg.annotation is not None: + annotations[f"arg:{index}"] = ast.unparse(arg.annotation) + if args.vararg is not None and args.vararg.annotation is not None: + annotations["vararg"] = ast.unparse(args.vararg.annotation) + for arg in args.kwonlyargs: + if arg.annotation is not None: + annotations[f"kwonly:{arg.arg}"] = ast.unparse(arg.annotation) + if args.kwarg is not None and args.kwarg.annotation is not None: + annotations["kwarg"] = ast.unparse(args.kwarg.annotation) + if statement.returns is not None: + annotations["return"] = ast.unparse(statement.returns) + return annotations + + @dataclass(frozen=True) class RestatedOverrideDeletion: """One class's members that restate what it inherits, proved deletable.""" @@ -902,8 +927,12 @@ def proved(cls, snapshot: CodemodSourceSnapshot, overlap: OverlapClass) -> Resta f"`{overlap.qualname}`'s order, not first by `{inherited}`", NeededInput.PROOF, ) + inherited_overlap = OverlapClass.for_symbol(snapshot, inherited) restatement = RestatedDeclarations.require( - snapshot, OverlapClass.for_symbol(snapshot, inherited), overlap, (name,) + snapshot, inherited_overlap, overlap, (name,) + ) + cls._require_inherited_preserves_annotations( + overlap, inherited_overlap, restatement, name ) for statement in restatement.statements: cls.require_once_per_class(proof, overlap, statement) @@ -913,6 +942,38 @@ def proved(cls, snapshot: CodemodSourceSnapshot, overlap: OverlapClass) -> Resta NamespaceReaders(snapshot).require_unread(overlap.facts, names) return cls(overlap, tuple(restated)) + @staticmethod + def _require_inherited_preserves_annotations( + overlap: OverlapClass, + inherited_overlap: OverlapClass, + restatement: RestatedDeclarations, + name: str, + ) -> None: + """Deleting an override must not silently drop or alter type annotations the + subclass declared and the inherited definition lacks or spells differently.""" + + if len(restatement.statements) != 1: + return + child_annotations = method_header_annotations(restatement.statements[0]) + if not child_annotations: + return + inherited_statements = inherited_overlap.statements_declaring((name,)) + if len(inherited_statements) != 1: + return + inherited_annotations = method_header_annotations(inherited_statements[0]) + changed = [ + f"{slot}: `{value}`" + for slot, value in child_annotations.items() + if inherited_annotations.get(slot) != value + ] + if changed: + raise NeedsInput( + f"`{overlap.qualname}.{name}` declares type annotation(s) ({', '.join(changed)}) " + f"not matched on `{inherited_overlap.qualname}.{name}`: align the annotations on " + f"`{inherited_overlap.qualname}.{name}` before deleting the override", + NeededInput.SOURCE_CHANGE, + ) + @staticmethod def require_once_per_class( proof: ClassCreationProof, overlap: OverlapClass, statement: ast.stmt diff --git a/nominal_refactor_advisor/refactors/sibling_overrides.py b/nominal_refactor_advisor/refactors/sibling_overrides.py index f4418bbf..8f723365 100644 --- a/nominal_refactor_advisor/refactors/sibling_overrides.py +++ b/nominal_refactor_advisor/refactors/sibling_overrides.py @@ -89,6 +89,7 @@ MemberDeletionCreationProof, NamespaceReaders, RestatedOverrideDeletion, + method_header_annotations, next_binder, ) @@ -138,8 +139,6 @@ def require_no_existing_home(self, member_name, snapshot, declaring, verdicts, c if '.' in child.qualname: raise NeedsInput(f'`{child.qualname}` is nested inside another class; declaring an intermediate base needs top-level sibling classes', NeededInput.SOURCE_CHANGE) restated = tuple((RestatedDeclarations.require(snapshot, children[0], child, (member_name,)) for child in children)) - first = restated[0] - first.require_no_owner_bound_values(snapshot) rebase = cls._select_rebase(snapshot, verdicts, declaring, children) if '.' in rebase.parent.qualname: raise NeedsInput(f'`{rebase.parent.qualname}` is nested inside another class', NeededInput.SOURCE_CHANGE) @@ -148,7 +147,9 @@ def require_no_existing_home(self, member_name, snapshot, declaring, verdicts, c placement, parent_spelling = cls._select_placement(snapshot, rebase, children, base_name) cls._require_base_name_unbound(snapshot, base_name, placement, children) creation_keywords = _creation_keywords_for_intermediate(snapshot, rebase.parent) - movable_members(ClassMemberMoveProofContext.between(snapshot, children[0].target, placement.anchor.target), children[0], first.statements) + lifted_index = SiblingOverrideMove.select_lifted_index(snapshot, children, restated, placement.anchor.target, member_name) + first = restated[lifted_index] + first.require_no_owner_bound_values(snapshot) cls._require_post_rebase_mro_safe(snapshot, verdicts, rebase, declaring, children, member_name, base_name, lifted_is_property=any((_is_property_statement(statement) for statement in first.statements))) names = frozenset((member_name,)) for child, restatement in zip(children, restated): @@ -160,7 +161,7 @@ def require_no_existing_home(self, member_name, snapshot, declaring, verdicts, c RestatedOverrideDeletion.require_plain_decorators(proof, child) proof.require_unchanged() NamespaceReaders(snapshot).require_unread(child.facts, names) - return cls(candidate=self, rebase=rebase, placement=placement, parent_spelling=parent_spelling, base_name=base_name, docstring=docstring.strip(), creation_keywords=creation_keywords, children=children, restated=restated) + return cls(candidate=self, rebase=rebase, placement=placement, parent_spelling=parent_spelling, base_name=base_name, docstring=docstring.strip(), creation_keywords=creation_keywords, children=children, restated=restated, lifted_index=lifted_index) def existing_home_note(self): """Format the summary clause naming an existing home class when one exists.""" @@ -819,6 +820,65 @@ class SiblingOverrideMove(ABC): candidate: SiblingOverrideCandidate children: tuple[OverlapClass, ...] restated: tuple[RestatedDeclarations, ...] + lifted_index: int + + @property + def lifted_restatement(self) -> RestatedDeclarations: + return self.restated[self.lifted_index] + + @staticmethod + def select_lifted_index( + snapshot: CodemodSourceSnapshot, + children: tuple[OverlapClass, ...], + restated: tuple[RestatedDeclarations, ...], + destination_target, + member_name: str, + ) -> int: + """Choose which sibling's source statement moves onto the shared ancestor. + + When siblings differ only by omitted type annotations, prefer the most-annotated + copy whose annotation imports move cleanly without closing a cycle. Refuse when + siblings declare conflicting annotations on the same header slot. + """ + + annotations_by_index = [ + method_header_annotations(restatement.statements[0]) + if len(restatement.statements) == 1 + else {} + for restatement in restated + ] + seen_slots: dict[str, str] = {} + for slot_map in annotations_by_index: + for slot, spelling in slot_map.items(): + prior = seen_slots.get(slot) + if prior is not None and prior != spelling: + raise NeedsInput( + f"siblings annotate `{member_name}` differently on {slot} " + f"(`{prior}` vs `{spelling}`): align the signature before lifting", + NeededInput.SOURCE_CHANGE, + ) + seen_slots[slot] = spelling + candidate_indices = sorted( + range(len(children)), + key=lambda index: (-len(annotations_by_index[index]), index), + ) + first_error: NeedsInput | None = None + for index in candidate_indices: + try: + movable_members( + ClassMemberMoveProofContext.between( + snapshot, children[index].target, destination_target + ), + children[index], + restated[index].statements, + ) + except NeedsInput as error: + if first_error is None: + first_error = error + continue + return index + assert first_error is not None + raise first_error @dataclass(frozen=True) @@ -873,15 +933,11 @@ def proved( RestatedDeclarations.require(snapshot, children[0], child, (member_name,)) for child in children ) - first = restated[0] - first.require_no_owner_bound_values(snapshot) - movable_members( - ClassMemberMoveProofContext.between( - snapshot, children[0].target, home.target - ), - children[0], - first.statements, + lifted_index = cls.select_lifted_index( + snapshot, children, restated, home.target, member_name ) + first = restated[lifted_index] + first.require_no_owner_bound_values(snapshot) placement = cls._require_home_placement( snapshot, verdicts, candidate, home, member_name ) @@ -931,6 +987,7 @@ def proved( candidate=candidate, children=children, restated=restated, + lifted_index=lifted_index, home=home, placement=placement, ) @@ -1110,7 +1167,7 @@ def edits( self, snapshot: CodemodSourceSnapshot, rationale: str ) -> tuple[NominalSourceEdit, ...]: home = self.home - first = self.restated[0] + first = self.lifted_restatement documentation = KeptDocumentation(self.children, first.deleted_names) rationale = documentation.rationale(rationale) home_source = snapshot.sources_by_file_path[home.file_path] @@ -1884,7 +1941,7 @@ def _require_post_rebase_mro_safe( def edits( self, snapshot: CodemodSourceSnapshot, rationale: str ) -> tuple[NominalSourceEdit, ...]: - first = self.restated[0] + first = self.lifted_restatement documentation = KeptDocumentation(self.children, first.deleted_names) rationale = documentation.rationale(rationale) edits: list[NominalSourceEdit] = [ diff --git a/tests/test_restated_overrides.py b/tests/test_restated_overrides.py index 6fbe571f..16d422b9 100644 --- a/tests/test_restated_overrides.py +++ b/tests/test_restated_overrides.py @@ -383,3 +383,79 @@ def test_a_metaclass_that_rewrites_its_bases_refuses_the_deletion(tmp_path: Path def test_a_metaclass_handing_its_bases_on_keeps_the_deletion(tmp_path: Path): _write(tmp_path, {"pkg/__init__.py": "", "pkg/ends.py": _rebasing("bases")}) assert [finding.primary_evidence.symbol for finding in _findings(tmp_path)] == ["Member"] + + +def test_restated_method_omitting_parent_annotation_is_found_and_deleted(tmp_path: Path): + _write( + tmp_path, + { + "pkg/__init__.py": "", + "pkg/annotated.py": ( + "class Base:\n" + " @property\n" + " def value(self) -> int:\n" + " return 1\n\n\n" + "class Child(Base):\n" + " @property\n" + " def value(self):\n" + " return 1\n" + ), + }, + ) + assert [f.primary_evidence.symbol for f in _findings(tmp_path)] == ["Child"] + evaluation = _evaluation(tmp_path, "Child") + assert evaluation.recipe is not None, evaluation.rejection_reason + simulation = evaluation.recipe.simulate(_snapshot(tmp_path)) + assert simulation.is_clean, simulation.preflight_report + simulation.apply() + assert _findings(tmp_path) == [] + + +def test_restated_method_adding_annotation_absent_on_parent_refuses_dropping_it( + tmp_path: Path, +): + """Reproduces Toad `FrozenClosedHistory.latest -> PreparedTranscriptPage` over + unannotated `ClosedHistory.latest`: flagged as a restated body, while deletion + refuses silently dropping the subclass return annotation.""" + + _write( + tmp_path, + { + "pkg/__init__.py": "", + "pkg/history.py": ( + "class ClosedHistory:\n" + " async def latest(self, page: str):\n" + " return page.strip()\n\n\n" + "class FrozenClosedHistory(ClosedHistory):\n" + " async def latest(self, page: str) -> str:\n" + " return page.strip()\n" + ), + }, + ) + assert [f.primary_evidence.symbol for f in _findings(tmp_path)] == ["FrozenClosedHistory"] + evaluation = _evaluation(tmp_path, "FrozenClosedHistory") + assert evaluation.recipe is None + assert "declares type annotation(s)" in evaluation.rejection_reason + assert NeededInput.SOURCE_CHANGE in evaluation.needs + + +def test_abstractmethod_with_different_return_annotation_is_no_finding(tmp_path: Path): + """Reproduces Toad `ActivatesContract.activate() -> None` vs `Activates.activate() -> object`: + abstract stubs' signatures ARE their contracts and must not be collapsed.""" + + _write( + tmp_path, + { + "pkg/__init__.py": "", + "pkg/contracts.py": ( + "from abc import ABC, abstractmethod\n\n\n" + "class ActivatesContract(ABC):\n" + " @abstractmethod\n" + " def activate(self) -> None: ...\n\n\n" + "class Activates(ActivatesContract):\n" + " @abstractmethod\n" + " def activate(self) -> object: ...\n" + ), + }, + ) + assert _findings(tmp_path) == [] diff --git a/tests/test_sibling_overrides.py b/tests/test_sibling_overrides.py index c5d62d9b..d2eab7a9 100644 --- a/tests/test_sibling_overrides.py +++ b/tests/test_sibling_overrides.py @@ -725,3 +725,101 @@ def test_refuses_extract_when_picked_base_name_collides(tmp_path: Path): assert evaluation.recipe is None assert "already bound" in evaluation.rejection_reason assert NeededInput.OWNER_PICK in evaluation.needs + + +def test_sibling_property_with_return_annotation_on_one_sibling_lifts_keeping_annotation( + tmp_path: Path, +): + """Reproduces Toad `ConversationPager.selected_categories`: an unannotated + `@property` on Qt and an annotated `@property` on Textual are one + declaration and lift onto their shared ancestor keeping the annotation.""" + + _write( + tmp_path, + { + "pkg/__init__.py": "", + "pkg/pager.py": ( + "from __future__ import annotations\n\n\n" + "class HistoryPager:\n" + " @property\n" + " def selected_categories(self) -> frozenset[str]:\n" + " return frozenset(('all',))\n\n\n" + "class ConversationPager(HistoryPager):\n" + " pass\n" + ), + "pkg/qt_history.py": ( + "from pkg.pager import ConversationPager\n\n\n" + "class QtConversationHistory(ConversationPager):\n" + " def __init__(self, visible: frozenset[str]) -> None:\n" + " self.visible = visible\n\n" + " @property\n" + " def selected_categories(self):\n" + " return self.visible\n" + ), + "pkg/tui_history.py": ( + "from __future__ import annotations\n\n" + "from pkg.pager import ConversationPager\n\n\n" + "class ConversationHistory(ConversationPager):\n" + " def __init__(self, visible: frozenset[str]) -> None:\n" + " self.visible = visible\n\n" + " @property\n" + " def selected_categories(self) -> frozenset[str]:\n" + " return self.visible\n" + ), + }, + ) + findings = _findings(tmp_path) + assert len(findings) == 1 + assert "`ConversationPager` already exists to hold it" in findings[0].summary + evaluation = SiblingOverrideDetector().evaluate_recipe_for_finding( + findings[0], _snapshot(tmp_path) + ) + assert evaluation.recipe is not None, evaluation.rejection_reason + simulation = evaluation.recipe.simulate(_snapshot(tmp_path)) + assert simulation.is_clean, simulation.preflight_report + simulation.apply() + pager_text = (tmp_path / "pkg/pager.py").read_text() + assert "def selected_categories(self) -> frozenset[str]:" in pager_text + assert "selected_categories" not in (tmp_path / "pkg/qt_history.py").read_text() + assert "selected_categories" not in (tmp_path / "pkg/tui_history.py").read_text() + assert _findings(tmp_path) == [] + + +def test_sibling_property_with_conflicting_return_annotations_is_found_and_refuses_blind_lift( + tmp_path: Path, +): + """Reproduces Toad `QtQuestion.question -> QtQuestion` vs `Question.question -> Question`: + detected as identical runtime overrides, while lifting refuses stamping one sibling's + return type onto the other.""" + + _write( + tmp_path, + { + "pkg/__init__.py": "", + "pkg/question.py": ( + "from __future__ import annotations\n" + "from abc import ABC, abstractmethod\n\n\n" + "class QuestionContext(ABC):\n" + " @property\n" + " @abstractmethod\n" + " def question(self) -> QuestionContext: ...\n\n\n" + "class QtQuestion(QuestionContext):\n" + " @property\n" + " def question(self) -> QtQuestion:\n" + " return self\n\n\n" + "class TuiQuestion(QuestionContext):\n" + " @property\n" + " def question(self) -> TuiQuestion:\n" + " return self\n" + ), + }, + ) + findings = _findings(tmp_path) + assert len(findings) == 1 + assert "QuestionContext.question" in findings[0].summary + evaluation = SiblingOverrideDetector().evaluate_recipe_for_finding( + findings[0], _snapshot(tmp_path) + ) + assert evaluation.recipe is None + assert "annotate `question` differently" in evaluation.rejection_reason + assert NeededInput.SOURCE_CHANGE in evaluation.needs