Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 18 additions & 7 deletions nominal_refactor_advisor/detectors/_restated_facts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down
11 changes: 11 additions & 0 deletions nominal_refactor_advisor/probe_owner.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
190 changes: 190 additions & 0 deletions nominal_refactor_advisor/refactors/foreign_absence_branch.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
"""Push absence-probing consumer branches onto the scanned class that owns the probed field.

When a consumer branches on `other.attr is None` / `other.attr is not None` and
Expand Down Expand Up @@ -71,6 +71,7 @@
FunctionNode,
InstanceDispatchKind,
ModuleEnclosure,
NestedFunctionEnclosure,
OuterReceiverAlias,
ResolvedMethodAnnotations,
TypeTestDispatchProof,
Expand Down Expand Up @@ -2160,6 +2161,186 @@
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,
Expand Down Expand Up @@ -2517,6 +2698,15 @@

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:
Expand Down
30 changes: 30 additions & 0 deletions nominal_refactor_advisor/refactors/member_move.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -547,13 +549,41 @@ 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, ...]:
self.dropped_receiver(call)
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],
Expand Down
56 changes: 56 additions & 0 deletions tests/test_foreign_absence_branch.py
Original file line number Diff line number Diff line change
Expand Up @@ -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




Loading
Loading