From 4e9364d66f42f56f1be2e9f87a8ef7f6eae7301d Mon Sep 17 00:00:00 2001 From: James Emberton <60827102+j-emberton@users.noreply.github.com> Date: Wed, 2 Dec 2026 09:08:33 +0000 Subject: [PATCH] Recognise simple system factory wrappers and axis-name reads --- docs/development/source-migration.md | 2 + src/bilt/_tooling/source/objects.py | 74 +++++++++++++++++++- src/bilt/_tooling/source/obsolete_api.py | 11 ++- tests/cli/test_obsolete_api.py | 86 ++++++++++++++++++++++++ 4 files changed, 171 insertions(+), 2 deletions(-) diff --git a/docs/development/source-migration.md b/docs/development/source-migration.md index 1180a430..30945f3f 100644 --- a/docs/development/source-migration.md +++ b/docs/development/source-migration.md @@ -92,3 +92,5 @@ Project migration uses a source-only index of the original project files to reso The shared object analysis recognises direct, stable Bilt system declarations and explicit non-generic `type` aliases. It distinguishes system constructors from instances and annotation-only aliases from runtime callables. Only declared fields with identifiable kinds supply evidence; scalar-or-tensor unions do not establish tensor shape. Inheritance, unknown decorators and dynamic class bodies remain outside this analysis. 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. diff --git a/src/bilt/_tooling/source/objects.py b/src/bilt/_tooling/source/objects.py index a53828f5..1e6ffc20 100644 --- a/src/bilt/_tooling/source/objects.py +++ b/src/bilt/_tooling/source/objects.py @@ -323,9 +323,34 @@ def visit(self, node: ast.AST) -> None: def _may_change_fields(self, node: ast.AST) -> bool: if isinstance(node, ast.Call): - return not self.is_builtin_call(node, "isinstance") + return not (self.is_builtin_call(node, "isinstance") or self._axis_names_read(node)) return isinstance(node, (ast.Attribute, ast.Subscript)) and isinstance(node.ctx, (ast.Store, ast.Del)) + def _axis_names_read(self, node: ast.Call) -> bool: + """Recognise read-only materialisation of names from a known Bilt domain.""" + if not self.is_builtin_call(node, "tuple") or node.keywords or len(node.args) != 1: + return False + match node.args[0]: + case ast.GeneratorExp( + elt=ast.Call(args=[ast.Name(id=argument)], keywords=[]) as conversion, + generators=[ + ast.comprehension( + target=ast.Name(id=target), + iter=ast.Attribute(attr="dims" | "axes", value=domain), + ifs=[], + is_async=0, + ) + ], + ): + return ( + argument == target + and target != "str" + and self.is_builtin_call(conversion, "str") + and self.object_kind(domain) == "bilt.Domain" + ) + case _: + return False + @typing.override def visit_Assert(self, node: ast.Assert) -> None: self.generic_visit(node) @@ -351,8 +376,55 @@ def function_binding(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> Bind ): return None kind = self.annotation_binding(node.returns) + if kind is None: + kind = self._forwarded_system(node) return FunctionReturn(kind) if kind is not None else None + def _forwarded_system(self, node: ast.FunctionDef) -> SystemValue | None: + """Resolve the terminal factory call of a supported wrapper.""" + name = self._forwarded_factory_name(node) + if name is None: + return None + callee = self.scope.bindings.get(name) + if isinstance(callee, str): + callee = self.canonical_reference(callee) + if isinstance(callee, SystemClass): + return SystemValue(callee) + if isinstance(callee, FunctionReturn) and isinstance(callee.kind, SystemValue): + return SystemValue(callee.kind.system) + return None + + def _forwarded_factory_name(self, node: ast.FunctionDef) -> str | None: + """Require a single terminal call through a stable module-level binding.""" + if not (isinstance(node.returns, ast.Name) and node.returns.id == "object" and self.builtin_visible("object")): + return None + *prefix, last = node.body + if not ( + isinstance(last, ast.Return) and isinstance(last.value, ast.Call) and isinstance(last.value.func, ast.Name) + ): + return None + name = last.value.func.id + table = self.lexical.function(node) + if table is None or name not in table.get_identifiers() or not table.lookup(name).is_global(): + return None + if not all(self._factory_setup(statement, table) for statement in prefix): + return None + if name not in self.lexical.globals_for(node, table) and name not in self.stable_values: + return None + return name if self.lexical.global_in_children(name) else None + + @staticmethod + def _factory_setup(statement: ast.stmt, table: symtable.SymbolTable) -> bool: + """Accept only docstrings and ordinary local setup assignments.""" + if isinstance(statement, ast.Expr): + return isinstance(statement.value, ast.Constant) and isinstance(statement.value.value, str) + return isinstance(statement, ast.Assign) and all( + isinstance(target, ast.Name) + and table.lookup(target.id).is_local() + and not table.lookup(target.id).is_global() + for target in statement.targets + ) + def _system_class(self, node: ast.ClassDef) -> SystemClass | None: """Collect explicit fields from a simple, stable Bilt system declaration.""" if ( diff --git a/src/bilt/_tooling/source/obsolete_api.py b/src/bilt/_tooling/source/obsolete_api.py index c1d99305..6eeac245 100644 --- a/src/bilt/_tooling/source/obsolete_api.py +++ b/src/bilt/_tooling/source/obsolete_api.py @@ -103,7 +103,7 @@ def findings(self, node: MigrationNode, context: ObjectVisitor) -> Iterator[Rena node, "dims", self.members["bilt.Domain", "dims"], - reason="review unresolved .domain.dims access; use .axes for a Bilt domain", + reason=_unresolved_axis_reason(node.value.value, context), suspected=True, ) @@ -119,6 +119,15 @@ def _keyword_matches(self, node: ast.Call, reference: str) -> Iterator[Rename]: yield Rename(keyword, keyword.arg, new, reason) +def _unresolved_axis_reason(receiver: ast.expr, context: ObjectVisitor) -> str: + if context.object_kind(receiver) in QUANTITY_TYPES: + return ( + "review unresolved .domain.dims access; quantity shape is not established; " + "narrow to QuantityTensor before using .axes" + ) + return "review unresolved .domain.dims access; use .axes for a Bilt domain" + + def _positional_matches(node: ast.Call, parameters: tuple[str, ...]) -> Iterator[Rename]: """Only remove keyword labels when argument evaluation order is preserved.""" for keyword in node.keywords: diff --git a/tests/cli/test_obsolete_api.py b/tests/cli/test_obsolete_api.py index 0d0b9be5..059fde23 100644 --- a/tests/cli/test_obsolete_api.py +++ b/tests/cli/test_obsolete_api.py @@ -621,3 +621,89 @@ def test_literal_unpacking_propagates_type_evidence() -> None: ) assert migrate_source(source, _RULES).source == expected assert _diagnostics(source) == ["Obsolete API name 'dims'; use 'axes' instead."] * 2 + + +def test_project_factory_wrapper_and_repeated_guarded_axis_reads(tmp_path: Path) -> None: + producer = tmp_path / "producer.py" + producer.write_text( + _SYSTEM_GUARD_SOURCE + "def create(**values) -> Model:\n return Model(**values)\n", + encoding="utf-8", + ) + consumer = tmp_path / "consumer.py" + source = ( + "from bilt import QuantityTensor\n" + "from producer import create\n" + "def load(**overrides) -> object:\n" + " defaults = {'output': 1}\n" + " return create(**(defaults | overrides))\n" + "def read():\n" + " model = load()\n" + " assert isinstance(model.output, QuantityTensor)\n" + " assert tuple(str(axis) for axis in model.output.domain.dims) == ('a', 'b') or tuple(\n" + " str(axis) for axis in model.output.domain.dims\n" + " ) == ('b', 'a')\n" + ) + consumer.write_text(source, encoding="utf-8") + found = discover(consumer, tmp_path, ()) + assert len(found.errors) == source.count(".domain.dims") + assert all("BILT107" in error for error in found.errors) + assert not found.warnings + assert migrate(consumer, write=True, selection=SourceSelection(tmp_path)) == 0 + expected = source.replace(".dims", ".axes") + assert consumer.read_text(encoding="utf-8") == expected + assert not discover(consumer, tmp_path, ()).errors + assert migrate(consumer, write=True, selection=SourceSelection(tmp_path)) == 0 + assert consumer.read_text(encoding="utf-8") == expected + + +@pytest.mark.parametrize( + "definition", + ( + "def load(Model) -> object:\n return Model()\n", + "def load() -> object:\n Model = other\n return Model()\n", + "def load() -> object:\n if flag:\n return other\n return Model()\n", + "def load() -> object:\n return Model()\nload = other\n", + "def load() -> object:\n return other()\n", + "@decorate\ndef load() -> object:\n return Model()\n", + ), +) +def test_ambiguous_factory_wrapper_is_not_inferred(definition: str) -> None: + source = ( + _SYSTEM_GUARD_SOURCE + + definition + + ( + "def read():\n" + " model = load()\n" + " assert isinstance(model.output, QuantityTensor)\n" + " return model.output.domain.dims\n" + ) + ) + assert migrate_source(source, _RULES).source == source + assert not _diagnostics(source) + + +@pytest.mark.parametrize("projection", ("convert(axis)", "str(axis, encoding)", "str(axis) if flag else other")) +def test_unknown_axis_projection_invalidates_field_guard(projection: str) -> None: + source = _SYSTEM_GUARD_SOURCE + ( + "def read(model: Model):\n" + " assert isinstance(model.output, QuantityTensor)\n" + f" names = tuple({projection} for axis in model.output.domain.dims)\n" + " return model.output.domain.dims\n" + ) + expected = source.replace("for axis in model.output.domain.dims", "for axis in model.output.domain.axes") + assert migrate_source(source, _RULES).source == expected + assert _diagnostics(source) == ["Obsolete API name 'dims'; use 'axes' instead."] + + +def test_shape_independent_quantity_has_specific_review() -> None: + source = _SYSTEM_GUARD_SOURCE + ( + "def read(model: Model):\n output = model.output\n return output.domain.dims\n" + ) + checker = ApiChecker(source, ast.parse(source), "model.py", "", {}) + checker.visit(checker.tree) + result = migrate_source(source, _RULES) + assert result.source == source + assert not checker.diagnostics + assert [warning.code for warning in checker.warnings] == ["BILT108"] + assert "quantity shape is not established" in checker.warnings[0].message + assert result.notes == tuple(f"7: {warning.message}" for warning in checker.warnings)