Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(graph): resolve a Python alias of an imported name to its definition (#4812)

Swati Ahuja37ac869ed62f
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
index cb531549c..73a207a5c 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -420,6 +420,9 @@ class CallResolver(
# applied alongside ``_decl_to_def`` in ``_redirect_to_definition``
# (#2791).
self._alias_to_target: dict[str, str] = {}
+ # Module-level aliases of a name the file imports (``s = attrs`` after
+ # ``from ._make import attrs``), linked once barrel origins are known.
+ self._imported_aliases: list[tuple[str, str, str]] = []
# Import graph: {file_path: set of imported file paths}
self._import_targets = import_targets
@@ -461,6 +464,7 @@ class CallResolver(
self._build_indices(parsed_files)
self._follow_barrel_exports()
+ self._link_imported_aliases()
# Only a call to one of these has its named arguments typed.
self._overloaded_names = frozenset(self._symbols_by_id[m].name for m in self._overload_rep)
@@ -568,6 +572,8 @@ class CallResolver(
# No self-redirect: ``s = s`` names nothing beyond itself.
if target_id is not None and target_id != alias_id:
self._alias_to_target[alias_id] = target_id
+ elif target_id is None and parent_name is None:
+ self._imported_aliases.append((path, alias_id, alias_of_name))
self._file_symbols[path] = file_syms
self._file_top_level[path] = top_level
@@ -1532,18 +1538,38 @@ class CallResolver(
binding: NamedBinding | None,
) -> ResolvedCall | None:
"""2a: the specific imported name, binding-aware."""
+ published = self._imported_symbol(binding, call.target_name)
+ if published is None:
+ return None
+ return ResolvedCall(caller_id, published, 0.90, call.line, "import_scoped")
+
+ def _imported_symbol(self, binding: NamedBinding | None, name: str) -> str | None:
+ """The repo symbol an imported *name* binds, one barrel hop followed."""
if not (binding and binding.source_file):
return None
source_file = binding.source_file
- # Follow barrel re-export one hop
barrel = self._barrel_origins.get(source_file, {})
- lookup_name = binding.exported_name or call.target_name
+ lookup_name = binding.exported_name or name
if lookup_name in barrel:
source_file = barrel[lookup_name]
- published = self._published(source_file, lookup_name)
- if published is None:
- return None
- return ResolvedCall(caller_id, published, 0.90, call.line, "import_scoped")
+ return self._published(source_file, lookup_name)
+
+ def _link_imported_aliases(self) -> None:
+ """Redirect a module-level alias of an imported name onto its definition.
+
+ ``s = attributes = attrs`` after ``from ._make import attrs`` stands
+ for ``_make.attrs``; the same-file pass in ``_index_file`` finds no
+ ``attrs`` to link. An ``import x`` binding names a module, so it is
+ skipped. Ceiling: ``from pkg import sub`` binds a submodule like a name
+ and resolves as the import tier does; calling a module is never valid.
+ """
+ for path, alias_id, name in self._imported_aliases:
+ binding = self._import_bindings.get(path, {}).get(name)
+ if binding is None or binding.is_module_alias:
+ continue
+ target_id = self._imported_symbol(binding, name)
+ if target_id is not None and target_id != alias_id:
+ self._alias_to_target[alias_id] = target_id
def _named_import_call(
self,
diff --git a/tests/unit/ingestion/test_call_resolver_strategies.py b/tests/unit/ingestion/test_call_resolver_strategies.py
index aa9dfcb8a..b4ad7a64b 100644
--- a/tests/unit/ingestion/test_call_resolver_strategies.py
+++ b/tests/unit/ingestion/test_call_resolver_strategies.py
@@ -2436,6 +2436,108 @@ class TestPythonNameAliasAssignment:
assert len(attributes_symbols) == 2
assert len({symbol.id for symbol in attributes_symbols}) == 2
+ def _imported_alias_repo(self, tmp_path: Path, alias_line: str) -> dict[str, ParsedFile]:
+ parsed = _parse_all(
+ tmp_path,
+ {
+ "pkg/_make.py": ("python", "def attrs():\n pass\n"),
+ "pkg/__init__.py": (
+ "python",
+ f"from pkg._make import attrs\n\n{alias_line}\n",
+ ),
+ "app.py": (
+ "python",
+ "import pkg\nfrom pkg import s\n\n"
+ "def via_module():\n pkg.s()\n\n"
+ "def via_name():\n s()\n",
+ ),
+ },
+ )
+ _link_imports(
+ parsed,
+ {
+ "app.py": {"pkg": "pkg/__init__.py"},
+ "pkg/__init__.py": {"pkg._make": "pkg/_make.py"},
+ },
+ )
+ return parsed
+
+ def _app_edges(self, parsed: dict[str, ParsedFile], tmp_path: Path) -> set[tuple[str, str]]:
+ return {
+ (caller, callee)
+ for caller, callee, _, _ in _edges(parsed, tmp_path)
+ if caller.startswith("app.py")
+ }
+
+ def test_an_alias_of_an_imported_name_resolves_to_its_definition(
+ self, tmp_path: Path
+ ) -> None:
+ """``s = attributes = attrs`` re-exports an imported def under new names."""
+ parsed = self._imported_alias_repo(tmp_path, "s = attributes = attrs")
+ assert self._app_edges(parsed, tmp_path) == {
+ ("app.py::via_module", "pkg/_make.py::attrs"),
+ ("app.py::via_name", "pkg/_make.py::attrs"),
+ }
+
+ def test_a_class_level_alias_of_an_imported_name_is_not_linked(
+ self, tmp_path: Path
+ ) -> None:
+ """Only a module-level alias is linked; ``class C: s = attrs`` is left alone."""
+ parsed = _parse_all(
+ tmp_path,
+ {
+ "pkg/_make.py": ("python", "def attrs():\n pass\n"),
+ "pkg/__init__.py": (
+ "python",
+ "from pkg._make import attrs\n\nclass C:\n s = attrs\n",
+ ),
+ "app.py": ("python", "from pkg import C\n\ndef run():\n C.s()\n"),
+ },
+ )
+ _link_imports(
+ parsed,
+ {
+ "app.py": {"pkg": "pkg/__init__.py"},
+ "pkg/__init__.py": {"pkg._make": "pkg/_make.py"},
+ },
+ )
+ assert ("app.py::run", "pkg/_make.py::attrs") not in self._app_edges(parsed, tmp_path)
+
+ def test_an_alias_of_a_renamed_import_resolves_to_its_definition(
+ self, tmp_path: Path
+ ) -> None:
+ parsed = self._imported_alias_repo(
+ tmp_path, "from pkg._make import attrs as _attrs\ns = _attrs"
+ )
+ assert ("app.py::via_name", "pkg/_make.py::attrs") in self._app_edges(parsed, tmp_path)
+
+ def test_a_value_built_from_an_imported_name_is_not_an_alias(
+ self, tmp_path: Path
+ ) -> None:
+ parsed = self._imported_alias_repo(tmp_path, "s = attrs()")
+ assert self._app_edges(parsed, tmp_path) == {
+ ("app.py::via_module", "pkg/__init__.py::s"),
+ ("app.py::via_name", "pkg/__init__.py::s"),
+ }
+
+ def test_an_alias_of_an_imported_module_is_left_alone(self, tmp_path: Path) -> None:
+ parsed = _parse_all(
+ tmp_path,
+ {
+ "pkg/helpers.py": ("python", "def helpers():\n pass\n"),
+ "pkg/__init__.py": ("python", "import pkg.helpers as helpers\n\ns = helpers\n"),
+ "app.py": ("python", "import pkg\n\ndef run():\n pkg.s()\n"),
+ },
+ )
+ _link_imports(
+ parsed,
+ {
+ "app.py": {"pkg": "pkg/__init__.py"},
+ "pkg/__init__.py": {"pkg.helpers": "pkg/helpers.py"},
+ },
+ )
+ assert ("app.py::run", "pkg/helpers.py::helpers") not in self._app_edges(parsed, tmp_path)
+
_JS_TS = [("javascript", "js"), ("typescript", "ts")]