diff --git a/nominal_refactor_advisor/class_creation_store.py b/nominal_refactor_advisor/class_creation_store.py index 1b80e85f..5ab7a857 100644 --- a/nominal_refactor_advisor/class_creation_store.py +++ b/nominal_refactor_advisor/class_creation_store.py @@ -36,12 +36,16 @@ FunctionNode: TypeAlias = ast.FunctionDef | ast.AsyncFunctionDef +ABC_META = "abc.ABCMeta" +ABSTRACT_HOOKS_META = "metaclass_registry.abstract_hooks.AbstractHooksMeta" +AUTO_REGISTER_META = "metaclass_registry.core.AutoRegisterMeta" + MODELLED_METACLASSES = frozenset( ( "builtins.type", - "abc.ABCMeta", - "metaclass_registry.abstract_hooks.AbstractHooksMeta", - "metaclass_registry.core.AutoRegisterMeta", + ABC_META, + ABSTRACT_HOOKS_META, + AUTO_REGISTER_META, ) ) """Metaclasses whose class creation NRA knows without reading it: they keep the @@ -64,8 +68,6 @@ ) """The names a modelled metaclass reads from a class being created.""" -AUTO_REGISTER_META = "metaclass_registry.core.AutoRegisterMeta" - def _functions(statements: list[ast.stmt]) -> dict[str, FunctionNode]: return { diff --git a/nominal_refactor_advisor/refactors/class_creation.py b/nominal_refactor_advisor/refactors/class_creation.py index fe8e0742..d74fe64c 100644 --- a/nominal_refactor_advisor/refactors/class_creation.py +++ b/nominal_refactor_advisor/refactors/class_creation.py @@ -44,7 +44,12 @@ CompactIndexedClass, CompactUnannotatedCallable, ) -from nominal_refactor_advisor.class_creation_store import MODELLED_METACLASSES, REGISTRY_NAMES +from nominal_refactor_advisor.class_creation_store import ( + ABC_META, + ABSTRACT_HOOKS_META, + MODELLED_METACLASSES, + REGISTRY_NAMES, +) from nominal_refactor_advisor.class_mro import native_root_type from nominal_refactor_advisor.codemod_runtime import CodemodSourceSnapshot from nominal_refactor_advisor.codemod_selection_context import ResolvedClassTarget @@ -1073,17 +1078,24 @@ def metaclass_code(self, symbol: str) -> Iterator[CreationCode]: for indexed in self.metaclass_ancestry(symbol): yield from self.methods(indexed, hooks) - def metaclass_ancestry(self, symbol: str) -> Iterator[CompactIndexedClass]: - """The classes along a metaclass's ancestry, the scan's or an installed - module's source; a modelled metaclass ends its branch, and one NRA cannot - read refuses.""" + def _walk_metaclasses( + self, roots: Iterable[str] + ) -> tuple[tuple[CompactIndexedClass, ...], frozenset[str]]: + """Walk metaclass ancestries from `roots`, returning `(classes, models)` where + `classes` are the non-modelled metaclasses (scanned or installed) and `models` + are the `MODELLED_METACLASSES` reached.""" - pending, seen = [symbol], set() + classes: list[CompactIndexedClass] = [] + models: set[str] = set() + pending, seen = list(roots), set() while pending: current = self.canonical(pending.pop()) - if current in seen or current in MODELLED_METACLASSES: + if current in seen: continue seen.add(current) + if current in MODELLED_METACLASSES: + models.add(current) + continue indexed = self.snapshot.class_overlap_verdicts.ancestor(current) if indexed is None: raise NeedsInput( @@ -1091,8 +1103,28 @@ def metaclass_ancestry(self, symbol: str) -> Iterator[CompactIndexedClass]: "and is none of its creation models: NRA needs a proof of what it reads", NeededInput.PROOF, ) - yield indexed + classes.append(indexed) pending.extend(".".join(reference.resolved_parts) for reference in indexed.base_references) + return tuple(classes), frozenset(models) + + def metaclass_ancestry(self, symbol: str) -> Iterator[CompactIndexedClass]: + """The classes along a metaclass's ancestry, the scan's or an installed + module's source; a modelled metaclass ends its branch, and one NRA cannot + read refuses.""" + + yield from self._walk_metaclasses((symbol,))[0] + + def collects_mro_abstract_methods(self) -> bool: + """Whether class creation populates `__abstractmethods__` by walking `vars(base)` + across every class in `cls.__mro__` (plain bases included). + + `AbstractHooksMeta.__init__` reads `vars(base)` across `cls.__mro__`, so moving an + `@abstractmethod` onto any composed base preserves `__abstractmethods__` without + requiring that base to inherit `ABC`. When `ABCMeta` is also present, only bases + whose own metaclass populates `__abstractmethods__` qualify.""" + + _, models = self._walk_metaclasses(self.metaclasses()) + return ABSTRACT_HOOKS_META in models and ABC_META not in models @staticmethod def modelled_hooks() -> frozenset[str]: diff --git a/nominal_refactor_advisor/refactors/class_overlap.py b/nominal_refactor_advisor/refactors/class_overlap.py index d7566815..e0f28c73 100644 --- a/nominal_refactor_advisor/refactors/class_overlap.py +++ b/nominal_refactor_advisor/refactors/class_overlap.py @@ -35,6 +35,7 @@ ClassCreationProof, MroWalk, declared_names, + installed_class_node, ) from nominal_refactor_advisor.refactors.class_member_authority import ( ClassMemberMoveProofContext, @@ -61,6 +62,7 @@ NativeMroBase, namespace_read_native, native_declared_names, + native_root_type, ) from nominal_refactor_advisor.field_order_reads import DeclaringClass from nominal_refactor_advisor.class_overlap import ( @@ -717,22 +719,156 @@ def undocumented( indentation = rendered[start][: len(rendered[start]) - len(rendered[start].lstrip())] return "".join((*rendered[:start], *(() if rest else (f"{indentation}...\n",)), *rendered[end:])) + _NO_SET_NAME_BASES: ClassVar[frozenset[str]] = frozenset( + ( + "typing.NamedTuple", + "builtins.object", + "builtins.tuple", + "builtins.int", + "builtins.float", + "builtins.str", + "builtins.bytes", + "builtins.frozenset", + "builtins.bool", + ) + ) + + @staticmethod + def _class_ast_node(snapshot: CodemodSourceSnapshot, indexed: CompactIndexedClass) -> ast.ClassDef: + if snapshot.class_overlap_verdicts.class_index.class_for(indexed.symbol) is None: + return installed_class_node(indexed) + return ResolvedClassTarget.from_rewrite_target( + snapshot, + SourceRewriteTarget(file_path=indexed.file_path, qualname=indexed.qualname), + ).node + + @staticmethod + def _own_returns(function: ast.FunctionDef) -> list[ast.Return]: + """Collect `ast.Return` nodes belonging to `function`'s own scope (skipping nested defs/classes/lambdas).""" + returns: list[ast.Return] = [] + pending: list[ast.AST] = list(function.body) + while pending: + current = pending.pop() + if isinstance(current, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda)): + continue + if isinstance(current, ast.Return): + returns.append(current) + pending.extend(ast.iter_child_nodes(current)) + return returns + + @classmethod + def _is_self_constructing_classmethod( + cls, snapshot: CodemodSourceSnapshot, owner: CompactIndexedClass, method_name: str + ) -> bool: + """Whether `owner.method_name` is a `@classmethod` whose every return in its own + scope constructs and returns `cls(...)` without rebinding `cls`.""" + class_def = cls._class_ast_node(snapshot, owner) + method = next( + ( + stmt + for stmt in class_def.body + if isinstance(stmt, ast.FunctionDef) and stmt.name == method_name + ), + None, + ) + if method is None: + return False + if not any( + isinstance(dec, ast.Name) and dec.id == "classmethod" + for dec in method.decorator_list + ): + return False + params = (*method.args.posonlyargs, *method.args.args) + if not params: + return False + cls_param = params[0].arg + # Refuse if `cls_param` is rebound anywhere in the method body. + for node in ast.walk(method): + if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store) and node.id == cls_param: + return False + returns = cls._own_returns(method) + if not returns: + return False + return all( + isinstance(ret.value, ast.Call) + and isinstance(ret.value.func, ast.Name) + and ret.value.func.id == cls_param + for ret in returns + ) + + @classmethod + def _constructed_class_symbol( + cls, + snapshot: CodemodSourceSnapshot, + resolver, + callee: ast.AST, + ) -> str | None: + """Resolve the class symbol whose instance `callee(...)` constructs: either a direct + scanned/installed class call or a `@classmethod` constructor returning `cls(...)`.""" + verdicts = snapshot.class_overlap_verdicts + direct = resolver.symbol_for_node(callee) or resolver.imported_name_for_node(callee) + if direct is not None and ( + verdicts.ancestor(direct) is not None or native_root_type(direct) is not None + ): + return direct + if isinstance(callee, ast.Attribute): + owner_symbol = resolver.symbol_for_node(callee.value) or resolver.imported_name_for_node(callee.value) + if owner_symbol is not None: + owner = verdicts.ancestor(owner_symbol) + if owner is not None and cls._is_self_constructing_classmethod(snapshot, owner, callee.attr): + return owner.symbol + return None + + @classmethod + def _require_class_has_no_set_name(cls, snapshot: CodemodSourceSnapshot, symbol: str) -> None: + """Prove `symbol` and every ancestor in its closed MRO declare no `__set_name__`.""" + verdicts = snapshot.class_overlap_verdicts + pending = [symbol] + seen: set[str] = set() + while pending: + current = pending.pop() + if current in seen: + continue + seen.add(current) + if current in cls._NO_SET_NAME_BASES: + continue + native = native_root_type(current) + if native is not None: + if hasattr(native, "__set_name__"): + raise NeedsInput( + f"`{symbol}` learns its owner class through `__set_name__`", NeededInput.PROOF + ) + continue + indexed = verdicts.ancestor(current) + if indexed is None or not indexed.base_references_are_complete: + raise NeedsInput(f"`{symbol}` has an open MRO", NeededInput.PROOF) + if not indexed.class_decorators_are_promotion_safe: + raise NeedsInput(f"`{symbol}` has a class decorator NRA cannot prove free of `__set_name__`", NeededInput.PROOF) + if any( + declaration.name == "__set_name__" + for declaration in indexed.body_declarations + ): + raise NeedsInput( + f"`{symbol}` learns its owner class through `__set_name__`", NeededInput.PROOF + ) + for ref in indexed.base_references: + pending.append(ref.qualified_name) + def require_no_owner_bound_values(self, snapshot: CodemodSourceSnapshot) -> None: """A value built by a class with `__set_name__` learns the class it sits in. Moving it changes which class that hook receives, so a moved value that - calls anything is admitted only when the callee is a class whose whole - C3 order is indexed and none of those classes declares the hook. The one - other callee admitted is `dataclasses.field`: the dataclass decorator - consumes its `Field`, whose own `__set_name__` only forwards to its - `default`, and a default that calls anything is a call this walk checks. + calls anything is admitted only when the callee constructs a class (directly + or via a `@classmethod` returning `cls(...)`) whose whole ancestor graph is + closed (scanned, installed, or known builtin/NamedTuple base) and declares no + `__set_name__`. `dataclasses.field` is also admitted: the dataclass decorator + consumes its `Field`, whose own `__set_name__` only forwards to its `default`, + and a default that calls anything is a call this walk checks. """ - class_index = snapshot.class_overlap_verdicts.class_index resolver = snapshot.class_reference_resolver_for_source_path( self.restating.file_path ).reference_resolution - mro_authority = class_index.mro_authority for statement in self.statements: value = getattr(statement, "value", None) for call in () if value is None else ast.walk(value): @@ -745,23 +881,13 @@ def require_no_owner_bound_values(self, snapshot: CodemodSourceSnapshot) -> None resolver.imported_name_for_node(callee) ): continue - symbol = resolver.symbol_for_node(callee) - if symbol is None or class_index.class_for(symbol) is None: + symbol = self._constructed_class_symbol(snapshot, resolver, callee) + if symbol is None: raise NeedsInput( f"`{ast.unparse(call.func)}` builds a moved value; " "its callee is no indexed class", NeededInput.PROOF ) - mro_type = mro_authority.resolve(symbol).mro_type - if mro_type is None: - raise NeedsInput(f"`{symbol}` has an open MRO", NeededInput.PROOF) - if any( - declaration.name == "__set_name__" - for owner in mro_type.declarations - for declaration in owner.body_declarations - ): - raise NeedsInput( - f"`{symbol}` learns its owner class through `__set_name__`", NeededInput.PROOF - ) + self._require_class_has_no_set_name(snapshot, symbol) @dataclass(frozen=True) @@ -1584,10 +1710,14 @@ def creation(self) -> ClassCreationProof: tuple((owner.qualname, owner.node) for owner in self.owners), MroWalk(self.before, self.after, self.composer.symbol, self.deleted), ) - abstract_owners = tuple( - owner - for owner in self.owners - if NativeMroBase.ABSTRACT_ROOT.value in self.c3.linearized(owner.symbol) + abstract_owners = ( + self.owners + if proof.collects_mro_abstract_methods() + else tuple( + owner + for owner in self.owners + if NativeMroBase.ABSTRACT_ROOT.value in self.c3.linearized(owner.symbol) + ) ) kept = frozenset( name for owner in abstract_owners for name in self.names(owner.symbol, composed=False) diff --git a/tests/test_installed_creation_hooks.py b/tests/test_installed_creation_hooks.py index 3a4209bb..1719bb83 100644 --- a/tests/test_installed_creation_hooks.py +++ b/tests/test_installed_creation_hooks.py @@ -17,6 +17,7 @@ from nominal_refactor_advisor.class_index import InstalledClassDeclarations from nominal_refactor_advisor.codemod import CodemodPlanSequence, CodemodSourceSnapshot from nominal_refactor_advisor.detectors._base import DetectorConfig +from nominal_refactor_advisor.detectors._class_overlap import DuplicateClassDetector from nominal_refactor_advisor.detectors._restated_bases import RestatedBaseDetector from nominal_refactor_advisor.detectors._restated_overrides import RestatedOverrideDetector from nominal_refactor_advisor.installed_source import InstalledModule @@ -647,3 +648,130 @@ def test_member_deletion_proves_textual_pump_meta_dispatch_scope_and_actions_and compute_eval, _ = _evaluation(RestatedOverrideDetector(), scan, "LeafPane") assert "dir()" in compute_eval.rejection_reason assert NeededInput.PROOF in compute_eval.needs + + +def test_abstract_hooks_meta_composes_plain_abstract_contract_while_abcmeta_refuses( + tmp_path: Path, +) -> None: + """AbstractHooksMeta walks vars(base) across cls.__mro__, so moving an @abstractmethod + onto a plain-type composed base preserves __abstractmethods__; ABCMeta only reads + base.__abstractmethods__ and must still refuse.""" + + scan = tmp_path / "scan" + hooks_source = ( + "from abc import abstractmethod\n" + "from metaclass_registry.abstract_hooks import AbstractHooksMeta\n\n\n" + "class HooksBase(metaclass=AbstractHooksMeta):\n" + " pass\n\n\n" + "class SubmitsContract:\n" + " @abstractmethod\n" + " def submit(self) -> None:\n" + " ...\n\n\n" + "class HooksPane(HooksBase):\n" + " @abstractmethod\n" + " def submit(self) -> None:\n" + " ...\n" + ) + hooks_main = ( + "from app.panes import HooksPane\n" + "print(sorted(HooksPane.__abstractmethods__))\n" + ) + _write(scan, {"app/__init__.py": "", "app/panes.py": hooks_source, "main.py": hooks_main}) + expected = subprocess.check_output([sys.executable, "main.py"], cwd=scan, text=True) + + hooks_eval, snapshot = _evaluation(DuplicateClassDetector(), scan, "SubmitsContract") + assert hooks_eval.rejection_reason == "" + _apply(hooks_eval, snapshot) + assert "class HooksPane(SubmitsContract, HooksBase):" in (scan / "app/panes.py").read_text() + assert subprocess.check_output([sys.executable, "main.py"], cwd=scan, text=True) == expected + + # ABCMeta only reads base.__abstractmethods__ and must still refuse a plain-type abstract base. + abc_source = ( + "from abc import ABC, abstractmethod\n\n\n" + "class SubmitsContract:\n" + " @abstractmethod\n" + " def submit(self) -> None:\n" + " ...\n\n\n" + "class AbcPane(ABC):\n" + " pane_only = 1\n" + " @abstractmethod\n" + " def submit(self) -> None:\n" + " ...\n" + ) + _write(scan, {"app/panes.py": abc_source}) + abc_eval, _ = _evaluation(DuplicateClassDetector(), scan, "SubmitsContract") + assert "would take abstract ['submit']" in abc_eval.rejection_reason + assert NeededInput.PROOF in abc_eval.needs + + +def test_moved_class_value_proves_installed_namedtuple_classmethod_and_refuses_set_name( + tmp_path: Path, monkeypatch +) -> None: + """RestatedDeclarations.require_no_owner_bound_values admits installed NamedTuple + @classmethod constructors returning cls(...) and refuses classes declaring __set_name__.""" + + site = tmp_path / "site" + scan = tmp_path / "scan" + monkeypatch.syspath_prepend(str(site)) + + installed_source = ( + "from typing import NamedTuple\n\n\n" + "class Scalar(NamedTuple):\n" + " value: float\n\n" + " @classmethod\n" + " def from_number(cls, value: float) -> 'Scalar':\n" + " return cls(float(value))\n\n\n" + "class OwnerBound:\n" + " def __init__(self, value: int) -> None:\n" + " self.value = value\n\n" + " def __set_name__(self, owner: type, name: str) -> None:\n" + " self.owner = owner\n\n" + " @classmethod\n" + " def from_number(cls, value: int) -> 'OwnerBound':\n" + " return cls(value)\n" + ) + app_source = ( + "from unit_toolkit.units import Scalar\n\n\n" + "class FixedSize:\n" + " width = Scalar.from_number(1)\n" + " height = Scalar.from_number(2)\n\n\n" + "class SizedWidget:\n" + " width = Scalar.from_number(1)\n" + " height = Scalar.from_number(2)\n" + " label = 'ok'\n" + ) + main_source = ( + "from app.widgets import FixedSize, SizedWidget\n" + "print(FixedSize.width, FixedSize.height, SizedWidget.width, SizedWidget.height, SizedWidget.label)\n" + ) + _write(site, {"unit_toolkit/__init__.py": "", "unit_toolkit/units.py": installed_source}) + _write(scan, {"app/__init__.py": "", "app/widgets.py": app_source, "main.py": main_source}) + expected = _run(site, scan) + + try: + scalar_eval, snapshot = _evaluation(DuplicateClassDetector(), scan, "FixedSize") + assert scalar_eval.rejection_reason == "" + _apply(scalar_eval, snapshot) + assert "class SizedWidget(FixedSize):" in (scan / "app/widgets.py").read_text() + assert _run(site, scan) == expected + + # OwnerBound declares __set_name__: moving its @classmethod call must be refused. + bound_source = ( + "from unit_toolkit.units import OwnerBound\n\n\n" + "class FixedSize:\n" + " width = OwnerBound.from_number(1)\n" + " height = OwnerBound.from_number(2)\n\n\n" + "class SizedWidget:\n" + " width = OwnerBound.from_number(1)\n" + " height = OwnerBound.from_number(2)\n" + " label = 'ok'\n" + ) + _write(scan, {"app/widgets.py": bound_source}) + bound_eval, _ = _evaluation(DuplicateClassDetector(), scan, "FixedSize") + assert "__set_name__" in bound_eval.rejection_reason + assert NeededInput.PROOF in bound_eval.needs + finally: + for cached in CACHES: + cached.cache_clear() + for name in [n for n in sys.modules if n == "unit_toolkit" or n.startswith("unit_toolkit.")]: + del sys.modules[name]