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
2 changes: 2 additions & 0 deletions docs/development/source-migration.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,3 +96,5 @@ The shared guard analysis supports recognised `isinstance` checks on local value
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.

At a direct `-> float` return with recognised quantity evidence, or a direct `numpy.broadcast_to` return in an explicitly selected non-tensor branch with known quantity evidence, migration can wrap the magnitude in `float(...)`. This uses the existing scalar conversion contract (non-scalar arrays raise rather than flattening). Unknown receivers, shadowed builtins and ambiguous NumPy comparisons remain reviewable. The migration does not introduce a new runtime API or insert assertions that could disappear under optimization.
1 change: 1 addition & 0 deletions src/bilt/_tooling/migrate/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ def __init__(
exports = project.exports if project is not None else {}
super().__init__(source, tree, package, exports)
self.rules = rules
self.parents = {child: parent for parent in ast.walk(tree) for child in ast.iter_child_nodes(parent)}
self.path = path
self.notes: list[str] = []
self.review_notes: list[str] = []
Expand Down
78 changes: 78 additions & 0 deletions src/bilt/_tooling/migrate/review.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
if typing.TYPE_CHECKING:
from collections.abc import Iterator

from bilt._tooling.migrate.engine import MigrationContext, MigrationNode

_PAIR = 2
_NUMPY_BOUNDARIES = frozenset({"numpy.broadcast_to", "numpy.testing.assert_allclose"})

Expand Down Expand Up @@ -118,6 +120,82 @@ def visit(self, node: ast.AST) -> None:
)


def _explicit_float_return(node: ast.Attribute, context: MigrationContext) -> bool:
"""An immediate return with an explicit builtin scalar result contract."""
parent = context.parents.get(node)
if not isinstance(parent, ast.Return):
return False
while (parent := context.parents.get(parent)) is not None:
if isinstance(parent, (ast.FunctionDef, ast.AsyncFunctionDef)):
annotation = parent.returns
return (isinstance(annotation, ast.Name) and annotation.id == "float") or (
isinstance(annotation, ast.Constant) and annotation.value == "float"
)
if isinstance(parent, (ast.Lambda, ast.ClassDef)):
return False
return False


def _guarded_scalar_broadcast(node: ast.Attribute, context: MigrationContext) -> bool:
"""Only narrow the first positional argument of an already selected scalar branch."""
call = context.parents.get(node)
if not (
isinstance(call, ast.Call)
and call.args
and call.args[0] is node
and context.resolve(call.func) == "numpy.broadcast_to"
):
return False
statement = context.parents.get(call)
if not isinstance(statement, ast.Return):
return False
branch = context.parents.get(statement)
receiver = _quantity_receiver(node)
return (
isinstance(receiver, ast.Name)
and isinstance(branch, ast.If)
and branch.body[0] is statement
and isinstance(branch.test, ast.UnaryOp)
and isinstance(branch.test.op, ast.Not)
and _checks_receiver(branch.test.operand, receiver, context, frozenset({QUANTITY_TENSOR}))
and context.object_kind(receiver) in QUANTITY_TYPES
)


def _immediate_quantity_assertion(node: ast.Attribute, context: MigrationContext) -> bool:
"""Recognise a direct name asserted immediately before a scalar return."""
receiver = _quantity_receiver(node)
statement = context.parents.get(node)
if not isinstance(receiver, ast.Name) or not isinstance(statement, ast.Return):
return False
parent = context.parents.get(statement)
if parent is None:
return False
for _, suite in ast.iter_fields(parent):
if not isinstance(suite, list) or statement not in suite:
continue
index = suite.index(statement)
if index and isinstance(previous := suite[index - 1], ast.Assert):
return _checks_receiver(previous.test, receiver, context, QUANTITY_TYPES)
return False


def migrate_scalar_boundary(node: MigrationNode, context: MigrationContext) -> None:
"""Use the existing scalar conversion contract, never reshape a tensor."""
if not isinstance(node, ast.Attribute) or node.attr != "value" or not context.builtin_visible("float"):
return
receiver = _quantity_receiver(node)
if not (
_guarded_scalar_broadcast(node, context)
or (
_explicit_float_return(node, context)
and (context.object_kind(receiver) in QUANTITY_TYPES or _immediate_quantity_assertion(node, context))
)
):
return
context.editor.replace_expression(node, b"float(" + context.editor.render(node) + b")")


def review_quantity_shapes(source: str) -> tuple[str, ...]:
"""Report syntactically identifiable shape-sensitive sites in migrated source."""
tree = ast.parse(source)
Expand Down
3 changes: 2 additions & 1 deletion src/bilt/_tooling/migrate/rules.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from bilt._tooling.migrate.engine import migrate as _migrate
from bilt._tooling.migrate.engine import migrate_source as _migrate_source
from bilt._tooling.migrate.renames import RenameApiRule
from bilt._tooling.migrate.review import review_quantity_shapes
from bilt._tooling.migrate.review import migrate_scalar_boundary, review_quantity_shapes
from bilt._tooling.source.obsolete_api import (
AXIS_RENAMES,
QUANTITY_TENSOR,
Expand Down Expand Up @@ -158,6 +158,7 @@ def _migrate_tensor_runtime_check(node: MigrationNode, context: MigrationContext
_simplify_quantity_union,
_migrate_dimensioned_tensor_annotation,
_migrate_tensor_runtime_check,
migrate_scalar_boundary,
)


Expand Down
7 changes: 7 additions & 0 deletions src/bilt/_tooling/source/objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,13 @@ def _attribute_binding(self, node: ast.Attribute) -> InferredKind | None:
return None

def _call_binding(self, node: ast.Call) -> ValueKind | None:
if (
isinstance(node.func, ast.Attribute)
and node.func.attr in {"convert_to", "cast_to"}
and isinstance(owner := self.binding(node.func.value), InferredKind)
and owner.name in QUANTITY_KINDS
):
return owner
callee = self.binding(node.func)
if isinstance(callee, FunctionReturn):
return callee.kind
Expand Down
77 changes: 69 additions & 8 deletions tests/cli/test_migration_review.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""Review diagnostics are advisory and do not invent scalar semantics."""

import pytest

from bilt._tooling.migrate.review import review_quantity_shapes
from bilt._tooling.migrate.rules import migrate_source

Expand Down Expand Up @@ -55,18 +57,19 @@ def test_retained_import_report_does_not_prevent_rewrite() -> None:
assert migrate_source(result.source) == result


def test_scalar_return_after_quantity_check_is_reported() -> None:
def test_scalar_return_after_quantity_check_is_extracted() -> None:
source = (
"from bilt import Quantity\n"
"def extract(value) -> float:\n"
" assert isinstance(value, Quantity)\n"
" return value.convert_to(percent).value\n"
)
result = migrate_source(source)
assert result.source == source
assert result.notes == (
"4: review magnitude at scalar or NumPy boundary; explicitly narrow or extract the intended shape",
assert result.source == source.replace(
"return value.convert_to(percent).value", "return float(value.convert_to(percent).value)"
)
assert not result.notes
assert migrate_source(result.source) == result
corrected = source.replace(
" return value.convert_to(percent).value",
" magnitude = value.convert_to(percent).value\n assert isinstance(magnitude, float)\n return magnitude",
Expand Down Expand Up @@ -130,8 +133,66 @@ def test_no_review_for_unrelated_magnitude_or_shape_independent_use() -> None:

def test_read_only_review_matches_migration_notes() -> None:
source = "from bilt import Quantity\ndef extract(value: Quantity) -> float:\n return value.value\n"
assert (
review_quantity_shapes(source)
== migrate_source(source).notes
== ("3: review magnitude at scalar or NumPy boundary; explicitly narrow or extract the intended shape",)
assert review_quantity_shapes(source) == (
"3: review magnitude at scalar or NumPy boundary; explicitly narrow or extract the intended shape",
)
result = migrate_source(source)
assert result.source == source.replace("return value.value", "return float(value.value)")
assert not result.notes
assert migrate_source(result.source) == result


def test_known_quantity_broadcast_in_scalar_branch() -> None:
source = (
"import numpy as np\n"
"from bilt import Quantity, QuantityTensor\n"
"def align(value: Quantity, unit):\n"
" converted = value.convert_to(unit)\n"
" if not isinstance(converted, QuantityTensor):\n"
" return np.broadcast_to(converted.value, shape)\n"
" return converted.values\n"
)
expected = source.replace("broadcast_to(converted.value,", "broadcast_to(float(converted.value),")
result = migrate_source(source)
assert result.source == expected
assert not result.notes
assert migrate_source(result.source) == result


def test_scalar_extraction_does_not_reuse_stale_assertion() -> None:
source = (
"from bilt import Quantity\n"
"def extract(value) -> float:\n"
" assert isinstance(value, Quantity)\n"
" value = other\n"
" return value.value\n"
)
assert migrate_source(source).source == source


def test_scalar_extraction_respects_shadowed_float() -> None:
source = "from bilt import Quantity\ndef extract(value: Quantity, float) -> float:\n return value.value\n"
assert migrate_source(source).source == source


def test_known_quantity_broadcast_without_scalar_guard_is_not_extracted() -> None:
source = (
"import numpy as np\n"
"from bilt import Quantity\n"
"def align(value: Quantity):\n"
" return np.broadcast_to(value.value, shape)\n"
)
result = migrate_source(source)
assert result.source == source
assert result.notes


def test_quantity_scalar_conversion_runtime_contract() -> None:
from bilt import axis, tensor # noqa: PLC0415
from bilt.units import meter # noqa: PLC0415

expected = 2.0
assert float((expected * meter).value) == expected
assert float(tensor(expected, unit=meter).value) == expected
with pytest.raises(TypeError):
float(tensor([2.0, 3.0], over=axis("sample"), unit=meter).value)
Loading