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(health): roll anonymous-class members up to their named owner (#3643)
Swati Ahuja64b97d7369cc
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/split_file.py b/packages/core/src/repowise/core/analysis/health/refactoring/split_file.pyindex c5a531e72..f45524c40 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/split_file.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/split_file.py@@ -57,6 +57,8 @@ from typing import Anyfrom repowise.core.analysis.execution_graph import is_reliable_call_edgefrom ....code_origin import is_migration_path, is_vendored_or_generated_path+from ....ingestion.lang_helpers.anonymous_classes import is_anonymous_scope+from ....ingestion.symbol_identity import outer_scopefrom ....test_paths import is_test_related_pathfrom ...dead_code.file_reachability import BARREL_FILENAMESfrom ..effort import effort_bucket@@ -703,7 +705,9 @@ class SplitFileDetector(RefactoringDetector):def _resolve_owner(self, file_path: str, sid: str, defined: dict[str, dict]) -> str:"""Walk ``parent_name`` up to the outermost top-level symbol (a method- rolls up to its class, a nested function to its owner)."""+ rolls up to its class, a nested function to its owner). An anonymous+ class has no node, so its member climbs ``A::over#1(int)::Runnable``+ to the nearest scope that has one."""cur = sidseen: set[str] = set()while cur not in seen:@@ -712,6 +716,9 @@ class SplitFileDetector(RefactoringDetector):parent = data.get("parent_name")if not parent:return cur+ if is_anonymous_scope(data.get("language"), parent):+ while parent and f"{file_path}::{parent}" not in defined:+ parent = outer_scope(parent)pid = f"{file_path}::{parent}"if pid not in defined or pid == cur:return curdiff --git a/packages/core/src/repowise/core/generation/context/assembler.py b/packages/core/src/repowise/core/generation/context/assembler.pyindex c3df63561..a2f389de3 100644--- a/packages/core/src/repowise/core/generation/context/assembler.py+++ b/packages/core/src/repowise/core/generation/context/assembler.py@@ -1148,6 +1148,7 @@ def _symbol_to_dict(symbol: Symbol) -> dict[str, Any]:"complexity_estimate": symbol.complexity_estimate,"decorators": symbol.decorators,"parent_name": symbol.parent_name,+ "language": symbol.language,"start_line": symbol.start_line,"end_line": symbol.end_line,}diff --git a/packages/core/src/repowise/core/generation/page_generator/structural.py b/packages/core/src/repowise/core/generation/page_generator/structural.pyindex b13e86b37..60d3fcc75 100644--- a/packages/core/src/repowise/core/generation/page_generator/structural.py+++ b/packages/core/src/repowise/core/generation/page_generator/structural.py@@ -29,6 +29,7 @@ from typing import Anyimport structlog+from ...ingestion.lang_helpers.anonymous_classes import is_anonymous_scopefrom ..models import (GENERATION_LEVELS,TEMPLATE_PAGE_CONFIDENCE,@@ -44,7 +45,7 @@ log = structlog.get_logger(__name__)# output without changing any template's bytes: new context fields, a changed# helper, a reordered section. Template edits are picked up automatically# (their source is hashed), so this is only for the cases hashing cannot see.-STRUCTURAL_GENERATION_VERSION = "4"+STRUCTURAL_GENERATION_VERSION = "5"# Keyless stub templates live one directory down so their filenames can match# the prompt templates they stand in for.@@ -426,7 +427,9 @@ def is_public_api(symbol: Mapping[str, Any]) -> bool:Alembic's ``revision`` / ``down_revision`` are 771 of the 878 such symbolsin this repository, and not one of them is something another file calls.The type aliases that share the kind (``SourceFile``, ``ReasoningMode``)- keep their capitals and stay.+ keep their capitals and stay. A member of an anonymous class+ (``Gson::make::Comparator``) is reached through its supertype, never by+ name, and has no type of its own to be listed under.Demoted, not dropped: the caller still names them on the page, so theidentifier stays in ``content`` for the index.@@ -434,6 +437,8 @@ def is_public_api(symbol: Mapping[str, Any]) -> bool:name = str(symbol.get("name") or "")if name.startswith("__") and name.endswith("__"):return False+ if is_anonymous_scope(symbol.get("language"), symbol.get("parent_name")):+ return Falseif symbol.get("kind") == "variable" and not symbol.get("parent_name"):return any(c.isupper() for c in name)return Truediff --git a/packages/core/src/repowise/core/ingestion/lang_helpers/anonymous_classes.py b/packages/core/src/repowise/core/ingestion/lang_helpers/anonymous_classes.pyindex cdb64e5f5..a08f14b80 100644--- a/packages/core/src/repowise/core/ingestion/lang_helpers/anonymous_classes.py+++ b/packages/core/src/repowise/core/ingestion/lang_helpers/anonymous_classes.py@@ -57,10 +57,13 @@ def is_anonymous_member(symbol: Symbol) -> bool:In a language with anonymous classes only such a member has a parent ofseveral segments (``Gson::FILTER::Filter``)."""- config = LANGUAGE_CONFIGS.get(symbol.language)- return bool(- config and config.anonymous_class_types and "::" in (symbol.parent_name or "")- )+ return is_anonymous_scope(symbol.language, symbol.parent_name)+++def is_anonymous_scope(language: str | None, parent_name: str | None) -> bool:+ """:func:`is_anonymous_member` for a graph node or a symbol dict."""+ config = LANGUAGE_CONFIGS.get(language or "")+ return bool(config and config.anonymous_class_types and "::" in (parent_name or ""))def follow_renamed_hosts(symbols: list[Symbol]) -> None:diff --git a/tests/unit/generation/test_structural_pages_read_like_a_wiki.py b/tests/unit/generation/test_structural_pages_read_like_a_wiki.pyindex ca00699cc..b17a6be07 100644--- a/tests/unit/generation/test_structural_pages_read_like_a_wiki.py+++ b/tests/unit/generation/test_structural_pages_read_like_a_wiki.py@@ -477,6 +477,49 @@ class TestOpening:assert "defines `run`" not in pageassert "- `_Impl`\n - `def run(self)`" in page+ @pytest.mark.parametrize(+ ("language", "symbols", "member", "scope"),+ [+ (+ "java",+ [+ ("A", "class", "public class A", None),+ ("over", "method", "public void over(int n)", "A"),+ ("run", "method", "public void run()", "A::over#1(int)::Runnable"),+ ],+ "public void run()",+ "A::over",+ ),+ (+ "kotlin",+ [+ ("untilReady", "function", "fun untilReady()", None),+ ("apply", "method", "override fun apply(): Boolean", "untilReady::Condition"),+ ],+ "override fun apply(): Boolean",+ "untilReady::Condition",+ ),+ ],+ )+ def test_an_anonymous_class_member_lists_no_pseudo_type(+ self, generator, language, symbols, member, scope+ ):+ ctx = _context(+ docstring=None,+ language=language,+ symbols=[+ {**_symbol(n, k, signature=sig, parent_name=p), "language": language}+ for n, k, sig, p in symbols+ ],+ )+ page = render(generator, ctx)++ # Not an API entry of its own nor a member of the type around it, yet+ # still spelled on the page.+ assert scope not in page+ assert f"- `{member}`" not in page+ assert member in page+def test_a_barrel_keeps_the_graph_summary(self, generator):page = render(generator,diff --git a/tests/unit/health/test_refactoring_split_file.py b/tests/unit/health/test_refactoring_split_file.pyindex 80a79a20a..91ba99470 100644--- a/tests/unit/health/test_refactoring_split_file.py+++ b/tests/unit/health/test_refactoring_split_file.py@@ -650,3 +650,36 @@ def test_a_module_only_one_group_leans_on_still_names_it():by_first = {grp["symbols"][0]: grp for grp in out[0].plan["groups"]}assert by_first["fn_0"]["suggested_file"] == "src/Workspaces/utils.cpp"assert by_first["fn_4"]["suggested_file"] == "src/Workspaces/layout.cpp"+++ ("language", "parents", "member", "owner"),+ [+ # Java: ``new Runnable() { void run() }`` inside overload ``over(int)``.+ ("java", {"A": None, "A::over#1(int)": "A"}, ("run", "A::over#1(int)::Runnable"), "A"),+ # Kotlin: ``object : Condition { fun apply() }`` in a top-level function.+ ("kotlin", {"untilReady": None}, ("apply", "untilReady::Condition"), "untilReady"),+ ],+)+def test_an_anonymous_class_member_rolls_up_to_its_named_owner(language, parents, member, owner):+ path = "src/A.x"+ defined = {+ f"{path}::{sid}": {"parent_name": parent, "language": language}+ for sid, parent in parents.items()+ }+ name, scope = member+ member_id = f"{path}::{scope}::{name}"+ defined[member_id] = {"parent_name": scope, "language": language}++ assert SplitFileDetector()._resolve_owner(path, member_id, defined) == f"{path}::{owner}"+++def test_a_scoped_parent_without_a_node_stays_its_own_owner_outside_anonymous_classes():+ path = "src/a.cpp"+ defined = {+ f"{path}::ns": {"parent_name": None, "language": "cpp"},+ f"{path}::ns::Foo::bar": {"parent_name": "ns::Foo", "language": "cpp"},+ }++ owner = SplitFileDetector()._resolve_owner(path, f"{path}::ns::Foo::bar", defined)+ assert owner == f"{path}::ns::Foo::bar"