diff --git a/nominal_refactor_advisor/detectors/_restated_facts.py b/nominal_refactor_advisor/detectors/_restated_facts.py index be616f6f..26d64ff2 100644 --- a/nominal_refactor_advisor/detectors/_restated_facts.py +++ b/nominal_refactor_advisor/detectors/_restated_facts.py @@ -1045,12 +1045,13 @@ def forwards(sites: Sequence[RestatingSite]) -> list[RestatingSite]: ] def restates(self, site: RestatingSite, context: CompactClassFamilyIndex) -> bool: - """A member that overrides what an ancestor declares is the family's dispatch, - not a forward: a receiver typed as the ancestor reaches it through the MRO.""" + """A member that overrides an ancestor or is overridden by any descendant + is the family's polymorphic dispatch, not a pure forward: a receiver typed + as the family reaches the overriding subclass through the MRO.""" if site.detail[0] == ForwardingFacadeSiteFamily.CLASS_SITE: return True - return not _overrides_inherited(context, site.file_path, site.symbol, site.detail[0]) + return not _participates_in_dispatch(context, site.file_path, site.symbol, site.detail[0]) def admits(self, sites: Sequence[RestatingSite], context: CompactClassFamilyIndex) -> bool: return len(self.forwards(sites)) >= ForwardingFacadeSiteFamily.MIN_FORWARDS @@ -1091,14 +1092,24 @@ def finding_context( return {"metrics": ForwardingFacadeMetrics(len(self.forwards(sites)))} -def _overrides_inherited( +def _participates_in_dispatch( index: CompactClassFamilyIndex, file_path: str, qualname: str, member: str ) -> bool: - """Whether the member overrides a declaration the class inherits; a class the - index does not know is not proven free of one.""" + """Whether the member overrides a declaration the class inherits or is + overridden by any descendant in its subclass hierarchy; a class the index + does not know is not proven free of dispatch.""" symbol = index.symbol_for(file_path=file_path, qualname=qualname) - return symbol is None or bool(index.overridden_declarations(symbol, member)) + if symbol is None: + return True + if index.overridden_declarations(symbol, member): + return True + classes = index.classes_by_symbol + return any( + (descendant := classes.get(desc_symbol)) is not None + and member in descendant.member_binding_names + for desc_symbol in index.descendant_symbols(symbol) + ) class DeadModuleDetector( diff --git a/nominal_refactor_advisor/probe_owner.py b/nominal_refactor_advisor/probe_owner.py index dece2883..5cd9b392 100644 --- a/nominal_refactor_advisor/probe_owner.py +++ b/nominal_refactor_advisor/probe_owner.py @@ -346,6 +346,17 @@ def describe(self, field_name: str, context: ProbeOwnerContext) -> str: def resolved_in(self, context: ProbeOwnerContext) -> ProbeOwner: return self.resolved(context.typing).resolved_in(context) + def outside_family_symbols( + self, typing: DeclaredReceiverTyping, family: frozenset[str] + ) -> tuple[str, ...]: + """Declared scanned instance symbols of this expression that lie outside `family`.""" + + return tuple( + symbol + for symbol in self.path.declared(typing).instance_symbols() + if symbol not in family + ) + @dataclass(frozen=True) class ProbeOwnerResolver(ParsedModuleFact): diff --git a/nominal_refactor_advisor/refactors/foreign_absence_branch.py b/nominal_refactor_advisor/refactors/foreign_absence_branch.py index 436219d2..e6896560 100644 --- a/nominal_refactor_advisor/refactors/foreign_absence_branch.py +++ b/nominal_refactor_advisor/refactors/foreign_absence_branch.py @@ -71,6 +71,7 @@ class as a method eliminates the foreign absence probe without exporting a FunctionNode, InstanceDispatchKind, ModuleEnclosure, + NestedFunctionEnclosure, OuterReceiverAlias, ResolvedMethodAnnotations, TypeTestDispatchProof, @@ -2160,6 +2161,186 @@ def _resolve_scanned_instance_owner( return ResolvedClassTarget.from_rewrite_target(snapshot, source_rewrite_target(owner_indexed)) +def _subject_probed_attributes(site: AbsenceBranchSite) -> frozenset[str]: + """Attribute names read directly off `site.subject` inside its absence guard(s).""" + + subject_dump = ast.dump(site.subject) + attrs: set[str] = set() + for expr in site.guard_exprs(): + for node in ast.walk(expr): + match node: + case ast.Attribute(value=value, attr=attr) if ast.dump(value) == subject_dump: + attrs.add(attr) + return frozenset(attrs) + + +def _call_argument_for_parameter( + call: ast.Call, + param_name: str, + positional_indices: tuple[int, ...], +) -> ast.expr | None: + """The argument expression `call` passes for `param_name`, or None if omitted/unpacked.""" + + for kw in call.keywords: + if kw.arg == param_name: + return kw.value + for positional_index in positional_indices: + if positional_index >= len(call.args): + return None + if any(isinstance(arg, ast.Starred) for arg in call.args[: positional_index + 1]): + return None + return call.args[positional_index] + return None + + +def _require_parameter_callers_within_owner( + snapshot: CodemodSourceSnapshot, + source_path: str, + enclosure: FunctionEnclosure, + function: FunctionNode, + site: AbsenceBranchSite, + owner_symbol: str, + owner_qualname: str, +) -> None: + """Verify no scanned caller passes a supertype or unrelated instance to the + probed parameter. Python does not enforce parameter annotations at runtime, so + moving a branch onto a narrowed subclass (e.g. `EvidencedFragment` when callers + pass `HistoryFragment`, which also owns the probed attribute) raises + `AttributeError` on every non-subclass instance.""" + + match site.subject: + case ast.Name(id=param_name): + pass + case _: + return + + all_positional = (*function.args.posonlyargs, *function.args.args) + has_bound_receiver = ( + enclosure.receiver_symbol(snapshot) is not None + or enclosure.class_receiver_symbol(snapshot) is not None + ) + call_positional = all_positional[1:] if has_bound_receiver else all_positional + kwonly_names = {arg.arg for arg in function.args.kwonlyargs} + positional_indices = tuple( + idx for idx, arg in enumerate(call_positional) if arg.arg == param_name + ) + if not positional_indices and param_name not in kwonly_names: + return + + index = snapshot.compact_class_index + classes = index.classes_by_symbol + owner_family = frozenset((owner_symbol, *index.descendant_symbols(owner_symbol))) + typing = DeclaredReceiverTyping.from_projections( + snapshot.compact_class_projections, index + ) + probed_attrs = _subject_probed_attributes(site) + ancestors_with_attr = tuple( + anc + for anc in index.ancestor_symbols(owner_symbol) + if (decl := classes.get(anc)) is not None + and any(attr in decl.member_binding_names for attr in probed_attrs) + ) + + declaring_class = enclosure.declaring_class_symbol(snapshot) + callee_family: frozenset[str] = ( + frozenset( + ( + declaring_class, + *index.descendant_symbols(declaring_class), + *index.ancestor_symbols(declaring_class), + ) + ) + if declaring_class is not None + else frozenset() + ) + source_module = snapshot.parsed_module_for_source_path(source_path) + bindings = snapshot.module_binding_proof + expected_fn_qualified = f"{source_module.module_name}.{function.name}" + + if isinstance(enclosure, NestedFunctionEnclosure): + outer_fn = enclosure.enclosing_function_chain()[0] + candidate_modules = ( + (source_module, tuple(n for n in ast.walk(outer_fn) if isinstance(n, ast.Call))), + ) + else: + candidate_modules = tuple( + (parsed, parsed.syntax_index.instances_of(ast.Call)) + for parsed in snapshot.parsed_modules + if function.name in parsed.source + ) + + unproved_calls: list[tuple[str, int, ast.expr]] = [] + for parsed, calls in candidate_modules: + resolver = ProbeOwnerResolver.of(parsed) + for call in calls: + if declaring_class is not None: + match call.func: + case ast.Attribute(value=recv, attr=attr) if attr == function.name: + recv_syms = resolver.owner(recv).path.declared(typing).class_symbols() + if recv_syms and all( + sym in classes + and sym not in callee_family + and callee_family.isdisjoint(index.descendant_symbols(sym)) + for sym in recv_syms + ): + continue + case _: + continue + else: + match call.func: + case ast.Name(id=fn_name) | ast.Attribute(attr=fn_name) if fn_name == function.name: + witness = bindings.reference_or_builtin_witness_at( + parsed, call.func, line=call.lineno + ) + if witness is not None and witness.qualified_name != expected_fn_qualified: + continue + case _: + continue + + arg_expr = _call_argument_for_parameter(call, param_name, positional_indices) + if arg_expr is None: + continue + match arg_expr: + case ast.Constant(value=None): + raise NeedsInput( + f"{parsed.file_path}:{call.lineno} passes `None` to " + f"`{function.name}({param_name}: {owner_qualname})`; " + f"pushing onto `{owner_qualname}` would raise `AttributeError` at runtime", + NeededInput.SOURCE_CHANGE, + ) + path_owner = resolver.owner(arg_expr) + declared_syms = path_owner.path.declared(typing).instance_symbols() + if declared_syms: + outside = path_owner.outside_family_symbols(typing, owner_family) + if outside: + raise NeedsInput( + f"{parsed.file_path}:{call.lineno} passes `{ast.unparse(arg_expr)}` of type " + f"`{outside[0]}` to `{function.name}({param_name}: {owner_qualname})`, " + f"outside `{owner_qualname}`'s hierarchy; widen `{function.name}`'s parameter " + "annotation or narrow the caller before pushing", + NeededInput.SOURCE_CHANGE, + ) + continue + if ancestors_with_attr: + unproved_calls.append((parsed.file_path, call.lineno, arg_expr)) + + if unproved_calls: + spans = tuple(ReceiverSpan.of(fp, expr) for fp, _, expr in unproved_calls) + inferred = snapshot.type_checker.receiver_types(spans) + for (fp, lineno, arg_expr), span in zip(unproved_calls, spans): + answer = inferred.get(span) + if isinstance(answer, InferredReceiverType) and answer.classes: + outside = tuple(sym for sym in answer.classes if sym not in owner_family) + if outside: + raise NeedsInput( + f"{fp}:{lineno} passes `{ast.unparse(arg_expr)}` of inferred type " + f"`{answer.spelled}` to `{function.name}({param_name}: {owner_qualname})`, " + f"outside `{owner_qualname}`'s hierarchy; widen `{function.name}`'s parameter " + "annotation or narrow the caller before pushing", + NeededInput.SOURCE_CHANGE, + ) + + def _matching_existing_method_names( owner_node: ast.ClassDef, index: object, @@ -2517,6 +2698,15 @@ def proved( resolved_owner = _resolve_scanned_instance_owner(snapshot, source_path, site.subject) resolved_symbol = resolved_owner.required_symbol(snapshot) + _require_parameter_callers_within_owner( + snapshot, + source_path, + enclosure, + function, + site, + resolved_symbol, + resolved_owner.qualname, + ) if owner_target is not None: explicit = ResolvedClassTarget.from_rewrite_target(snapshot, owner_target) if explicit.required_symbol(snapshot) != resolved_symbol: diff --git a/nominal_refactor_advisor/refactors/member_move.py b/nominal_refactor_advisor/refactors/member_move.py index 8c13e0c3..a773af9b 100644 --- a/nominal_refactor_advisor/refactors/member_move.py +++ b/nominal_refactor_advisor/refactors/member_move.py @@ -63,8 +63,10 @@ SourceTextGeometry, SourceTextSpanReplacement, ) +from nominal_refactor_advisor.declared_receivers import DeclaredReceiverTyping from nominal_refactor_advisor.lexical_bindings import LEXICAL_SCOPE_BINDING_AUTHORITY from nominal_refactor_advisor.lexical_bindings import ImportBoundNameProjection +from nominal_refactor_advisor.probe_owner import ProbeOwnerResolver from nominal_refactor_advisor.refactors.function_operations import ( imports_only_read_by, method_deletion_offsets, @@ -547,6 +549,33 @@ def argument(self, call: MethodCall) -> PassedArgument: return PassedArgument(passed, passed) raise ValueError(f"{call.where} passes no {self.parameter.arg!r} to {self.moved.name!r}") + @cached_property + def _destination_typing(self) -> tuple[DeclaredReceiverTyping, frozenset[str]]: + snapshot = self.moved.snapshot + index = snapshot.compact_class_index + dest_symbol = self.moved.destination.required_symbol(snapshot) + dest_family = frozenset((dest_symbol, *index.descendant_symbols(dest_symbol))) + typing = DeclaredReceiverTyping.from_projections( + snapshot.compact_class_projections, index + ) + return typing, dest_family + + def _require_argument_within_destination(self, call: MethodCall, value: ast.expr) -> None: + """Refuse moving a method onto a destination class when a caller passes a + supertype or unrelated instance whose declared type lies outside the + destination's hierarchy.""" + + typing, dest_family = self._destination_typing + parsed = self.moved.snapshot.parsed_module_for_source_path(call.file_path) + outside = ProbeOwnerResolver.of(parsed).owner(value).outside_family_symbols( + typing, dest_family + ) + if outside: + raise ValueError( + f"{call.where} passes `{ast.unparse(value)}` of type `{outside[0]}`, " + f"outside destination `{self.moved.destination.qualname}`'s hierarchy" + ) + def replacement( self, geometry: SourceTextGeometry, call: MethodCall, ) -> tuple[SourceTextSpanReplacement, ...]: @@ -554,6 +583,7 @@ def replacement( receiver = call.attribute.value argument = self.argument(call) value = argument.value + self._require_argument_within_destination(call, value) passed: list[ast.AST] = sorted( (*call.call.args, *call.call.keywords), key=lambda each: geometry.required_node_offsets(each)[0], diff --git a/tests/test_foreign_absence_branch.py b/tests/test_foreign_absence_branch.py index 68e20ea4..29f322a9 100644 --- a/tests/test_foreign_absence_branch.py +++ b/tests/test_foreign_absence_branch.py @@ -2077,4 +2077,60 @@ def test_cross_module_push_preserves_aliased_module_and_symbol_imports( del sys.modules[mod_name] +def test_push_refuses_when_caller_passes_supertype_to_narrowed_parameter( + tmp_path: Path, +) -> None: + """Reproduces Toad `6358df80a` (`ReadMarkedHistory.retain_painted`): when a method's + parameter annotation is narrowed to `EvidencedFragment` while `HistoryFragment` owns + `evidence = None` and callers pass `HistoryFragment`, pushing onto `EvidencedFragment` + alone would raise `AttributeError` at runtime on non-evidenced subclasses.""" + + _write( + tmp_path, + { + "pkg/__init__.py": "", + "pkg/fragments.py": ( + "from dataclasses import dataclass\n\n\n" + "@dataclass\n" + "class HistoryFragment:\n" + " key: str\n" + " evidence: str | None = None\n\n\n" + "@dataclass\n" + "class EvidencedFragment(HistoryFragment):\n" + " evidence: str | None = None\n\n\n" + "@dataclass\n" + "class ToolFragment(HistoryFragment):\n" + " pass\n" + ), + "pkg/history.py": ( + "from pkg.fragments import EvidencedFragment, HistoryFragment\n\n\n" + "class ReadMarkedHistory:\n" + " def __init__(self) -> None:\n" + " self._painted: dict[str, HistoryFragment] = {}\n\n" + " def retain_painted(self, fragment: EvidencedFragment) -> None:\n" + " if fragment.evidence is not None:\n" + " self._painted[fragment.key] = fragment\n" + ), + "pkg/qt_view.py": ( + "from pkg.fragments import HistoryFragment\n" + "from pkg.history import ReadMarkedHistory\n\n\n" + "class QtHistoryView:\n" + " history: ReadMarkedHistory\n\n" + " def row_painted(self, fragment: HistoryFragment) -> None:\n" + " self.history.retain_painted(fragment)\n" + ), + }, + ) + + _mods, snap, findings = _scan(tmp_path) + (finding,) = [ + f for f in findings if f.primary_evidence.symbol == "ReadMarkedHistory.retain_painted" + ] + ev = ForeignAbsenceProbeDetector().evaluate_recipe_for_finding(finding, snap) + assert ev.needs == (NeededInput.SOURCE_CHANGE,) + assert "pkg.fragments.HistoryFragment" in ev.rejection_reason + assert "outside `EvidencedFragment`'s hierarchy" in ev.rejection_reason + + + diff --git a/tests/test_move_method_to_class.py b/tests/test_move_method_to_class.py index bd50d8d1..c3c15374 100644 --- a/tests/test_move_method_to_class.py +++ b/tests/test_move_method_to_class.py @@ -428,3 +428,48 @@ def test_a_module_the_method_reads_is_imported_into_the_destination_as_the_sourc moved = _source(tmp_path, result, "requests") assert binding in moved assert "from pkg.threads import json" not in moved and "from pkg.threads import osp" not in moved + + +@pytest.mark.native_proof +def test_move_method_to_parameter_refuses_caller_passing_supertype(tmp_path: Path) -> None: + """Moving a method onto a narrowed parameter subclass must refuse when a caller + passes a supertype instance whose declared type lies outside the destination.""" + + _write( + tmp_path, + { + "fragments": ( + "class HistoryFragment:\n" + " evidence = None\n\n\n" + "class EvidencedFragment(HistoryFragment):\n" + " pass\n" + ), + "history": ( + "from pkg.fragments import EvidencedFragment\n\n\n" + "class ReadMarkedHistory:\n" + " def retain_painted(self, fragment: EvidencedFragment) -> object:\n" + " return fragment.evidence\n" + ), + "view": ( + "from pkg.fragments import HistoryFragment\n" + "from pkg.history import ReadMarkedHistory\n\n\n" + "def row_painted(history: ReadMarkedHistory, fragment: HistoryFragment) -> object:\n" + " return history.retain_painted(fragment)\n" + ), + }, + ) + snapshot = CodemodSourceSnapshot.from_modules(parse_python_modules(tmp_path, use_parse_cache=False)) + operation = MoveMethodToClassOperation( + target=SourceRewriteTarget( + file_path=(tmp_path / "pkg/history.py").as_posix(), + qualname="ReadMarkedHistory.retain_painted", + ), + destination=SourceRewriteTarget( + file_path=(tmp_path / "pkg/fragments.py").as_posix(), + qualname="EvidencedFragment", + ), + receiver_parameter="history", + ) + with pytest.raises(CodemodOperationPreflightError, match="outside destination `EvidencedFragment`'s hierarchy"): + RefactorRecipe(recipe_id="test", reason="test").with_operation(operation).simulate(snapshot) + diff --git a/tests/test_restated_fact_detectors.py b/tests/test_restated_fact_detectors.py index 4f5d0784..af343516 100644 --- a/tests/test_restated_fact_detectors.py +++ b/tests/test_restated_fact_detectors.py @@ -1327,6 +1327,24 @@ def test_a_member_overriding_an_inherited_one_is_dispatch_not_a_forward(tmp_path assert _findings(tmp_path, ForwardingFacadeDetector, {"m": source}) == [] +def test_a_base_member_overridden_two_hops_down_is_dispatch_not_a_forward(tmp_path: Path): + """Reproduces Toad `WireCut.older()` overridden by `AfterSequence(AfterMessage)`: + a base method overridden anywhere in its subclass hierarchy is polymorphic default + dispatch, never a forwarding facade member.""" + + source = ( + "class WireCut:\n" + " def __init__(self, cursor):\n self.cursor = cursor\n" + " def older(self):\n return self.cursor.older()\n" + " def newer(self):\n return self.cursor.newer()\n\n\n" + "class AfterMessage(WireCut):\n" + " pass\n\n\n" + "class AfterSequence(AfterMessage):\n" + " def older(self):\n return ('custom', self.cursor)\n" + ) + assert _findings(tmp_path, ForwardingFacadeDetector, {"m": source}) == [] + + def test_a_cooperative_mi_mixin_implementing_a_sibling_base_is_not_a_facade(tmp_path: Path): source = ( "from abc import ABC, abstractmethod\n\n\n"