diff --git a/nominal_refactor_advisor/class_index.py b/nominal_refactor_advisor/class_index.py index 39963bff..c711b924 100644 --- a/nominal_refactor_advisor/class_index.py +++ b/nominal_refactor_advisor/class_index.py @@ -831,6 +831,7 @@ class CompactAnnotatedMethod(CompactCallableMemberDeclaration): """A method with a return annotation: calling it has that type.""" return_annotation_expression: str + is_async: bool = False def answer(self, owner: CompactIndexedClass, answers: ClassMemberAnswersABC[MemberAnswerT]) -> MemberAnswerT: return answers.annotated_method(owner, self) @@ -942,6 +943,7 @@ class CompactAnnotatedFunctionReturn: name: str line: int return_annotation_expression: str + is_async: bool = False class CompactDataclassFieldRole(StrEnum): @@ -1418,6 +1420,8 @@ def own_dataclass_field_names(self) -> tuple[str, ...] | None: end_line: int | None = None method_names: tuple[str, ...] = () callable_member_declarations: tuple[CompactCallableMemberDeclaration, ...] = () + init_attribute_annotations: tuple[tuple[str, str], ...] = () + """Unambiguous `self.: T` annotations declared directly inside `__init__`.""" base_argument_sources: tuple[tuple[str, ...], ...] = () """Each referenced base's subscript arguments (`Base[A, B]`), aligned with its base references.""" type_parameter_names: tuple[str, ...] = () @@ -5566,6 +5570,7 @@ def _compact_indexed_classes( callable_member_declarations=_compact_callable_member_declarations( node, binding_snapshots[node.lineno] ), + init_attribute_annotations=_compact_init_attribute_annotations(node), abstract_method_names=sorted_tuple( statement.name for statement in FunctionDefinition.within(node.body) @@ -6094,7 +6099,10 @@ def collect_stub( type_aliases=_module_type_aliases(parsed_module), annotated_function_returns=tuple( CompactAnnotatedFunctionReturn( - node.name, node.lineno, ast.unparse(returns) + node.name, + node.lineno, + ast.unparse(returns), + is_async=isinstance(node, ast.AsyncFunctionDef), ) for node in FunctionDefinition.within(parsed_module.module.body) for returns in declared_annotations(node) @@ -6142,7 +6150,10 @@ def _collect( type_aliases=_module_type_aliases(parsed_module), annotated_function_returns=tuple( CompactAnnotatedFunctionReturn( - node.name, node.lineno, ast.unparse(returns) + node.name, + node.lineno, + ast.unparse(returns), + is_async=isinstance(node, ast.AsyncFunctionDef), ) for node in FunctionDefinition.within(parsed_module.module.body) for returns in declared_annotations(node) @@ -7752,9 +7763,14 @@ def _compact_callable_member_declarations( ) if reads_as_property: property_names.add(statement.name) + is_async = isinstance(statement, ast.AsyncFunctionDef) declared = tuple( - (CompactAnnotatedProperty if reads_as_property else CompactAnnotatedMethod)( - statement.name, statement.lineno, ast.unparse(returns) + ( + CompactAnnotatedProperty(statement.name, statement.lineno, ast.unparse(returns)) + if reads_as_property + else CompactAnnotatedMethod( + statement.name, statement.lineno, ast.unparse(returns), is_async=is_async + ) ) for returns in declared_annotations(statement) ) @@ -7764,6 +7780,58 @@ def _compact_callable_member_declarations( return tuple(declarations) +def _compact_init_attribute_annotations( + node: ast.ClassDef, +) -> tuple[tuple[str, str], ...]: + """Unambiguous `self.: T` annotations declared inside `__init__`.""" + + init_defs = [ + statement + for statement in FunctionDefinition.within(node.body) + if statement.name == "__init__" + ] + if len(init_defs) != 1: + return () + init_def = init_defs[0] + positional = (*init_def.args.posonlyargs, *init_def.args.args) + if not positional: + return () + self_name = positional[0].arg + annotations: dict[str, str] = {} + ambiguous: set[str] = set() + + def walk(statements: Sequence[ast.stmt]) -> None: + for stmt in statements: + match stmt: + case ast.AnnAssign( + target=ast.Attribute(value=ast.Name(id=receiver), attr=attr), + annotation=annotation, + ) if receiver == self_name: + source = ast.unparse(annotation) + previous = annotations.get(attr) + if previous is not None and previous != source: + ambiguous.add(attr) + else: + annotations[attr] = source + case ast.FunctionDef() | ast.AsyncFunctionDef() | ast.ClassDef(): + continue + case _: + for field_value in ast.iter_child_nodes(stmt): + if isinstance(field_value, ast.stmt): + walk((field_value,)) + elif isinstance(field_value, ast.ExceptHandler): + walk(field_value.body) + elif isinstance(field_value, ast.match_case): + walk(field_value.body) + + walk(init_def.body) + return tuple( + (name, source) + for name, source in annotations.items() + if name not in ambiguous + ) + + def _redefines_property( statement: ast.FunctionDef | ast.AsyncFunctionDef, property_names: Collection[str] ) -> bool: @@ -7825,6 +7893,44 @@ def stub(module_name: str) -> CompactModuleClassProjection | None: (projection,) = found return projection + @staticmethod + @cache + def import_aliases_map(module_name: str) -> Mapping[str, str]: + """Import aliases of an installed module, cached once per module.""" + + projection = InstalledClassDeclarations.module(module_name) + return dict(projection.import_aliases) if projection is not None else {} + + @classmethod + def is_nominal_non_protocol_class( + cls, + qualified_name: str, + scan: CompactRepositoryPublicExposureIndex, + ) -> bool: + """Whether `qualified_name` resolves to an installed non-`Protocol`, non-`object` class.""" + + if qualified_name in {"builtins.object", "typing.Any", "typing_extensions.Any"}: + return False + protocol_names = frozenset(("typing.Protocol", "typing_extensions.Protocol")) + root = cls.declaration(qualified_name, scan) + if root is None: + return False + pending = [root] + seen: set[str] = {root.symbol} + while pending: + current = pending.pop() + for base_ref in current.base_references: + base_name = base_ref.qualified_name + if base_name in protocol_names: + return False + if base_name == "builtins.object" or base_name in seen: + continue + seen.add(base_name) + resolved_base = cls.declaration(base_name, scan) + if resolved_base is not None: + pending.append(resolved_base) + return True + @staticmethod @cache def lazy_getattr_aliases(module_name: str) -> Mapping[str, str]: diff --git a/nominal_refactor_advisor/declared_receivers.py b/nominal_refactor_advisor/declared_receivers.py index ed6619d4..6799eec7 100644 --- a/nominal_refactor_advisor/declared_receivers.py +++ b/nominal_refactor_advisor/declared_receivers.py @@ -57,6 +57,7 @@ CompactModuleClassProjection, CompactModuleClassProjectionFamily, CompactUnannotatedCallable, + InstalledClassDeclarations, native_identity, build_compact_class_family_index, ) @@ -136,6 +137,19 @@ def attribute(self, typing: DeclaredReceiverTyping, name: str) -> DeclaredType: def called(self, typing: DeclaredReceiverTyping, name: str) -> DeclaredType: return UndeclaredType(f"{self.spelled()} has no declared method `{name}`") + def awaited_called(self, typing: DeclaredReceiverTyping, name: str) -> DeclaredType: + return UndeclaredType(f"{self.spelled()} has no declared async method `{name}`") + + def reaches_method_owner( + self, + reaching_symbols: frozenset[str], + reaching_ancestors: frozenset[str], + is_nominal_class: Callable[[str], bool], + ) -> bool | None: + """Whether this declared type can reach `reaching_symbols`, or `None` if unproved.""" + del reaching_symbols, reaching_ancestors, is_nominal_class + return None + def element(self, typing: DeclaredReceiverTyping) -> DeclaredType: return UndeclaredType(f"{self.spelled()} is not a declared collection") @@ -225,6 +239,21 @@ class DeclaredScannedClasses(DeclaredType): def class_symbols(self) -> tuple[str, ...]: return self.symbols + def reaches_method_owner( + self, + reaching_symbols: frozenset[str], + reaching_ancestors: frozenset[str], + is_nominal_class: Callable[[str], bool], + ) -> bool | None: + if any(sym in reaching_symbols for sym in self.symbols): + return True + if self.symbols and all( + sym not in reaching_ancestors and is_nominal_class(sym) + for sym in self.symbols + ): + return False + return None + @abstractmethod def with_symbols(self, symbols: tuple[str, ...]) -> DeclaredType: raise NotImplementedError @@ -254,6 +283,11 @@ def called(self, typing: DeclaredReceiverTyping, name: str) -> DeclaredType: typing.method_call(symbol, name, self) for symbol in self.symbols ) + def awaited_called(self, typing: DeclaredReceiverTyping, name: str) -> DeclaredType: + return typing.joined( + typing.awaited_method_call(symbol, name, self) for symbol in self.symbols + ) + def with_symbols(self, symbols: tuple[str, ...]) -> DeclaredType: return DeclaredInstance(symbols) @@ -287,6 +321,20 @@ class DeclaredForeignInstance(DeclaredType): def class_symbols(self) -> tuple[str, ...]: return self.qualified_names + def reaches_method_owner( + self, + reaching_symbols: frozenset[str], + reaching_ancestors: frozenset[str], + is_nominal_class: Callable[[str], bool], + ) -> bool | None: + del reaching_symbols + if self.qualified_names and all( + fqn not in reaching_ancestors and is_nominal_class(fqn) + for fqn in self.qualified_names + ): + return False + return None + def spelled(self) -> str: return " | ".join(f"`{name}`" for name in self.qualified_names) @@ -311,7 +359,7 @@ class DeclaredClassObject(DeclaredScannedClasses): def attribute(self, typing: DeclaredReceiverTyping, name: str) -> DeclaredType: return typing.joined( - typing.member_read(symbol, name, DeclaredInstance((symbol,))) + typing.class_member_read(symbol, name, DeclaredInstance((symbol,))) for symbol in self.symbols ) @@ -321,6 +369,12 @@ def called(self, typing: DeclaredReceiverTyping, name: str) -> DeclaredType: for symbol in self.symbols ) + def awaited_called(self, typing: DeclaredReceiverTyping, name: str) -> DeclaredType: + return typing.joined( + typing.awaited_method_call(symbol, name, DeclaredInstance((symbol,))) + for symbol in self.symbols + ) + def element(self, typing: DeclaredReceiverTyping) -> DeclaredType: """Iterating an enum class yields its members.""" return typing.joined(typing.enum_members(symbol) for symbol in self.symbols) @@ -841,6 +895,14 @@ def declaring(self, symbol: str) -> DeclaredReceiverTyping: def member_read( self, symbol: str, name: str, receiver: DeclaredInstance + ) -> DeclaredType: + typing = self.declaring(symbol) + return typing.class_index.declared_member(symbol, name).answer( + _InstanceMemberRead(typing, symbol, name, receiver) + ) + + def class_member_read( + self, symbol: str, name: str, receiver: DeclaredInstance ) -> DeclaredType: typing = self.declaring(symbol) return typing.class_index.declared_member(symbol, name).answer( @@ -855,6 +917,14 @@ def method_call( _MethodCall(typing, symbol, name, receiver) ) + def awaited_method_call( + self, symbol: str, name: str, receiver: DeclaredInstance + ) -> DeclaredType: + typing = self.declaring(symbol) + return typing.class_index.declared_member(symbol, name).answer( + _AwaitedMethodCall(typing, symbol, name, receiver) + ) + def function_result(self, function_symbol: str) -> DeclaredType: module = function_symbol.rpartition(".")[0] declared = self.function_returns.get(function_symbol, ()) @@ -1077,11 +1147,34 @@ def called_unscanned( f"`{'.'.join(parts)}(...)` calls no scanned class or annotated function" ) + def awaited_called_reference( + self, module_name: str, parts: tuple[str, ...] + ) -> DeclaredType: + """`await f(...)` or `await C.m(...)` for an `async def` function or method.""" + + function = self.qualified(module_name, parts) + declared = self.function_returns.get(function, ()) + if declared: + if len(declared) == 1 and declared[0].is_async: + return self.function_result(function) + return UndeclaredType(f"`{function}` is not a single async function") + if len(parts) > 1: + return self.reference(module_name, parts[:-1]).awaited_called(self, parts[-1]) + return UndeclaredType( + f"`await {'.'.join(parts)}(...)` calls no annotated async function" + ) + def qualified(self, module_name: str, parts: tuple[str, ...]) -> str: """The qualified name a module-level name chain spells.""" head, *rest = parts - aliases = self.aliases_by_module.get(module_name, {}) + aliases = self.aliases_by_module.get(module_name) + if aliases is None: + aliases = ( + InstalledClassDeclarations.import_aliases_map(module_name) + if module_name.partition(".")[0] not in self.scanned_roots + else {} + ) if head in aliases: return ".".join((aliases[head], *rest)) if head in self.definitions_by_module.get(module_name, frozenset()) or not hasattr( @@ -1464,6 +1557,38 @@ def open(self) -> DeclaredType: return UndeclaredType(f"`{self.symbol}`'s MRO is open before `{self.name}`") +@dataclass(frozen=True) +class _InstanceMemberRead(_MemberRead): + """Reading `instance.name`: falls back to `__init__` `self.: T` annotations + along the resolved MRO prefix when no class-body declaration binds `name`.""" + + def _from_init(self) -> DeclaredType | None: + authority = self.typing.class_index.declared_mro_authority + mro = authority.resolve(self.symbol).mro_type + if mro is not None: + owners = mro.declarations_before( + lambda entry: authority.bases.stops_lookup(entry, self.name) + ) + else: + direct = self.typing.class_index.class_for(self.symbol) + owners = (direct,) if direct is not None else () + for owner in owners: + for attr_name, source in owner.init_attribute_annotations: + if attr_name == self.name: + return self.typing.annotation_source_type( + owner.module_name, source, self.scope(owner) + ) + return None + + def missing(self) -> DeclaredType: + found = self._from_init() + return found if found is not None else super().missing() + + def open(self) -> DeclaredType: + found = self._from_init() + return found if found is not None else super().open() + + @dataclass(frozen=True) class _MethodCall(_MemberRead): """Calling `receiver.name(...)`: the method's declared return, `Self` the receiver.""" @@ -1480,6 +1605,16 @@ def annotated_method(self, owner: CompactIndexedClass, declaration: CompactAnnot ) +@dataclass(frozen=True) +class _AwaitedMethodCall(_MethodCall): + """Awaiting `await receiver.name(...)`: only `async def` methods unwrap here.""" + + def annotated_method(self, owner: CompactIndexedClass, declaration: CompactAnnotatedMethod) -> DeclaredType: + if not declaration.is_async: + return UndeclaredType(f"`{owner.symbol}.{self.name}` is not an async method") + return super().annotated_method(owner, declaration) + + def _reference_parts(node: ast.expr) -> tuple[str, ...]: match node: case ast.Name(id=name): @@ -1508,6 +1643,15 @@ def method_call_of(self, path: ReceiverPath, name: str) -> ReceiverPath: """`P.name(...)`, for a path P starting here.""" return path.then(CallStep(name)) + def awaited_method_call_of(self, path: ReceiverPath, name: str) -> ReceiverPath: + """`await P.name(...)`, for a path P starting here.""" + return path.then(AwaitCallStep(name)) + + def awaited_call_of(self, path: ReceiverPath) -> ReceiverPath: + """`await P(...)`, for a path P starting here.""" + del path + return unresolved("the awaited call's callee is not a declared async callable") + def call_of( self, path: ReceiverPath, @@ -1591,6 +1735,16 @@ def method_call_of(self, path: ReceiverPath, name: str) -> ReceiverPath: return super().method_call_of(path, name) return ReceiverPath(CalledReferenceRoot(self.module_name, (*self.parts, name))) + def awaited_method_call_of(self, path: ReceiverPath, name: str) -> ReceiverPath: + if path.steps: + return super().awaited_method_call_of(path, name) + return ReceiverPath(AwaitedCalledReferenceRoot(self.module_name, (*self.parts, name))) + + def awaited_call_of(self, path: ReceiverPath) -> ReceiverPath: + if path.steps: + return super().awaited_call_of(path) + return ReceiverPath(AwaitedCalledReferenceRoot(self.module_name, self.parts)) + def call_of(self, path: ReceiverPath, builder: ReceiverPathBuilder, arguments: Sequence[ast.expr], pending: Pending) -> ReceiverPath: if path.steps: return super().call_of(path, builder, arguments, pending) @@ -1608,6 +1762,17 @@ def declared(self, typing: DeclaredReceiverTyping) -> DeclaredType: return typing.called_reference(self.module_name, self.parts) +@dataclass(frozen=True) +class AwaitedCalledReferenceRoot(ReceiverRoot): + """An awaited call of a module-level async function or class method.""" + + module_name: str + parts: tuple[str, ...] + + def declared(self, typing: DeclaredReceiverTyping) -> DeclaredType: + return typing.awaited_called_reference(self.module_name, self.parts) + + @dataclass(frozen=True) class AgreeingRoot(ReceiverRoot): """A local bound more than once: the join of every binding's declared type.""" @@ -1723,6 +1888,14 @@ def applied(self, declared: DeclaredType, typing: DeclaredReceiverTyping) -> Dec return declared.called(typing, self.name) +@dataclass(frozen=True) +class AwaitCallStep(ReceiverStep): + name: str + + def applied(self, declared: DeclaredType, typing: DeclaredReceiverTyping) -> DeclaredType: + return declared.awaited_called(typing, self.name) + + @dataclass(frozen=True) class ElementStep(ReceiverStep): """Iterating the value: `for x in E` binds an element of E.""" @@ -1795,6 +1968,12 @@ def attribute(self, name: str) -> ReceiverPath: def method_call(self, name: str) -> ReceiverPath: return self.root.method_call_of(self, name) + def awaited_method_call(self, name: str) -> ReceiverPath: + return self.root.awaited_method_call_of(self, name) + + def awaited_call(self) -> ReceiverPath: + return self.root.awaited_call_of(self) + def call( self, builder: ReceiverPathBuilder, @@ -1952,6 +2131,10 @@ def _path(self, expression: ast.expr, pending: Pending) -> ReceiverPath: return self._path(value, pending).method_call(method) case ast.Call(func=func, args=arguments): return self._path(func, pending).call(self, arguments, pending) + case ast.Await(value=ast.Call(func=ast.Attribute(value=value, attr=method))): + return self._path(value, pending).awaited_method_call(method) + case ast.Await(value=ast.Call(func=func)): + return self._path(func, pending).awaited_call() case ast.Subscript(value=value, slice=key): base = self._path(value, pending) match key: diff --git a/nominal_refactor_advisor/probe_owner.py b/nominal_refactor_advisor/probe_owner.py index cc313934..dece2883 100644 --- a/nominal_refactor_advisor/probe_owner.py +++ b/nominal_refactor_advisor/probe_owner.py @@ -20,7 +20,10 @@ from nominal_refactor_advisor.ast_tools import ParsedModule, ParsedModuleFact from nominal_refactor_advisor.class_index import ( + CompactClassFamilyIndex, CompactIndexedClass, + CompactRepositoryPublicExposureIndex, + InstalledClassDeclarations, module_import_aliases, ) from nominal_refactor_advisor.declared_receivers import ( @@ -373,11 +376,139 @@ def owner(self, receiver: ast.expr) -> DeclaredPathProbeOwner: ) +_EMPTY_EXPOSURE_INDEX = CompactRepositoryPublicExposureIndex(()) +_PROTOCOL_BASES = frozenset(("typing.Protocol", "typing_extensions.Protocol")) + + +@dataclass +class MethodOwnerReceiverProof: + """Decides whether a receiver expression can dispatch to `reaching_symbols`, + using mypy first and falling back to declared/installed receiver types when + mypy degrades an unfollowed import to `Any`/`Unknown`/`object`.""" + + class_index: CompactClassFamilyIndex + declared_typing: DeclaredReceiverTyping + reaching_symbols: frozenset[str] + _ancestors: frozenset[str] | None = None + _scanned_modules: frozenset[str] | None = None + _nominal_cache: dict[str, bool] | None = None + + def _collect_installed_ancestors(self, seed_names: set[str], target: set[str]) -> None: + pending = [ + name + for name in seed_names + if name != "builtins.object" and name not in self.class_index.classes_by_symbol + ] + seen: set[str] = set(pending) + while pending: + current = pending.pop() + decl = InstalledClassDeclarations.declaration(current, _EMPTY_EXPOSURE_INDEX) + if decl is None: + continue + for ref in decl.base_references: + base_name = ref.qualified_name + if base_name == "builtins.object": + continue + target.add(base_name) + if base_name not in seen and base_name not in self.class_index.classes_by_symbol: + seen.add(base_name) + pending.append(base_name) + + def _reaching_ancestors(self) -> frozenset[str]: + if self._ancestors is None: + ancestors: set[str] = set(self.reaching_symbols) + authority = self.class_index.declared_mro_authority + for symbol in self.reaching_symbols: + mro = authority.resolve(symbol).mro_type + if mro is not None: + for decl in mro.declarations: + ancestors.add(decl.symbol) + ancestors.update(ref.qualified_name for ref in decl.base_references) + indexed = self.class_index.class_for(symbol) + if indexed is not None: + ancestors.update(ref.qualified_name for ref in indexed.base_references) + self._collect_installed_ancestors(set(ancestors), ancestors) + self._ancestors = frozenset(ancestors) + return self._ancestors + + def _is_nominal_class(self, qualified_name: str) -> bool: + if self._nominal_cache is None: + self._nominal_cache = {} + cached = self._nominal_cache.get(qualified_name) + if cached is not None: + return cached + if qualified_name in {"builtins.object", "typing.Any", "typing_extensions.Any"}: + result = False + elif qualified_name in self.class_index.classes_by_symbol: + ancestors: set[str] = set() + authority = self.class_index.declared_mro_authority + mro = authority.resolve(qualified_name).mro_type + if mro is not None: + for decl in mro.declarations: + ancestors.add(decl.symbol) + ancestors.update(ref.qualified_name for ref in decl.base_references) + indexed = self.class_index.class_for(qualified_name) + if indexed is not None: + ancestors.update(ref.qualified_name for ref in indexed.base_references) + self._collect_installed_ancestors(set(ancestors), ancestors) + result = not bool(ancestors & _PROTOCOL_BASES) + else: + if self._scanned_modules is None: + self._scanned_modules = frozenset( + decl.module_name for decl in self.class_index.classes_by_symbol.values() + ) + if qualified_name.rpartition(".")[0] in self._scanned_modules: + result = False + else: + result = InstalledClassDeclarations.is_nominal_non_protocol_class( + qualified_name, _EMPTY_EXPOSURE_INDEX + ) + self._nominal_cache[qualified_name] = result + return result + + def reaches( + self, + answer: ReceiverType | None, + parsed_module: ParsedModule, + receiver_expr: ast.expr, + *, + method_name: str, + line: int, + ) -> bool: + try: + if answer is None: + raise NeedsInput( + f"{parsed_module.file_path}:{line} accesses `.{method_name}` on an unproved receiver", + NeededInput.PROOF, + ) + return answer.reaches_method_owner( + self.reaching_symbols, + file_path=parsed_module.file_path, + line=line, + method_name=method_name, + ) + except NeedsInput: + declared = ( + ProbeOwnerResolver.of(parsed_module) + .builder.path_of(receiver_expr) + .declared(self.declared_typing) + ) + verdict = declared.reaches_method_owner( + self.reaching_symbols, + self._reaching_ancestors(), + self._is_nominal_class, + ) + if verdict is not None: + return verdict + raise + + __all__ = ( "DeclaredFamilyProbeOwner", "DeclaredPathProbeOwner", "FailedReceiverType", "InferredReceiverType", + "MethodOwnerReceiverProof", "ProbeOwner", "ProbeOwnerContext", "ProbeOwnerResolver", diff --git a/nominal_refactor_advisor/refactors/threaded_absence.py b/nominal_refactor_advisor/refactors/threaded_absence.py index d3fd091b..ecf23aba 100644 --- a/nominal_refactor_advisor/refactors/threaded_absence.py +++ b/nominal_refactor_advisor/refactors/threaded_absence.py @@ -50,7 +50,10 @@ ) from nominal_refactor_advisor.module_node_index import ModuleNodeIndex from nominal_refactor_advisor.needed_input import NeededInput, NeedsInput -from nominal_refactor_advisor.probe_owner import ReceiverSpan +from nominal_refactor_advisor.probe_owner import ( + MethodOwnerReceiverProof, + ReceiverSpan, +) from nominal_refactor_advisor.refactor_concepts import ThreadedAbsenceFamilyConcept from nominal_refactor_advisor.refactors.finding_recipes import ( FindingEvidenceActionKeysMixin, @@ -2535,7 +2538,7 @@ def _collect_closed_call_args( # Pass 1: collect definite hits and defer receiver-type queries for one batched mypy call. definite_hits: list[tuple[str, ast.Attribute, ast.Call | None]] = [] - deferred_checks: list[tuple[str, ast.Attribute, ast.Call | None, ReceiverSpan]] = [] + deferred_checks: list[tuple[ParsedModule, ast.Attribute, ast.Call | None, ReceiverSpan]] = [] for mod in snapshot.parsed_modules: if function.name not in mod.source: continue @@ -2588,7 +2591,7 @@ def _collect_closed_call_args( continue deferred_checks.append( ( - mod.file_path, + mod, node, parent_call, ReceiverSpan.of(mod.file_path, node.value), @@ -2602,21 +2605,21 @@ def _collect_closed_call_args( if deferred_checks else {} ) + receiver_proof = MethodOwnerReceiverProof( + snapshot.compact_class_index, + snapshot.declared_receiver_typing, + reaching_symbols, + ) all_hits = list(definite_hits) - for file_path, node, parent_call, span in deferred_checks: - answer = inferred_receivers.get(span) - if answer is None: - raise NeedsInput( - f"{file_path}:{node.lineno} accesses `.{function.name}` on an unproved receiver", - NeededInput.PROOF, - ) - if answer.reaches_method_owner( - reaching_symbols, - file_path=file_path, - line=node.lineno, + for mod, node, parent_call, span in deferred_checks: + if receiver_proof.reaches( + inferred_receivers.get(span), + mod, + node.value, method_name=function.name, + line=node.lineno, ): - all_hits.append((file_path, node, parent_call)) + all_hits.append((mod.file_path, node, parent_call)) for file_path, node, parent_call in all_hits: if parent_call is None: diff --git a/nominal_refactor_advisor/refactors/zero_one_tuple.py b/nominal_refactor_advisor/refactors/zero_one_tuple.py index 158e1c90..082a611b 100644 --- a/nominal_refactor_advisor/refactors/zero_one_tuple.py +++ b/nominal_refactor_advisor/refactors/zero_one_tuple.py @@ -47,7 +47,10 @@ from nominal_refactor_advisor.models import RefactorFinding, ZeroOneTupleMetrics from nominal_refactor_advisor.module_node_index import ModuleNodeIndex from nominal_refactor_advisor.needed_input import NeededInput, NeedsInput -from nominal_refactor_advisor.probe_owner import ReceiverSpan +from nominal_refactor_advisor.probe_owner import ( + MethodOwnerReceiverProof, + ReceiverSpan, +) from nominal_refactor_advisor.refactor_concepts import ZeroOneTupleFamilyConcept from nominal_refactor_advisor.refactors.constant_subtype_answer import ( _contains_super_call, @@ -1066,19 +1069,19 @@ def _collect_closed_consumers( if deferred_checks else {} ) + receiver_proof = MethodOwnerReceiverProof( + snapshot.compact_class_index, + snapshot.declared_receiver_typing, + reaching_symbols, + ) all_hits = list(definite_hits) for mod, node_index, node, parent_call, span in deferred_checks: - answer = inferred_receivers.get(span) - if answer is None: - raise NeedsInput( - f"{mod.file_path}:{node.lineno} accesses `.{function.name}` on an unproved receiver", - NeededInput.PROOF, - ) - if answer.reaches_method_owner( - reaching_symbols, - file_path=mod.file_path, - line=node.lineno, + if receiver_proof.reaches( + inferred_receivers.get(span), + mod, + node.value, method_name=function.name, + line=node.lineno, ): all_hits.append((mod, node_index, node, parent_call)) diff --git a/tests/test_declared_receivers.py b/tests/test_declared_receivers.py index 2b490641..c374023e 100644 --- a/tests/test_declared_receivers.py +++ b/tests/test_declared_receivers.py @@ -660,3 +660,113 @@ def test_declared_receiver_typing_expands_module_and_reexported_type_aliases( use_mod.module_name, "CyclicA", OUTSIDE_METHOD ) assert isinstance(cyclic, UndeclaredType) + + +def test_declared_receiver_typing_resolves_init_annotations_and_keeps_class_objects_separate( + tmp_path: Path, +) -> None: + """`self.: T` annotations in `__init__` resolve on instances (including + subclasses of open bases), stay off class objects, and reject conflicting annotations.""" + + pkg = tmp_path / "init_pkg" + pkg.mkdir() + (pkg / "__init__.py").write_text("") + (pkg / "models.py").write_text( + "from __future__ import annotations\n" + "from nonexistent_external_pkg import ExternalBase\n\n" + "class Base: pass\n" + "class Left(Base): pass\n" + "class Right(Base): pass\n\n" + "class Holder(ExternalBase):\n" + " def __init__(self, flag: bool) -> None:\n" + " self._choice: Left | Right = Left() if flag else Right()\n" + " if flag:\n" + " self._ambig: Left = Left()\n" + " else:\n" + " self._ambig: Right = Right()\n\n" + "def read_all(h: Holder, cls: type[Holder]):\n" + " a = h._choice\n" + " b = h._ambig\n" + " c = cls._choice\n" + " return a, b, c\n" + ) + modules = parse_python_modules(pkg) + projections = tuple( + CompactModuleClassProjectionFamily.collect_stub(module) for module in modules + ) + class_index = CompactClassFamilyIndexBuilder(projections).build() + typing = DeclaredReceiverTyping.from_projections(projections, class_index) + mod = next(m for m in modules if m.module_name == "init_pkg.models") + builder = ReceiverPathBuilder( + mod.module_name, + mod.module, + module_import_aliases(mod), + mod.syntax_index.parent_index, + ) + assigns = { + stmt.targets[0].id: stmt.value + for fn in mod.module.body + if isinstance(fn, ast.FunctionDef) and fn.name == "read_all" + for stmt in fn.body + if isinstance(stmt, ast.Assign) and isinstance(stmt.targets[0], ast.Name) + } + assert builder.path_of(assigns["a"]).declared(typing) == DeclaredInstance( + ("init_pkg.models.Left", "init_pkg.models.Right") + ) + assert isinstance(builder.path_of(assigns["b"]).declared(typing), UndeclaredType) + assert isinstance(builder.path_of(assigns["c"]).declared(typing), UndeclaredType) + + +def test_declared_receiver_typing_unwraps_awaited_async_calls_only( + tmp_path: Path, +) -> None: + """`await` unwraps `async def` methods and functions, and rejects non-async callables.""" + + pkg = tmp_path / "async_pkg" + pkg.mkdir() + (pkg / "__init__.py").write_text("") + (pkg / "service.py").write_text( + "from __future__ import annotations\n" + "from typing import Self\n\n" + "class Catalog:\n" + " @classmethod\n" + " async def read(cls) -> Self:\n" + " return cls()\n\n" + " def sync_read(self) -> Self:\n" + " return self\n\n" + "async def load_catalog() -> Catalog:\n" + " return Catalog()\n\n" + "def sync_catalog() -> Catalog:\n" + " return Catalog()\n\n" + "async def use(cat: Catalog):\n" + " a = await Catalog.read()\n" + " b = await load_catalog()\n" + " c = await cat.sync_read()\n" + " d = await sync_catalog()\n" + " return a, b, c, d\n" + ) + modules = parse_python_modules(pkg) + projections = tuple( + CompactModuleClassProjectionFamily.collect_stub(module) for module in modules + ) + class_index = CompactClassFamilyIndexBuilder(projections).build() + typing = DeclaredReceiverTyping.from_projections(projections, class_index) + mod = next(m for m in modules if m.module_name == "async_pkg.service") + builder = ReceiverPathBuilder( + mod.module_name, + mod.module, + module_import_aliases(mod), + mod.syntax_index.parent_index, + ) + assigns = { + stmt.targets[0].id: stmt.value + for fn in mod.module.body + if isinstance(fn, ast.AsyncFunctionDef) and fn.name == "use" + for stmt in fn.body + if isinstance(stmt, ast.Assign) and isinstance(stmt.targets[0], ast.Name) + } + expected = DeclaredInstance(("async_pkg.service.Catalog",)) + assert builder.path_of(assigns["a"]).declared(typing) == expected + assert builder.path_of(assigns["b"]).declared(typing) == expected + assert isinstance(builder.path_of(assigns["c"]).declared(typing), UndeclaredType) + assert isinstance(builder.path_of(assigns["d"]).declared(typing), UndeclaredType) diff --git a/tests/test_threaded_absence.py b/tests/test_threaded_absence.py index 0abe795f..9e5b5ce6 100644 --- a/tests/test_threaded_absence.py +++ b/tests/test_threaded_absence.py @@ -857,3 +857,85 @@ def test_threaded_absence_prefix_guarded_returning_void_ifexp_and_bool_probe( _, _, after_findings = _scan(tmp_path) assert after_findings == [] + + +def test_threaded_absence_declared_receiver_proof_clears_installed_non_protocol_and_blocks_protocol( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """When mypy degrades an unfollowed installed import to `Any`, `MethodOwnerReceiverProof` + proves non-reaching nominal installed classes (including `__init__`-annotated fields) + while refusing to dismiss an installed `Protocol` or scanned `Protocol`.""" + + ext_root = tmp_path / "ext_site" + ext_pkg = ext_root / "nra_ext_tok_mod" + ext_pkg.mkdir(parents=True) + (ext_pkg / "__init__.py").write_text("") + (ext_pkg / "tokens.py").write_text( + "from __future__ import annotations\n" + "from typing import Protocol\n\n" + "class ForeignToken:\n" + " def accepts(self, value: str) -> bool:\n" + " return bool(value)\n\n" + "class ForeignProto(Protocol):\n" + " def accepts(self, value: str) -> bool: ...\n" + ) + monkeypatch.syspath_prepend(str(ext_root)) + + scan_ok = tmp_path / "scan_ok" + _write( + scan_ok, + { + "app_ok/__init__.py": "", + "app_ok/gate.py": ( + "from __future__ import annotations\n" + "from nra_ext_tok_mod.tokens import ForeignToken\n\n" + "class LocalGate:\n" + " def accepts(self, tag: str | None) -> bool:\n" + " if tag is None:\n" + " return False\n" + " return tag == 'ok'\n\n" + "class Attachment:\n" + " def __init__(self, tok: ForeignToken) -> None:\n" + " self._tok: ForeignToken = tok\n\n" + " def check(self, text: str) -> bool:\n" + " return self._tok.accepts(text)\n\n" + "def call_local(gate: LocalGate, value: str | None) -> bool:\n" + " return gate.accepts(value)\n" + ), + }, + ) + _, snap_ok, findings_ok = _scan(scan_ok) + assert len(findings_ok) == 1 + eval_ok = ThreadedAbsenceDetector().evaluate_recipe_for_finding( + findings_ok[0], snap_ok + ) + assert eval_ok.needs == (NeededInput.OWNER_PICK,), eval_ok.reason + + # A foreign Protocol must stay blocked on PROOF (a nominal class can satisfy it structurally). + scan_proto = tmp_path / "scan_proto" + _write( + scan_proto, + { + "app_proto/__init__.py": "", + "app_proto/gate.py": ( + "from __future__ import annotations\n" + "from nra_ext_tok_mod.tokens import ForeignProto\n\n" + "class LocalGate:\n" + " def accepts(self, tag: str | None) -> bool:\n" + " if tag is None:\n" + " return False\n" + " return tag == 'ok'\n\n" + "def check_proto(proto: ForeignProto, text: str) -> bool:\n" + " return proto.accepts(text)\n\n" + "def call_local(gate: LocalGate, value: str | None) -> bool:\n" + " return gate.accepts(value)\n" + ), + }, + ) + _, snap_proto, findings_proto = _scan(scan_proto) + assert len(findings_proto) == 1 + eval_proto = ThreadedAbsenceDetector().evaluate_recipe_for_finding( + findings_proto[0], snap_proto + ) + assert NeededInput.PROOF in eval_proto.needs, eval_proto.reason diff --git a/tests/test_zero_one_tuple.py b/tests/test_zero_one_tuple.py index 3b0fa53b..1f85dcd5 100644 --- a/tests/test_zero_one_tuple.py +++ b/tests/test_zero_one_tuple.py @@ -388,3 +388,89 @@ def test_zero_one_tuple_overriding_hierarchy_across_modules_and_abstract_base( with ScanCache.scope(): _mods_after, _snap_after, findings_after = _scan(tmp_path) assert findings_after == [] + + +def test_zero_one_tuple_resolves_installed_family_member_returning_type_self( + tmp_path: Path, + monkeypatch, +): + """When an installed base class declares `member_named(cls, name) -> type[Self]`, + `DeclaredReceiverTyping` resolves `Self` through the installed module's import aliases + so `zero_one_tuple` proves the call site reaches the scanned tag hierarchy.""" + + ext_root = tmp_path / "ext_fam" + ext_pkg = ext_root / "nra_ext_fam_mod" + ext_pkg.mkdir(parents=True) + (ext_pkg / "__init__.py").write_text("", encoding="utf-8") + (ext_pkg / "family.py").write_text( + "from __future__ import annotations\n" + "from typing import Self\n\n" + "class ExtFamily:\n" + " @classmethod\n" + " def member_named(cls, name: str) -> type[Self]:\n" + " for sub in cls.__subclasses__():\n" + " if sub.__name__ == name:\n" + " return sub\n" + " raise KeyError(name)\n", + encoding="utf-8", + ) + monkeypatch.syspath_prepend(str(ext_root)) + + scan_root = tmp_path / "scan_fam" + pkg = scan_root / "tags_pkg" + pkg.mkdir(parents=True) + (pkg / "__init__.py").write_text("", encoding="utf-8") + (pkg / "tags.py").write_text( + "from __future__ import annotations\n" + "from nra_ext_fam_mod.family import ExtFamily\n\n" + "class BaseTag(ExtFamily):\n" + " @classmethod\n" + " def decode_block(cls, text: str) -> tuple[str, ...]:\n" + " return ()\n\n" + "class NoteTag(BaseTag):\n" + " @classmethod\n" + " def decode_block(cls, text: str) -> tuple[str, ...]:\n" + " if not text:\n" + " return ()\n" + " return (text,)\n\n" + "def decode_all(kind: str, text: str) -> list[str]:\n" + " tag_member = BaseTag.member_named(kind)\n" + " return [item for item in tag_member.decode_block(text)]\n", + encoding="utf-8", + ) + + before_mod = _import_fresh(scan_root, "tags_pkg.tags") + assert before_mod.decode_all("NoteTag", "hello") == ["hello"] + assert before_mod.decode_all("NoteTag", "") == [] + + with ScanCache.scope(): + _mods, snap, findings = _scan(scan_root) + assert len(findings) == 1 + picks = OwnerPicks( + "picks.json", + "", + ( + OwnerPick( + finding=findings[0].stable_id, + owner="NoteTag.decode_block", + because="decoded block presence belongs on a nominal family", + name="DecodedTagBlock", + judgement="Present or absent decoded tag block.", + ), + ), + ) + picked, report = picks.applied(findings) + assert not report.unmatched + plan = codemod_plan_from_findings(picked, selector_context=snap) + assert plan.candidate_count == 1, plan.report + sim = plan.document.simulate(snap) + assert sim.is_clean, sim.preflight_report + sim.apply() + + after_mod = _import_fresh(scan_root, "tags_pkg.tags") + assert after_mod.decode_all("NoteTag", "hello") == ["hello"] + assert after_mod.decode_all("NoteTag", "") == [] + + with ScanCache.scope(): + _, _, findings_after = _scan(scan_root) + assert findings_after == []