Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(ingestion): follow a Kotlin typealias to the repo class it names (#3787)
Yunus Ozen95db0df49f72
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.pyindex 1676da986..8e89ada86 100644--- a/packages/core/src/repowise/core/ingestion/call_resolver.py+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py@@ -81,6 +81,7 @@ from .type_names import (bare_type_name,csharp_extension_receiver,is_resolvable_type_name,+ strip_type_arguments,)log = structlog.get_logger(__name__)@@ -1410,6 +1411,23 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):# --- Free function call: function() ---return self._with_props(self._resolve_bare_call(file_path, call, caller_id), call)+ def _through_kotlin_alias(+ self, alias: Symbol, call: CallSite, caller_id: str+ ) -> ResolvedCall | None:+ """The repo class a Kotlin ``typealias`` names, as a call in its file would reach it."""+ _, _, target = (alias.signature or "").partition(" = ")+ head = strip_type_arguments(target).rstrip("? ").strip()+ alias_file = self._symbol_paths_by_id.get(alias.id)+ # A function type, a qualified (possibly external) name or the alias's own+ # name gives no repo class to construct.+ if alias_file is None or not head.isidentifier() or head == alias.name:+ return None+ hit = self._resolve_free_call(alias_file, replace(call, target_name=head), alias.id)+ target_sym = self._symbols_by_id.get(hit.callee_id) if hit is not None else None+ if target_sym is None or target_sym.kind != "class" or target_sym.name == alias.name:+ return None+ return replace(hit, caller_id=caller_id)+def _resolve_bare_call(self,file_path: str,@@ -1418,17 +1436,19 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):) -> ResolvedCall | None:"""A receiver-less call, refused where it lands on an extension it has no receiver for.- Also refused on a Kotlin ``typealias``: ``IOException(..)`` through- ``actual typealias IOException = java.io.IOException`` constructs the- aliased type, which the alias is not. Ceiling: an alias of a repo class- draws no edge to that class.+ A Kotlin ``typealias`` is followed to the class it names, resolved from+ the alias's own file, and refused when that is not a repo class:+ ``IOException(..)`` through ``actual typealias IOException =+ java.io.IOException`` constructs the external type, which the alias is+ not. Ceiling: a qualified target (``= app.data.Repo``) is refused too."""invoked = self._operator_invoke_call(file_path, call, caller_id)if invoked is not None:return invokedhit = self._resolve_free_call(file_path, call, caller_id)- if hit is not None and _is_kotlin_alias(self._symbols_by_id.get(hit.callee_id)):- return None+ alias = self._symbols_by_id.get(hit.callee_id) if hit is not None else None+ if _is_kotlin_alias(alias):+ return self._through_kotlin_alias(alias, call, caller_id)if hit is None or call.receiver_call is not None:return hitreturn None if self._lacks_extension_receiver(file_path, call, hit.callee_id) else hitdiff --git a/packages/core/src/repowise/core/ingestion/extractors/signatures.py b/packages/core/src/repowise/core/ingestion/extractors/signatures.pyindex 571e80a7f..b6d432937 100644--- a/packages/core/src/repowise/core/ingestion/extractors/signatures.py+++ b/packages/core/src/repowise/core/ingestion/extractors/signatures.py@@ -68,6 +68,10 @@ def build_signature(node_type: str, name: str, params_text: str, def_node: Node,return f"{name}(){_ret(('type',))}"if node_type == "type_alias_declaration":return f"type {name}"+ if node_type == "type_alias" and any(c.type == "typealias" for c in def_node.children):+ # Kotlin: keep the aliased type, which a call through the alias constructs.+ target = def_node.children[-1]+ return f"typealias {name} = {node_text(target, src)}"if node_type == "enum_declaration":return f"enum {name}"if node_type in ("method_definition", "method_signature"):diff --git a/packages/core/src/repowise/core/upgrade/version.py b/packages/core/src/repowise/core/upgrade/version.pyindex ce91ad826..1d0a209c1 100644--- a/packages/core/src/repowise/core/upgrade/version.py+++ b/packages/core/src/repowise/core/upgrade/version.py@@ -95,6 +95,8 @@ STORE_FORMAT_VERSION: int = 2#: argument.#: A Kotlin call whose only argument is a trailing lambda (``AppTheme { }``,#: ``s.forEachSegment { }``) is a call site, with one argument.+#: A Kotlin ``typealias`` signature carries its target (``typealias Repo =+#: DefaultRepository``), so a call through the alias reaches the repo class.PARSER_SCHEMA_VERSION: int = 8#: state.json key holding the store format version that wrote the store.diff --git a/tests/unit/ingestion/test_kotlin_typealias_calls.py b/tests/unit/ingestion/test_kotlin_typealias_calls.pynew file mode 100644index 000000000..d73cbe42b--- /dev/null+++ b/tests/unit/ingestion/test_kotlin_typealias_calls.py@@ -0,0 +1,83 @@+"""A Kotlin call through a ``typealias`` of a repo class reaches that class (#3760).++``Repo()`` where ``typealias Repo = DefaultRepository`` constructs+``DefaultRepository``. The alias is followed from its own file, the way a call+written there would resolve, and only a repo class counts: a function type, a+primitive or a qualified external target still gives no callee (see+``test_kotlin_multiplatform_calls.py`` for ``actual typealias``).+"""++from __future__ import annotations++from pathlib import Path++import pytest++from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder++_SRC = "src/main/kotlin/"+FILES = {+ _SRC + "a/Repository.kt": (+ "package a\n\n"+ "class DefaultRepository {\n fun load(): Int = 0\n}\n\n"+ "typealias Repo = DefaultRepository\n\n"+ "class Holder<T>\n\n"+ "typealias Repos = Holder<String>\n\n"+ "typealias Handler = (String) -> Unit\n\n"+ "typealias Fd = Int\n\n"+ "fun sameFile() = Repo()\n"+ ),+ _SRC + "a/Use.kt": (+ "package a\n\n"+ "fun direct() = DefaultRepository()\n\n"+ "fun samePackage() = Repo()\n\n"+ "fun generic() = Repos()\n\n"+ "fun functionType() = Handler()\n\n"+ "fun primitive() = Fd()\n"+ ),+ _SRC + "b/Imported.kt": "package b\n\nimport a.Repo\n\nfun imported() = Repo()\n",+}++_REPOSITORY = _SRC + "a/Repository.kt"++[email protected](scope="module")+def calls(tmp_path_factory: pytest.TempPathFactory) -> dict[str, set[str]]:+ repo = tmp_path_factory.mktemp("alias")+ for rel, text in FILES.items():+ path = repo / rel+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(text)+ parser = ASTParser()+ builder = GraphBuilder(repo_path=repo)+ for fi in FileTraverser(repo).traverse():+ builder.add_file(parser.parse_file(fi, Path(fi.abs_path).read_bytes()))+ out: dict[str, set[str]] = {}+ for caller, callee, data in builder.build().edges(data=True):+ if data.get("edge_type") == "calls":+ out.setdefault(caller.rsplit("::", 1)[-1], set()).add(callee)+ return out++[email protected]("caller", ["direct", "sameFile", "samePackage", "imported"])+def test_a_call_through_an_alias_reaches_the_class(calls: dict[str, set[str]], caller: str) -> None:+ assert calls[caller] == {_REPOSITORY + "::DefaultRepository"}+++def test_a_generic_alias_reaches_its_class(calls: dict[str, set[str]]) -> None:+ assert calls["generic"] == {_REPOSITORY + "::Holder"}++[email protected]("caller", ["functionType", "primitive"])+def test_an_alias_of_no_repo_class_has_no_callee(calls: dict[str, set[str]], caller: str) -> None:+ assert caller not in calls+++def test_the_alias_signature_carries_its_target(tmp_path: Path) -> None:+ path = tmp_path / "A.kt"+ path.write_text("package a\n\ntypealias Repos = Holder<String>\n")+ (fi,) = FileTraverser(tmp_path).traverse()+ parsed = ASTParser().parse_file(fi, path.read_bytes())++ (alias,) = [s for s in parsed.symbols if s.kind == "type_alias"]+ assert alias.signature == "typealias Repos = Holder<String>"