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(ingestion): stop declaration-only edges forming break_cycle plans (#2983)

Raghav Chamadiya61c0b37e3258
diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py b/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py
index 7ffe26505..1428eb6bf 100644
--- a/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py
+++ b/packages/cli/src/repowise/cli/commands/health_cmd/refactoring_targets.py
@@ -618,7 +618,8 @@ def _plan_detail_console(p: dict) -> list[str]:
cuts = pl.get("cut_edges", [])
out.append(
f" [dim]import cycle of {ev.get('cycle_size')} files "
- f"({ev.get('edge_count')} edges), cut {len(cuts)} edge(s)[/dim]"
+ f"({ev.get('edge_count')} edges), cut {len(cuts)} edge(s)"
+ f"{_idiom_note(pl)}[/dim]"
)
for e in cuts:
out.append(f" [dim]-[/dim] invert {e['from']} -> {e['to']}")
@@ -687,7 +688,10 @@ def _plan_detail_md(p: dict) -> list[str]:
)
elif kind == "break_cycle":
cuts = pl.get("cut_edges", [])
- out.append(f" - import cycle of {ev.get('cycle_size')} files, cut {len(cuts)} edge(s):")
+ out.append(
+ f" - import cycle of {ev.get('cycle_size')} files, cut {len(cuts)} edge(s)"
+ f"{_idiom_note(pl)}:"
+ )
for e in cuts:
out.append(f" - invert {e['from']} -> {e['to']}")
elif kind == "split_file":
@@ -705,6 +709,11 @@ def _plan_detail_md(p: dict) -> list[str]:
return out
+def _idiom_note(pl: dict) -> str:
+ """Marks a cycle the detector judged idiomatic, so its cut reads as optional."""
+ return " (same directory, idiomatic; optional)" if pl.get("idiom") else ""
+
+
def _helper_site(pl: dict) -> str:
"""Where a shared helper should live.
diff --git a/packages/core/src/repowise/core/analysis/health/fix_first/build.py b/packages/core/src/repowise/core/analysis/health/fix_first/build.py
index a99e5ef71..3e7dd2085 100644
--- a/packages/core/src/repowise/core/analysis/health/fix_first/build.py
+++ b/packages/core/src/repowise/core/analysis/health/fix_first/build.py
@@ -599,7 +599,7 @@ def _refactor_step(order: int, step: Mapping[str, Any], plan: Any) -> FixStep:
f"Cut the import of {text.basename(edge['to'])} in "
f"{text.basename(edge['from'])} (line {edge['line']})"
if edge
- else f"Break the import cycle at {text.basename(path)}"
+ else _uncut_cycle_text(path, plan)
)
elif kind == "move_method":
dest = _plan_body(plan).get("to_class") or text.basename(
@@ -614,8 +614,24 @@ def _refactor_step(order: int, step: Mapping[str, Any], plan: Any) -> FixStep:
return FixStep(order, line_text, path, start or step.get("line_start"), mechanical)
+def _uncut_cycle_text(path: str, plan: Any) -> str:
+ """A cycle step with no import line to cut, labelled when it is idiomatic."""
+ if _plan_body(plan).get("idiom"):
+ return (
+ f"Optional: {text.basename(path)} is in an import cycle within one "
+ "directory, which is idiomatic in this language"
+ )
+ return f"Break the import cycle at {text.basename(path)}"
+
+
def _cut_edge(plan: Any) -> dict[str, Any] | None:
- """The first cut edge whose import line is stored."""
+ """The first cut edge whose import line is stored.
+
+ An idiomatic cycle (one directory of a language that compiles mutual
+ references in one pass) has no edge to cut, so it never reads as a must-do.
+ """
+ if _plan_body(plan).get("idiom"):
+ return None
for edge in _plan_body(plan).get("cut_edges") or ():
if isinstance(edge, dict) and edge.get("line") and edge.get("from") and edge.get("to"):
return edge
@@ -833,7 +849,8 @@ def _refactor_measure(
f"{evidence.get('group_count') or 'several'} loosely coupled groups"
)
if kind == "break_cycle" and evidence.get("cycle_size"):
- return f"{name} is in an import cycle of {evidence['cycle_size']} files"
+ idiom = " within one directory (idiomatic)" if evidence.get("idiom") else ""
+ return f"{name} is in an import cycle of {evidence['cycle_size']} files{idiom}"
if kind == "extract_class" and evidence.get("method_count"):
return (
f"{sym}: {evidence['method_count']} methods in "
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/break_cycle.py b/packages/core/src/repowise/core/analysis/health/refactoring/break_cycle.py
index b7b0199cc..6886a95d4 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/break_cycle.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/break_cycle.py
@@ -36,6 +36,14 @@ from .registry import RefactoringDetector, register
_MAX_CYCLE_FILES = 20
_MAX_CUT_EDGES = 4
+# Languages that compile files referencing each other in one pass, so a cycle
+# whose files all sit in one directory (a JVM package, a C# folder that is
+# conventionally one namespace, a Rust module directory) is real but idiomatic:
+# a class and its builder, two entities that point at each other. It is still
+# reported, at low confidence and labelled as such, not as a cut to make.
+_SAME_DIRECTORY_IDIOM_LANGUAGES = frozenset({"java", "kotlin", "scala", "csharp", "rust"})
+_IDIOM_LABEL = "same directory, idiomatic"
+
def _greedy_mfas(members: tuple[str, ...], edges: list[tuple[str, str]]) -> list[tuple[str, str]]:
"""Approximate the minimum feedback arc set with the greedy ordering heuristic.
@@ -94,8 +102,21 @@ def _greedy_mfas(members: tuple[str, ...], edges: list[tuple[str, str]]) -> list
return sorted(set(cut))
+def _split_path(path: str) -> tuple[str, str]:
+ """``(directory, basename)`` of a repo path, either separator."""
+ head, _, tail = path.replace("\\", "/").rpartition("/")
+ return head, tail
+
+
def _basename(path: str) -> str:
- return path.replace("\\", "/").rsplit("/", 1)[-1]
+ return _split_path(path)[1]
+
+
+def _same_directory_idiom(language: str, members: tuple[str, ...]) -> bool:
+ """Whether every member sits in one directory of an idiom language."""
+ if language not in _SAME_DIRECTORY_IDIOM_LANGUAGES:
+ return False
+ return len({_split_path(m)[0] for m in members}) == 1
@register
@@ -138,12 +159,17 @@ class BreakCycleDetector(RefactoringDetector):
# A short cut on a small cycle is the cleanest, highest-confidence
# break; a sprawling component with many back-edges is murkier.
confidence = "high" if len(cut) == 1 and size <= 4 else "medium"
+ label = f"cycle[{size}]"
+ if _same_directory_idiom(ctx.language, members):
+ confidence = "low"
+ plan["idiom"] = evidence["idiom"] = "same_directory"
+ label = f"{label} ({_IDIOM_LABEL})"
cut_label = ", ".join(f"{_basename(u)}->{_basename(v)}" for u, v in cut)
return [
RefactoringSuggestion(
refactoring_type=self.name,
file_path=ctx.file_path,
- target_symbol=f"cycle[{size}]: {cut_label}",
+ target_symbol=f"{label}: {cut_label}",
line_start=None,
line_end=None,
plan=plan,
diff --git a/packages/core/src/repowise/core/ingestion/cohesion.py b/packages/core/src/repowise/core/ingestion/cohesion.py
index 7584437cc..32b85c918 100644
--- a/packages/core/src/repowise/core/ingestion/cohesion.py
+++ b/packages/core/src/repowise/core/ingestion/cohesion.py
@@ -38,6 +38,19 @@ SAME_NAMESPACE_HINT = "same_namespace"
#: target reachable, but no code depends on it, so it cannot close a cycle.
DOC_COMMENT_HINT = "doc_comment"
+#: Hint stamped on a parent module's edge to a child it declares (Rust
+#: ``mod child;``). The declaration places the child in the module tree; it uses
+#: nothing from it, so the child importing its parent is not a cycle. Any real
+#: import or type use between the same two files withdraws the hint
+#: (:func:`withdraw_declaration_hint`).
+MODULE_DECLARATION_HINT = "module_declaration"
+
+#: Hint stamped on a Java, Kotlin or C# ``type_use`` edge whose every type name
+#: the source file declares itself (two classes that each nest a ``Node``, an
+#: ``expect``/``actual`` pair). The language binds those names to the file's own
+#: declaration, so the edge depends on nothing in its target.
+OWN_TYPE_NAME_HINT = "own_type_name"
+
#: Languages whose import statement names a *compilation unit* that is exactly a
#: directory, so a fan-out landing in the importer's own directory landed on its
#: siblings — and a unit cannot depend on itself.
@@ -78,10 +91,18 @@ COHESION_HINTS: frozenset[str] = frozenset(
"header_source_pair", # C/C++ foo.h <-> foo.c
DOC_COMMENT_HINT, # PHP name seen only in a comment: not co-membership,
# but the same split applies (reachability yes, cycle no)
+ MODULE_DECLARATION_HINT, # Rust parent module declaring its child
+ OWN_TYPE_NAME_HINT, # JVM / C# name the source file declares itself
}
)
+def withdraw_declaration_hint(data: dict[str, Any]) -> None:
+ """Drop the module-declaration hint once a real reference shares the edge."""
+ if data.get("hint_source") == MODULE_DECLARATION_HINT:
+ del data["hint_source"]
+
+
def is_cohesion_edge(data: Any) -> bool:
"""True if *data* — a graph edge's attribute dict — is a cohesion edge."""
return data.get("hint_source") in COHESION_HINTS
diff --git a/packages/core/src/repowise/core/ingestion/graph/builder.py b/packages/core/src/repowise/core/ingestion/graph/builder.py
index ba63dfbdd..9d595821c 100644
--- a/packages/core/src/repowise/core/ingestion/graph/builder.py
+++ b/packages/core/src/repowise/core/ingestion/graph/builder.py
@@ -14,7 +14,12 @@ from typing import Any
import networkx as nx
import structlog
-from ..cohesion import SAME_PACKAGE_HINT, UNIT_FANOUT_LANGUAGES
+from ..cohesion import (
+ MODULE_DECLARATION_HINT,
+ SAME_PACKAGE_HINT,
+ UNIT_FANOUT_LANGUAGES,
+ withdraw_declaration_hint,
+)
from ..languages.python_modules import dotted_module_for
from ..models import ParsedFile
from ..resolvers import ResolverContext, resolve_import
@@ -469,6 +474,8 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd
existing = self._graph[path][target].get("imported_names", [])
merged = list(set(existing + imp.imported_names))
self._graph[path][target]["imported_names"] = merged
+ if not imp.is_module_declaration:
+ withdraw_declaration_hint(self._graph[path][target])
else:
edge_attrs: dict[str, Any] = {
"edge_type": "imports",
@@ -487,6 +494,8 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd
and PurePosixPath(target).parent.as_posix() == _own_dir
):
edge_attrs["hint_source"] = SAME_PACKAGE_HINT
+ elif imp.is_module_declaration:
+ edge_attrs["hint_source"] = MODULE_DECLARATION_HINT
self._graph.add_edge(path, target, **edge_attrs)
import_targets[path] = file_imports
lang_import_time[_lang] = lang_import_time.get(_lang, 0.0) + (_t.monotonic() - _t0)
diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.py
index 511ed6335..6a43e0552 100644
--- a/packages/core/src/repowise/core/ingestion/models.py
+++ b/packages/core/src/repowise/core/ingestion/models.py
@@ -255,6 +255,8 @@ class Import:
resolved_file: str | None # absolute path if successfully resolved
bindings: list[NamedBinding] = field(default_factory=list)
is_reexport: bool = False # True for `pub use` (Rust) or re-export patterns
+ # Rust ``mod child;``: declares the child module, uses nothing from it.
+ is_module_declaration: bool = False
@property
def local_names(self) -> list[str]:
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index 9b94f529c..c340048df 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -1117,7 +1117,8 @@ def _generic_import(
stmt_node: Node, module_text: str, raw: str, language: str, src: str
) -> Import:
"""The single Import of a statement no language-specific shape claims."""
- if language == "rust" and stmt_node.type == "mod_item":
+ is_module_declaration = language == "rust" and stmt_node.type == "mod_item"
+ if is_module_declaration:
module_text = _rust_mod_path_attribute(stmt_node, src) or module_text
# JVM wildcard imports: the query captures the scoped identifier only,
@@ -1142,6 +1143,7 @@ def _generic_import(
resolved_file=None,
bindings=bindings,
is_reexport=_is_reexport_import(stmt_node, raw, language),
+ is_module_declaration=is_module_declaration,
)
diff --git a/packages/core/src/repowise/core/ingestion/type_ref_resolution.py b/packages/core/src/repowise/core/ingestion/type_ref_resolution.py
index 00eb55fd3..241618aa1 100644
--- a/packages/core/src/repowise/core/ingestion/type_ref_resolution.py
+++ b/packages/core/src/repowise/core/ingestion/type_ref_resolution.py
@@ -48,6 +48,7 @@ from typing import TYPE_CHECKING, Any
import structlog
+from .cohesion import OWN_TYPE_NAME_HINT, withdraw_declaration_hint
from .models import ParsedFile
if TYPE_CHECKING:
@@ -96,6 +97,68 @@ def _build_defined_name_index(graph: nx.DiGraph) -> dict[str, set[str]]:
return index
+def _stamp_local_type_uses(graph: nx.DiGraph, from_path: str, names: set[str]) -> None:
+ """Record type names a file references from its own declarations.
+
+ No self-loop edge is emitted for them, so the dead-code analyzer reads this
+ node attribute instead to see a type used only inside its own file as live.
+ """
+ if not names or not graph.has_node(from_path):
+ return
+ existing = graph.nodes[from_path].get("local_type_uses")
+ if existing is None:
+ graph.nodes[from_path]["local_type_uses"] = set(names)
+ else:
+ existing.update(names)
+
+
+# Languages whose compilers bind a bare type name to a type the referencing
+# file declares (top-level or nested) before any same-package, same-namespace
+# or imported type of that name. A JVM policy class with its own nested
+# ``Node`` means that ``Node``, never a sibling's; a Kotlin ``expect class`` and
+# its platform ``actual`` each name their own declaration; a C# class naming
+# itself means itself, not a same-named class in another project. The
+# strategies below resolve such names to another file anyway, which minted
+# edges in both directions between files that never name each other.
+#
+# Those edges are only kept out of cycle detection (see :data:`OWN_TYPE_NAME_HINT`):
+# call resolution and dead code read them as scope, and dropping them moved
+# call edges onto worse candidates. Upgrade path: resolve own names to the file
+# itself in every strategy once call resolution no longer leans on them.
+_OWN_TYPE_FIRST_LANGUAGES: frozenset[str] = frozenset({"java", "kotlin", "csharp"})
+
+# Symbol kinds that declare a type name. Properties and fields are left out on
+# purpose: C#'s ``public Color Color { get; }`` names the type ``Color`` from
+# another file through a member of the same name.
+_TYPE_DECLARATION_KINDS: frozenset[str] = frozenset(
+ {"class", "interface", "enum", "struct", "trait", "type_alias"}
+)
+
+
+def _mark_own_name_edges(parsed: ParsedFile, graph: nx.DiGraph) -> None:
+ """Stamp each ``type_use`` edge whose every type name *parsed* declares itself.
+
+ Such an edge carries no reference the file could not satisfy on its own,
+ so it cannot close a dependency cycle. An edge with one name the file does
+ not declare is real evidence and is left alone.
+ """
+ own = {s.name for s in parsed.symbols if s.name and s.kind in _TYPE_DECLARATION_KINDS}
+ src = parsed.file_info.path
+ if not own or not graph.has_node(src):
+ return
+ for _, _, data in graph.out_edges(src, data=True):
+ if _names_only_own_types(data, own):
+ data["hint_source"] = OWN_TYPE_NAME_HINT
+
+
+def _names_only_own_types(data: dict[str, Any], own: set[str]) -> bool:
+ """An unstamped ``type_use`` edge whose type names are all in *own*."""
+ if data.get("edge_type") != "type_use" or "hint_source" in data:
+ return False
+ names = data.get("type_uses")
+ return bool(names) and own.issuperset(names)
+
+
# ---------------------------------------------------------------------------
# Strategy: C# / .NET
# ---------------------------------------------------------------------------
@@ -364,12 +427,7 @@ def _resolve_go_type_refs(
if name in defined_names.get(from_path, _EMPTY_NAMES):
same_file_refs.add(name)
- if same_file_refs and graph.has_node(from_path):
- existing = graph.nodes[from_path].get("local_type_uses")
- if existing is None:
- graph.nodes[from_path]["local_type_uses"] = same_file_refs
- else:
- existing.update(same_file_refs)
+ _stamp_local_type_uses(graph, from_path, same_file_refs)
return emitted
@@ -506,12 +564,7 @@ def _resolve_c_type_refs(
type_name=name, origin=ref.origin)
emitted += 1
- if same_file_refs and graph.has_node(from_path):
- existing = graph.nodes[from_path].get("local_type_uses")
- if existing is None:
- graph.nodes[from_path]["local_type_uses"] = same_file_refs
- else:
- existing.update(same_file_refs)
+ _stamp_local_type_uses(graph, from_path, same_file_refs)
return emitted
@@ -636,12 +689,7 @@ def _resolve_ts_type_refs(
)
emitted += 1
- if same_file_refs and graph.has_node(from_path):
- existing = graph.nodes[from_path].get("local_type_uses")
- if existing is None:
- graph.nodes[from_path]["local_type_uses"] = same_file_refs
- else:
- existing.update(same_file_refs)
+ _stamp_local_type_uses(graph, from_path, same_file_refs)
return emitted
@@ -802,6 +850,8 @@ def resolve_type_refs(
if strategy is None:
continue
emitted = strategy(parsed, ctx, graph, defined_names)
+ if lang in _OWN_TYPE_FIRST_LANGUAGES:
+ _mark_own_name_edges(parsed, graph)
if emitted:
counts[lang] = counts.get(lang, 0) + emitted
if counts:
@@ -860,6 +910,7 @@ def _add_or_merge_type_use_edge(
# are genuinely import-linked however the earlier references were found.
if widens_scope:
data.pop("no_scope_widening", None)
+ withdraw_declaration_hint(data)
return
attrs: dict[str, Any] = {
"edge_type": "type_use",
diff --git a/tests/unit/cli/test_refactoring_targets_render.py b/tests/unit/cli/test_refactoring_targets_render.py
index 87cef3243..b48f604d7 100644
--- a/tests/unit/cli/test_refactoring_targets_render.py
+++ b/tests/unit/cli/test_refactoring_targets_render.py
@@ -237,3 +237,11 @@ def test_an_advisory_finding_beside_a_real_one_keeps_the_real_lead(capsys):
_render_refactoring_targets(metrics, findings, [], fmt="json")
out = json.loads(capsys.readouterr().out)
assert [t["primary_biomarker"] for t in out["targets"]] == ["complex_method"]
+
+
+def test_an_idiomatic_cycle_is_marked_optional_in_the_detail(capsys):
+ cycle = _break_cycle()
+ cycle.plan["idiom"] = "same_directory"
+ _render_refactoring_targets([], [], [cycle], fmt="md")
+ text = capsys.readouterr().out
+ assert "(same directory, idiomatic; optional)" in text
diff --git a/tests/unit/health/test_fix_first_precision.py b/tests/unit/health/test_fix_first_precision.py
index bdd8c81a9..51a14282a 100644
--- a/tests/unit/health/test_fix_first_precision.py
+++ b/tests/unit/health/test_fix_first_precision.py
@@ -250,6 +250,15 @@ def test_break_cycle_needs_the_import_line() -> None:
assert lined.lead.action.steps[0].text == "Cut the import of b.py in a.py (line 7)"
+def test_an_idiomatic_cycle_is_never_a_cut_to_make() -> None:
+ edges = [{"from": "src/a.py", "to": "src/b.py", "line": 7}]
+ plan = {"cut_edges": edges, "idiom": "same_directory"}
+ assert _refactor_queue("break_cycle", plan).totals.excluded["no_concrete_step"] == 1
+ text = _step_text("break_cycle", plan)
+ assert text.startswith("Optional:") and "idiomatic" in text
+ assert "Cut the import" not in text
+
+
def test_split_file_needs_named_groups() -> None:
unnamed = {"groups": [{"symbols": ["a", "b"]}]}
assert _refactor_queue("split_file", unnamed).totals.excluded["no_concrete_step"] == 1
diff --git a/tests/unit/health/test_refactoring_break_cycle.py b/tests/unit/health/test_refactoring_break_cycle.py
index 31735444f..3ea69821a 100644
--- a/tests/unit/health/test_refactoring_break_cycle.py
+++ b/tests/unit/health/test_refactoring_break_cycle.py
@@ -241,3 +241,33 @@ def test_php_use_both_ways_is_a_cycle(tmp_path):
"src/Identity/HostIdentity.php",
"src/Validation/HostValidator.php",
]
+
+
+def _detect_lang(g: nx.DiGraph, file_path: str, language: str) -> list:
+ idx = build_file_scc_index(g)
+ ctx = RefactoringContext(
+ file_path=file_path, language=language, nloc=50, graph=g, file_scc=idx.get(file_path)
+ )
+ return [s for s in detect_refactorings(ctx) if s.refactoring_type == "break_cycle"]
+
+
+def test_same_directory_java_cycle_is_kept_but_demoted():
+ a, b = "src/com/acme/Project.java", "src/com/acme/User.java"
+ out = _detect_lang(_import_graph([(a, b), (b, a)]), a, "java")
+ assert len(out) == 1
+ assert out[0].confidence == "low"
+ assert out[0].evidence["idiom"] == out[0].plan["idiom"] == "same_directory"
+ assert out[0].target_symbol.startswith("cycle[2] (same directory, idiomatic): ")
+
+
+def test_cross_package_java_cycle_is_not_demoted():
+ a, b = "src/com/acme/api/Client.java", "src/com/acme/core/Engine.java"
+ out = _detect_lang(_import_graph([(a, b), (b, a)]), a, "java")
+ assert out[0].confidence == "high"
+ assert "idiom" not in out[0].evidence
+
+
+def test_same_directory_python_cycle_is_not_demoted():
+ # A Python import cycle fails at import time; it is never an idiom.
+ out = _detect_lang(_import_graph([("pkg/a.py", "pkg/b.py"), ("pkg/b.py", "pkg/a.py")]), "pkg/a.py", "python")
+ assert out[0].confidence == "high"
diff --git a/tests/unit/ingestion/test_declaration_edges_not_cycles.py b/tests/unit/ingestion/test_declaration_edges_not_cycles.py
new file mode 100644
index 000000000..3f96cf671
--- /dev/null
+++ b/tests/unit/ingestion/test_declaration_edges_not_cycles.py
@@ -0,0 +1,173 @@
+"""Edges that come from a declaration, not a dependency, must not close a cycle.
+
+Two shapes produced phantom break-cycle plans:
+
+* A type name the referencing file declares itself (a nested ``Node`` in two
+ sibling Java policies, a Kotlin ``expect``/``actual`` pair, two C# projects
+ each with a ``Contributor`` class) was resolved to the *other* file, minting
+ edges in both directions between files that never name each other. The
+ edges stay (call resolution and dead code read them) but are stamped so the
+ cycle views skip them.
+* A Rust parent's ``mod child;`` was an ``imports`` edge to the child, so the
+ child importing its parent read as a two-file cycle.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import networkx as nx
+
+from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder
+from repowise.core.ingestion.cohesion import MODULE_DECLARATION_HINT, OWN_TYPE_NAME_HINT
+
+
+def _build(repo: Path, files: dict[str, str]) -> GraphBuilder:
+ 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()))
+ builder.build()
+ return builder
+
+
+def _cycles(builder: GraphBuilder) -> list[set[str]]:
+ graph = builder.cycle_subgraph()
+ return [set(c) for c in nx.strongly_connected_components(graph) if len(c) > 1]
+
+
+_PKG = "src/main/java/com/acme/"
+
+
+class TestJvmOwnTypeFirst:
+ def test_sibling_nested_types_of_one_name_are_not_a_cycle(self, tmp_path: Path) -> None:
+ b = _build(
+ tmp_path,
+ {
+ _PKG + "LruPolicy.java": (
+ "package com.acme;\npublic class LruPolicy {\n"
+ " Node head;\n static final class Node { Node next; }\n}\n"
+ ),
+ _PKG + "FifoPolicy.java": (
+ "package com.acme;\npublic class FifoPolicy {\n"
+ " Node head;\n static final class Node { Node next; }\n}\n"
+ ),
+ },
+ )
+ g = b.graph()
+ for src, dst in (("LruPolicy", "FifoPolicy"), ("FifoPolicy", "LruPolicy")):
+ edge = g.get_edge_data(_PKG + src + ".java", _PKG + dst + ".java")
+ assert edge["hint_source"] == OWN_TYPE_NAME_HINT, edge
+ assert _cycles(b) == []
+
+ def test_real_same_package_mutual_reference_is_still_a_cycle(self, tmp_path: Path) -> None:
+ b = _build(
+ tmp_path,
+ {
+ _PKG + "Project.java": "package com.acme;\npublic class Project { User owner; }\n",
+ _PKG + "User.java": "package com.acme;\npublic class User { Project project; }\n",
+ },
+ )
+ assert _cycles(b) == [{_PKG + "Project.java", _PKG + "User.java"}]
+
+ def test_own_nested_type_does_not_hide_a_sibling_type(self, tmp_path: Path) -> None:
+ b = _build(
+ tmp_path,
+ {
+ _PKG + "Cache.java": (
+ "package com.acme;\npublic class Cache {\n"
+ " Stats stats;\n static final class Node {}\n}\n"
+ ),
+ _PKG + "Stats.java": "package com.acme;\npublic class Stats {}\n",
+ },
+ )
+ edge = b.graph().get_edge_data(_PKG + "Cache.java", _PKG + "Stats.java")
+ assert edge is not None and "hint_source" not in edge
+
+ def test_kotlin_expect_and_actual_are_not_a_cycle(self, tmp_path: Path) -> None:
+ common = "src/commonMain/kotlin/io/acme/ByteOrder.kt"
+ jvm = "src/jvmMain/kotlin/io/acme/ByteOrderJvm.kt"
+ b = _build(
+ tmp_path,
+ {
+ common: (
+ "package io.acme\n"
+ "expect class ByteOrder {\n fun flip(): ByteOrder\n}\n"
+ ),
+ jvm: (
+ "package io.acme\n"
+ "actual class ByteOrder {\n actual fun flip(): ByteOrder = this\n}\n"
+ ),
+ },
+ )
+ assert _cycles(b) == []
+
+
+class TestCSharpOwnTypeFirst:
+ def test_same_named_classes_in_two_projects_are_not_a_cycle(self, tmp_path: Path) -> None:
+ csproj = '<Project Sdk="Microsoft.NET.Sdk"></Project>\n'
+ src = "src/Core/Contributor.cs"
+ tpl = "template/Core/Contributor.cs"
+ body = (
+ "namespace {ns};\npublic class Contributor {{\n"
+ " public Contributor(string name) {{}}\n"
+ " public static Contributor Create(Contributor other) => other;\n}}\n"
+ )
+ b = _build(
+ tmp_path,
+ {
+ "src/Core/Core.csproj": csproj,
+ "template/Core/Core.csproj": csproj,
+ src: body.format(ns="Acme.Core"),
+ tpl: body.format(ns="Template.Core"),
+ },
+ )
+ g = b.graph()
+ for a, z in ((src, tpl), (tpl, src)):
+ edge = g.get_edge_data(a, z)
+ assert edge is None or edge.get("hint_source") == OWN_TYPE_NAME_HINT, edge
+ assert _cycles(b) == []
+
+
+class TestRustModuleDeclaration:
+ def test_parent_declaring_a_child_is_not_a_cycle(self, tmp_path: Path) -> None:
+ b = _build(
+ tmp_path,
+ {
+ "Cargo.toml": '[package]\nname = "demo"\nversion = "0.1.0"\n',
+ "src/lib.rs": "pub mod ser;\n",
+ "src/ser/mod.rs": "mod fmt;\npub trait Serializer {}\n",
+ "src/ser/fmt.rs": (
+ "use crate::ser::Serializer;\npub struct Fmt;\nimpl Serializer for Fmt {}\n"
+ ),
+ },
+ )
+ edge = b.graph().get_edge_data("src/ser/mod.rs", "src/ser/fmt.rs")
+ assert edge is not None, "the declaration edge stays for reachability"
+ assert edge.get("hint_source") == MODULE_DECLARATION_HINT
+ assert _cycles(b) == []
+
+ def test_a_reexport_from_the_child_withdraws_the_exemption(self, tmp_path: Path) -> None:
+ b = _build(
+ tmp_path,
+ {
+ "Cargo.toml": '[package]\nname = "demo"\nversion = "0.1.0"\n',
+ "src/lib.rs": "pub mod ser;\n",
+ "src/ser/mod.rs": (
+ "mod impossible;\npub use self::impossible::Impossible;\n"
+ "pub trait Serializer {}\n"
+ ),
+ "src/ser/impossible.rs": (
+ "use crate::ser::Serializer;\npub struct Impossible;\n"
+ "impl Serializer for Impossible {}\n"
+ ),
+ },
+ )
+ edge = b.graph().get_edge_data("src/ser/mod.rs", "src/ser/impossible.rs")
+ assert edge is not None
+ assert edge.get("hint_source") != MODULE_DECLARATION_HINT
+ assert _cycles(b) == [{"src/ser/mod.rs", "src/ser/impossible.rs"}]