From fa2a569f839d3d4214d501316299a0abe42e57ca Mon Sep 17 00:00:00 2001 From: James Emberton <60827102+j-emberton@users.noreply.github.com> Date: Wed, 2 Dec 2026 09:25:56 +0000 Subject: [PATCH] Make type-only import cleanup conservative and repeatable --- docs/development/source-migration.md | 2 + src/bilt/_tooling/migrate/cleanup.py | 80 ++++++++++++++++++++++++---- tests/cli/test_migrate.py | 37 +++++++++++++ tests/cli/test_migration_cleanup.py | 2 + tests/cli/test_migration_review.py | 1 + 5 files changed, 113 insertions(+), 9 deletions(-) diff --git a/docs/development/source-migration.md b/docs/development/source-migration.md index 30945f3f..ffddb425 100644 --- a/docs/development/source-migration.md +++ b/docs/development/source-migration.md @@ -94,3 +94,5 @@ The shared object analysis recognises direct, stable Bilt system declarations an The shared guard analysis supports recognised `isinstance` checks on local values and declared system fields, negation and conservative compound conditions. Temporary field evidence is discarded at potentially mutating calls, writes and complex control-flow boundaries. Explicit fixed-length tuple/list assignments propagate individual bindings; arbitrary iterable unpacking and unrecognised properties are not inferred. A stable undecorated module helper annotated as `object` can supply system evidence when its only return is a direct call to a recognised system constructor or annotated factory, preceded only by simple local assignments or docstrings. Unknown or shadowed factories, alternative returns and decorated functions remain unresolved. Materialising axis names with `tuple(str(axis) for axis in known_domain.axes)` preserves guarded field evidence; arbitrary projections and calls do not. Shape-independent quantities receive a specific review message rather than an inferred tensor domain. + +Cleanup reuses the lexical index to identify stable `TYPE_CHECKING` imports. An unused approved type-only import can be removed when the only dynamic access is runtime `getattr`; runtime imports, quoted references, explicit exports and other dynamic namespace access remain protected. Retained unused imports with identifiable cleanup blockers are reported on subsequent runs as well as the first pass. Imports used only in postponed annotations are not automatically moved under `TYPE_CHECKING`: runtime annotation inspection may require them. Ruff remains an optional AST-preserving formatter, not a general-purpose unsafe import fixer. diff --git a/src/bilt/_tooling/migrate/cleanup.py b/src/bilt/_tooling/migrate/cleanup.py index b31424b2..54f1bbde 100644 --- a/src/bilt/_tooling/migrate/cleanup.py +++ b/src/bilt/_tooling/migrate/cleanup.py @@ -5,6 +5,8 @@ import typing from dataclasses import dataclass +from bilt._tooling.source.lexical import LexicalScopes + if typing.TYPE_CHECKING: from collections.abc import Callable from pathlib import Path @@ -43,15 +45,49 @@ def _newly_unused_imports( return {(path, name) for path, name in _imports(before) if path in removable_imports and name in lost} -def has_dynamic_access(tree: ast.Module) -> bool: +def has_dynamic_access(tree: ast.Module, *, ignore_getattr: bool = False) -> bool: + names = _DYNAMIC - {"getattr"} if ignore_getattr else _DYNAMIC return any( - (isinstance(node, ast.Name) and node.id in _DYNAMIC) - or (isinstance(node, ast.Attribute) and node.attr in _DYNAMIC) + (isinstance(node, ast.Name) and node.id in names) + or (isinstance(node, ast.Attribute) and node.attr in names) or (isinstance(node, ast.ImportFrom) and any(alias.name == "*" for alias in node.names)) for node in ast.walk(tree) ) +def _type_only_imports(source: str, tree: ast.Module) -> set[tuple[str, str, int]]: + """Reuse lexical analysis of stable imports in TYPE_CHECKING suites.""" + try: + scope = LexicalScopes(source, tree) + except SyntaxError: + return set() + return {(reference, name, line) for name, (reference, line) in scope.type_only.items()} + + +@dataclass(frozen=True, slots=True) +class _ImportSafety: + dynamic: bool + dynamic_except_getattr: bool + type_only: frozenset[tuple[str, str, int]] + + @classmethod + def inspect(cls, source: str, tree: ast.Module) -> _ImportSafety: + dynamic = has_dynamic_access(tree) + return cls( + dynamic, + has_dynamic_access(tree, ignore_getattr=True), + frozenset(_type_only_imports(source, tree)) if dynamic else frozenset(), + ) + + def permits(self, node: ast.ImportFrom, qualified: str, name: str) -> bool: + # A stable TYPE_CHECKING import never becomes a runtime module binding. + # Runtime getattr cannot observe it. Other dynamic namespace access + # remains a blocker, as do quoted references and explicit exports. + return not self.dynamic or ( + not self.dynamic_except_getattr and (qualified, name, node.lineno) in self.type_only + ) + + def _sole_suite_statements(tree: ast.Module) -> set[ast.stmt]: return { statements[0] @@ -110,11 +146,17 @@ def remove_obsolete_imports( return migrated before = ast.parse(original) after = ast.parse(migrated) - if has_dynamic_access(before) or has_dynamic_access(after): - return migrated obsolete = _newly_unused_imports(before, after, removable_imports) if not obsolete: return migrated + safety = _ImportSafety.inspect(migrated, after) + # Retain runtime imports if dynamic access was present before the edit. + original_dynamic = has_dynamic_access(before) + original_other_dynamic = has_dynamic_access(before, ignore_getattr=True) + if original_other_dynamic: + return migrated + if original_dynamic and not safety.dynamic: + return migrated lines = migrated.encode().splitlines(keepends=True) sole = _sole_suite_statements(after) # Reverse source order keeps all earlier line offsets valid. @@ -124,7 +166,8 @@ def remove_obsolete_imports( reverse=True, ) for node in imports: - replacement = _import_replacement(node, lines, obsolete, sole_statement=node in sole) + permitted = {(qualified, name) for qualified, name in obsolete if safety.permits(node, qualified, name)} + replacement = _import_replacement(node, lines, permitted, sole_statement=node in sole) if replacement is not None: lines[node.lineno - 1 : node.end_lineno] = [replacement] result = b"".join(lines).decode() @@ -133,11 +176,23 @@ def remove_obsolete_imports( def retained_import_notes(original: str, migrated: str, removable_imports: frozenset[str]) -> tuple[str, ...]: - """Report newly unused approved imports retained by conservative cleanup.""" - if original == migrated or not removable_imports: + """Report unused approved imports that remain blocked by conservative cleanup. + + Also report newly unused imports on the first pass, for example when a + separate migration edit failed. Persist blockers identifiable in the + resulting source rather than relying only on a change in reference counts. + """ + if not removable_imports: return () before, after = ast.parse(original), ast.parse(migrated) obsolete = _newly_unused_imports(before, after, removable_imports) + references = _references(after) + unused = {(path, name) for path, name in _imports(after) if path in removable_imports and name not in references} + if not unused: + return () + safety = _ImportSafety.inspect(migrated, after) + lines = migrated.encode().splitlines(keepends=True) + sole = _sole_suite_statements(after) notes: list[str] = [] for node in ast.walk(after): if not isinstance(node, ast.ImportFrom) or node.level or node.module is None: @@ -145,7 +200,14 @@ def retained_import_notes(original: str, migrated: str, removable_imports: froze for alias in node.names: name = alias.asname or alias.name qualified = f"{node.module}.{alias.name}" - if (qualified, name) in obsolete: + candidate = (qualified, name) + if candidate not in unused: + continue + if ( + candidate in obsolete + or not safety.permits(node, qualified, name) + or _import_replacement(node, lines, {candidate}, sole_statement=node in sole) is None + ): notes.append(f"{node.lineno}: review retained import {qualified}; cleanup could not safely remove it") return tuple(notes) diff --git a/tests/cli/test_migrate.py b/tests/cli/test_migrate.py index 3a29e932..66c099d1 100644 --- a/tests/cli/test_migrate.py +++ b/tests/cli/test_migrate.py @@ -540,3 +540,40 @@ def test_project_migration_preserves_shadowed_and_unknown_helpers(tmp_path: Path consumer.write_text(source, encoding="utf-8") assert main(["migrate", str(consumer), "--write"]) == 0 assert consumer.read_text(encoding="utf-8") == source + + +def test_type_checking_cleanup_with_dynamic_runtime_getattr() -> None: + source = ( + "from __future__ import annotations\n" + "from typing import TYPE_CHECKING\n" + "from bilt import Quantity\n" + "if TYPE_CHECKING:\n" + " from bilt import QuantityTensor, Tensor\n" + "def load(value: Tensor) -> Quantity | QuantityTensor:\n" + " return Quantity(2, meter)\n" + "def read(model, name):\n" + " return getattr(model, name)\n" + ) + expected = source.replace("QuantityTensor, Tensor", "Tensor") + expected = expected.replace("Quantity | QuantityTensor", "Quantity").replace("Quantity(2, meter)", "2 * meter") + result = migrate_source(source) + assert result.source == expected + assert not result.notes + assert migrate_source(result.source) == result + + +def test_dynamic_namespace_access_still_blocks_type_only_removal() -> None: + source = ( + "from __future__ import annotations\n" + "from typing import TYPE_CHECKING\n" + "from bilt import Quantity\n" + "if TYPE_CHECKING:\n" + " from bilt import QuantityTensor\n" + "def load() -> Quantity | QuantityTensor:\n" + " return Quantity(2, meter)\n" + "namespace = globals()\n" + ) + result = migrate_source(source) + assert "from bilt import QuantityTensor" in result.source + assert result.notes == ("5: review retained import bilt.QuantityTensor; cleanup could not safely remove it",) + assert migrate_source(result.source) == result diff --git a/tests/cli/test_migration_cleanup.py b/tests/cli/test_migration_cleanup.py index ce8a3c7e..11721631 100644 --- a/tests/cli/test_migration_cleanup.py +++ b/tests/cli/test_migration_cleanup.py @@ -88,4 +88,6 @@ def test_removal_and_retained_notes_share_eligibility() -> None: assert remove_obsolete_imports(before, after, _APPROVED) == after assert retained_import_notes(before, after, _APPROVED) == ( "1: review retained import example.old; cleanup could not safely remove it", + "1: review retained import example.other; cleanup could not safely remove it", ) + assert retained_import_notes(after, after, _APPROVED) == retained_import_notes(before, after, _APPROVED) diff --git a/tests/cli/test_migration_review.py b/tests/cli/test_migration_review.py index 28a35663..81c3c2d5 100644 --- a/tests/cli/test_migration_review.py +++ b/tests/cli/test_migration_review.py @@ -52,6 +52,7 @@ def test_retained_import_report_does_not_prevent_rewrite() -> None: result = migrate_source(source) assert result.source == source.replace("Mass = Quantity | QuantityTensor", "Mass = Quantity") assert result.notes == ("1: review retained import bilt.QuantityTensor; cleanup could not safely remove it",) + assert migrate_source(result.source) == result def test_scalar_return_after_quantity_check_is_reported() -> None: