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
160 changes: 160 additions & 0 deletions nominal_refactor_advisor/class_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -1422,6 +1422,8 @@ def own_dataclass_field_names(self) -> tuple[str, ...] | None:
callable_member_declarations: tuple[CompactCallableMemberDeclaration, ...] = ()
init_attribute_annotations: tuple[tuple[str, str], ...] = ()
"""Unambiguous `self.<attr>: T` annotations declared directly inside `__init__`."""
init_attribute_calls: tuple[tuple[str, tuple[str, ...]], ...] = ()
"""Unambiguous `self.<attr> = SomeClass(...)` assignments 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, ...] = ()
Expand Down Expand Up @@ -1821,6 +1823,7 @@ class CompactModuleClassHeader(CompactModuleIdentity):
star_import_origins: tuple[CompactModuleStarImportOrigin, ...]
classes: tuple[CompactIndexedClass, ...]
field_declaration_wrappers: tuple[CompactFieldDeclarationWrapper, ...] = ()
type_checking_import_aliases: tuple[tuple[str, str], ...] = ()

@cached_property
def has_unsettled_field_declarations(self) -> bool:
Expand Down Expand Up @@ -1871,6 +1874,9 @@ def declared_in(
field_declaration_wrappers=module_field_declaration_wrappers(
parsed_module, binding_snapshots[None]
),
type_checking_import_aliases=tuple(
sorted(_module_type_checking_import_aliases(parsed_module).items())
),
)

ClassProjectionT = TypeVar("ClassProjectionT", bound=CompactModuleClassHeader)
Expand Down Expand Up @@ -5105,6 +5111,37 @@ def module_import_aliases(parsed_module: ParsedModule) -> dict[str, str]:
}


def _module_type_checking_import_aliases(parsed_module: ParsedModule) -> dict[str, str]:
"""Import aliases declared inside `if TYPE_CHECKING:` blocks, for annotation resolution."""

runtime_aliases = module_import_aliases(parsed_module)
aliases: dict[str, str] = {}
for statement in ModuleImportScope.TYPE_CHECKING.import_statements(
parsed_module.module
):
match statement:
case ast.Import(names=names):
for alias in names:
local_name = alias.asname or alias.name.partition(".")[0]
target = alias.name if alias.asname else local_name
if local_name not in runtime_aliases:
aliases[local_name] = target
case ast.ImportFrom(module=module, level=level, names=names):
resolved = parsed_module.module_path_identity.resolve_import_from_module(
imported_module=module,
level=level,
)
if resolved is None:
continue
for alias in names:
if alias.name == "*":
continue
local_name = alias.asname or alias.name
if local_name not in runtime_aliases:
aliases[local_name] = f"{resolved}.{alias.name}"
return aliases


def module_import_names(parsed_module: ParsedModule) -> frozenset[str]:
"""Names the module's final bindings resolve to an imported module."""

Expand Down Expand Up @@ -5571,6 +5608,7 @@ def _compact_indexed_classes(
node, binding_snapshots[node.lineno]
),
init_attribute_annotations=_compact_init_attribute_annotations(node),
init_attribute_calls=_compact_init_attribute_calls(node),
abstract_method_names=sorted_tuple(
statement.name
for statement in FunctionDefinition.within(node.body)
Expand Down Expand Up @@ -6088,6 +6126,7 @@ def collect_stub(
star_import_origins=declarations.star_import_origins,
classes=declarations.classes,
field_declaration_wrappers=declarations.field_declaration_wrappers,
type_checking_import_aliases=declarations.type_checking_import_aliases,
top_level_definitions=tuple(
(node.name, node.lineno)
for node in parsed_module.module.body
Expand Down Expand Up @@ -7832,6 +7871,127 @@ def walk(statements: Sequence[ast.stmt]) -> None:
)


def _dotted_name_parts(expr: ast.expr) -> tuple[str, ...]:
match expr:
case ast.Name(id=name):
return (name,)
case ast.Attribute(value=value, attr=attr):
prefix = _dotted_name_parts(value)
return (*prefix, attr) if prefix else ()
return ()


def _compact_init_attribute_calls(
node: ast.ClassDef,
) -> tuple[tuple[str, tuple[str, ...]], ...]:
"""Unambiguous `self.<attr> = SomeClass(...)` assignments inside `__init__`,
excluding any attribute also annotated, reassigned to another expression, or
calling a local parameter/variable shadowing a module symbol."""

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
init_locals: set[str] = {
arg.arg
for arg in (*positional, *init_def.args.kwonlyargs)
}
if init_def.args.vararg is not None:
init_locals.add(init_def.args.vararg.arg)
if init_def.args.kwarg is not None:
init_locals.add(init_def.args.kwarg.arg)

def collect_locals(statements: Sequence[ast.stmt]) -> None:
for stmt in statements:
match stmt:
case ast.FunctionDef(name=name) | ast.AsyncFunctionDef(name=name) | ast.ClassDef(name=name):
init_locals.add(name)
continue
case ast.Import(names=names) | ast.ImportFrom(names=names):
for alias in names:
if alias.name != "*":
init_locals.add(alias.asname or alias.name.partition(".")[0])
continue
case _:
for child in ast.iter_child_nodes(stmt):
match child:
case ast.Name(id=name, ctx=ast.Store()):
init_locals.add(name)
case ast.stmt():
collect_locals((child,))
case ast.ExceptHandler(name=str() as handler_name, body=body):
init_locals.add(handler_name)
collect_locals(body)
case ast.ExceptHandler(body=body):
collect_locals(body)
case ast.match_case(body=body):
collect_locals(body)

collect_locals(init_def.body)

calls: dict[str, tuple[str, ...]] = {}
ambiguous: set[str] = set()

def walk(statements: Sequence[ast.stmt]) -> None:
for stmt in statements:
match stmt:
case ast.Assign(targets=targets, value=value):
callee_parts = (
_dotted_name_parts(value.func)
if isinstance(value, ast.Call)
else ()
)
for target in targets:
match target:
case ast.Attribute(value=ast.Name(id=receiver), attr=attr) if receiver == self_name:
if callee_parts and callee_parts[0] not in init_locals:
previous = calls.get(attr)
if previous is not None and previous != callee_parts:
ambiguous.add(attr)
else:
calls[attr] = callee_parts
else:
ambiguous.add(attr)
case ast.AnnAssign(
target=ast.Attribute(value=ast.Name(id=receiver), attr=attr)
) if receiver == self_name:
ambiguous.add(attr)
case ast.AugAssign(
target=ast.Attribute(value=ast.Name(id=receiver), attr=attr)
) if receiver == self_name:
ambiguous.add(attr)
case ast.Delete(targets=targets):
for target in targets:
match target:
case ast.Attribute(value=ast.Name(id=receiver), attr=attr) if receiver == self_name:
ambiguous.add(attr)
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, parts)
for name, parts in calls.items()
if name not in ambiguous
)


def _redefines_property(
statement: ast.FunctionDef | ast.AsyncFunctionDef, property_names: Collection[str]
) -> bool:
Expand Down
68 changes: 60 additions & 8 deletions nominal_refactor_advisor/declared_receivers.py
Original file line number Diff line number Diff line change
Expand Up @@ -823,6 +823,9 @@ class DeclaredReceiverTyping:
type_variables_by_module: Mapping[str, tuple[str, ...]]
declarations: StubDeclarations
type_aliases_by_module: Mapping[str, Mapping[str, str]] = field(default_factory=dict)
annotation_aliases_by_module: Mapping[str, Mapping[str, str]] = field(
default_factory=dict
)

@classmethod
def from_projections(
Expand Down Expand Up @@ -880,6 +883,13 @@ def declared_over(
for projection in projections
if projection.type_aliases
},
annotation_aliases_by_module={
projection.module_name: {
**dict(projection.type_checking_import_aliases),
**dict(projection.import_aliases),
}
for projection in projections
},
)

# members and calls ---------------------------------------------------
Expand Down Expand Up @@ -1053,7 +1063,11 @@ def bound(self, qualified: str) -> ScannedClassLookup:
if qualified in self.class_index.classes_by_symbol:
return ScannedClass(qualified)
owner, _, name = qualified.rpartition(".")
following = self.aliases_by_module.get(owner, {}).get(name, qualified)
following = self.aliases_by_module.get(owner, {}).get(name)
if following is None:
following = self.annotation_aliases_by_module.get(owner, {}).get(
name, qualified
)
if following == qualified:
break
qualified = following
Expand Down Expand Up @@ -1164,11 +1178,14 @@ def awaited_called_reference(
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."""

def _qualified_in(
self,
module_name: str,
parts: tuple[str, ...],
aliases_map: Mapping[str, Mapping[str, str]],
) -> str:
head, *rest = parts
aliases = self.aliases_by_module.get(module_name)
aliases = aliases_map.get(module_name)
if aliases is None:
aliases = (
InstalledClassDeclarations.import_aliases_map(module_name)
Expand All @@ -1183,6 +1200,34 @@ def qualified(self, module_name: str, parts: tuple[str, ...]) -> str:
return ".".join((module_name, *parts))
return ".".join(("builtins", *parts))

def qualified(self, module_name: str, parts: tuple[str, ...]) -> str:
"""The qualified name a module-level name chain spells at runtime."""

return self._qualified_in(module_name, parts, self.aliases_by_module)

def annotation_qualified(self, module_name: str, parts: tuple[str, ...]) -> str:
"""The qualified name a module-level annotation spells, including `if TYPE_CHECKING:` imports."""

return self._qualified_in(
module_name,
parts,
self.annotation_aliases_by_module or self.aliases_by_module,
)

def annotation_class_symbol(
self, module_name: str, parts: tuple[str, ...]
) -> ScannedClassLookup:
"""The scanned or stub class an annotation name chain names, including `if TYPE_CHECKING:` imports."""

match self.resolver.symbol_for(
module_name=module_name,
reference_parts=parts,
allow_unique_unqualified=False,
):
case str() as symbol:
return ScannedClass(symbol)
return self.chased(self.annotation_qualified(module_name, parts))

@cached_property
def scanned_roots(self) -> frozenset[str]:
return frozenset(module.partition(".")[0] for module in self.aliases_by_module)
Expand Down Expand Up @@ -1225,14 +1270,16 @@ def named_type(
parts = _reference_parts(annotation)
if not parts:
return UndeclaredType(f"annotation `{ast.unparse(annotation)}` names no type")
qualified = self.qualified(module_name, parts)
qualified = self.annotation_qualified(module_name, parts)
if qualified in scope.parameters:
return scope.parameters[qualified]
if qualified in SELF_SPELLINGS:
return scope.self_type
if qualified in ANY_SPELLINGS:
return UndeclaredType("`Any` declares no type")
return self.class_symbol(module_name, parts).annotation_instance(self, scope)
return self.annotation_class_symbol(module_name, parts).annotation_instance(
self, scope
)

def subscripted_type(
self,
Expand All @@ -1247,7 +1294,9 @@ def subscripted_type(
return UndeclaredType(f"annotation `{ast.unparse(head)}[...]` names no type")
typed = [self.annotation_type(module_name, item, scope) for item in items]
assert isinstance(head, ast.Name | ast.Attribute)
return AnnotationHead.spelled_as(self.qualified(module_name, parts)).declared(
return AnnotationHead.spelled_as(
self.annotation_qualified(module_name, parts)
).declared(
items, typed, self, lambda: self.named_type(module_name, head, scope)
)

Expand Down Expand Up @@ -1578,6 +1627,9 @@ def _from_init(self) -> DeclaredType | None:
return self.typing.annotation_source_type(
owner.module_name, source, self.scope(owner)
)
for attr_name, callee_parts in owner.init_attribute_calls:
if attr_name == self.name:
return self.typing.called_reference(owner.module_name, callee_parts)
return None

def missing(self) -> DeclaredType:
Expand Down
Loading
Loading