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(health): count implicit member access in class cohesion (#2908)

Raghav Chamadiyab0669f76092c
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/low_cohesion.py b/packages/core/src/repowise/core/analysis/health/biomarkers/low_cohesion.py
index 7da461350..13655e391 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/low_cohesion.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/low_cohesion.py
@@ -17,6 +17,7 @@ signal), so this biomarker simply doesn't fire there — never falsely.
from __future__ import annotations
+from ..complexity.class_analysis import cohesion_applies
from ..models import Severity
from .base import BiomarkerResult, FileContext
@@ -31,21 +32,15 @@ class LowCohesionDetector:
def detect(self, ctx: FileContext) -> list[BiomarkerResult]:
out: list[BiomarkerResult] = []
+ if not cohesion_applies(ctx.file_path, ctx.language):
+ return out
for cls in ctx.class_metrics:
if cls.lcom4 < 2 or cls.method_count < self._MIN_METHODS:
continue
-
- if cls.lcom4 >= 4 and cls.method_count >= 15:
- severity = Severity.CRITICAL
- elif cls.lcom4 >= 3 or cls.method_count >= 20:
- severity = Severity.HIGH
- else:
- severity = Severity.MEDIUM
-
out.append(
BiomarkerResult(
biomarker_type=self.name,
- severity=severity,
+ severity=_severity(cls.lcom4, cls.method_count),
function_name=cls.name,
line_start=cls.start_line,
line_end=cls.end_line,
@@ -65,4 +60,12 @@ class LowCohesionDetector:
return out
+def _severity(lcom4: int, method_count: int) -> Severity:
+ if lcom4 >= 4 and method_count >= 15:
+ return Severity.CRITICAL
+ if lcom4 >= 3 or method_count >= 20:
+ return Severity.HIGH
+ return Severity.MEDIUM
+
+
BIOMARKER = LowCohesionDetector()
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/class_analysis.py b/packages/core/src/repowise/core/analysis/health/complexity/class_analysis.py
index 04eed012a..ae8394698 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/class_analysis.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/class_analysis.py
@@ -6,24 +6,71 @@ cohesion metric: connected components over the methods, where two methods are
linked if they share an instance member or one calls the other. The safety
valve returns ``1`` ("no signal") when no instance-member references are
detected, so an unmapped language never produces a false ``low_cohesion`` hit.
+
+A member reference is explicit (``self.x`` / ``this.x``) or, for a language
+whose map names its field declarations, implicit: a bare name that resolves to
+a field declared in the class body or to a sibling method, and that no
+parameter or local of the method rebinds. A C# ``partial`` class is never
+scored, because its other parts live in files this pass does not see, and in
+those languages only components that hold state count (``_stateful_groups``).
"""
from __future__ import annotations
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, NamedTuple
+from ....test_paths import is_test_related_path
from .ast_utils import _IDENTIFIER_SUFFIX, _find_name
-from .languages import LanguageNodeMap
+from .languages import LanguageNodeMap, get_language_map
from .models import ClassComplexity, CohesionGroup, FunctionComplexity
from .nloc import CodeLineIndex
if TYPE_CHECKING:
+ from collections.abc import Iterator
+
from tree_sitter import Node
_PROP_FIELD_NAMES = ("property", "attribute", "field", "name")
# ``expression`` is C#'s receiver field on ``member_access_expression`` (its
# ``this`` token is unnamed, so the positional fallback would pick the member).
_OBJECT_FIELD_NAMES = ("object", "value", "argument", "operand", "expression")
+# Fields of a binding node that hold the bound name, in probe order.
+_BINDING_NAME_FIELDS = ("name", "declarator", "left", "parameters")
+# A method's signature children: names there declare, they do not reference.
+_SIGNATURE_FIELDS = frozenset({"name", "declarator", "type", "returns"})
+# Declaration words that make a member class-level rather than instance state.
+_STATIC_WORDS = frozenset({"static", "const"})
+
+
+class _ClassBody(NamedTuple):
+ """The direct members of one class node."""
+
+ methods: list[Node]
+ field_decls: list[Node]
+ nested: list[Node] # nested classes
+
+
+class _MemberRefs(NamedTuple):
+ """Each method's member references, the methods the class body only
+ declares (a C++ method defined out of line: a call target, never a field),
+ and the indices of the methods that are contracts rather than behaviour
+ (constructors and overrides)."""
+
+ per_method: list[set[str]]
+ out_of_line: frozenset[str]
+ contracts: frozenset[int] = frozenset()
+
+
+def cohesion_applies(file_path: str, language: str) -> bool:
+ """Whether class cohesion findings and splits apply to *file_path*.
+
+ Not in test files of implicit-receiver languages: a test class groups its
+ tests by the fixtures they share (a date fixture pair, a datetime pair),
+ which reads as a split but is how the tests are meant to be organised.
+ """
+ lmap = get_language_map(language)
+ implicit = lmap is not None and bool(lmap.field_decl_kinds)
+ return not (implicit and is_test_related_path(file_path, language))
def _class_name(node: Node) -> str:
@@ -40,55 +87,152 @@ def _class_name(node: Node) -> str:
return _find_name(node)
-def _collect_class_methods(class_node: Node, lmap: LanguageNodeMap) -> list[Node]:
- """Direct method nodes of *class_node*.
+def _text(node: Node) -> str:
+ return node.text.decode("utf-8", errors="replace") if node.text is not None else ""
+
- Stops at nested classes (their methods belong to the inner class) and
- does not descend into a method body (nested local defs roll up into
- the method, mirroring ``_collect_function_nodes``).
+def _collect_class_body(class_node: Node, lmap: LanguageNodeMap) -> _ClassBody:
+ """Direct method, field-declaration and nested-class nodes of *class_node*.
+
+ Stops at nested types (their members are not ours) and does not descend
+ into a method body (nested local defs roll up into the method, mirroring
+ ``_collect_function_nodes``).
"""
- methods: list[Node] = []
+ body = _ClassBody([], [], [])
stack: list[Node] = list(class_node.children)
while stack:
node = stack.pop()
if node.type in lmap.class_kinds:
- continue # nested class — its methods are not ours
- if node.type in lmap.function_kinds:
- methods.append(node)
- continue # don't descend into the method body
- for child in node.children:
- stack.append(child)
- return methods
+ body.nested.append(node)
+ elif node.type in lmap.function_kinds:
+ body.methods.append(node)
+ elif node.type in lmap.field_decl_kinds:
+ body.field_decls.append(node)
+ elif node.type not in lmap.nested_type_kinds:
+ stack.extend(node.children)
+ return body
+
+
+def _decl_words(node: Node) -> set[str]:
+ """Keyword and modifier words directly on a declaration (``static``,
+ ``partial``, ``override``, Kotlin ``val``)."""
+ words: set[str] = set()
+ for child in node.children:
+ if (
+ not child.is_named
+ or "modifier" in child.type
+ or child.type in ("storage_class_specifier", "binding_pattern_kind")
+ ):
+ words.update(_text(child).split())
+ return words
+
+
+def _next_in_chain(node: Node, lmap: LanguageNodeMap) -> Node | None:
+ nxt = node.child_by_field_name("declarator") or node.child_by_field_name("name")
+ if nxt is not None:
+ return nxt
+ return next(
+ (
+ c
+ for c in node.named_children
+ if c.type in lmap.identifier_kinds or c.type.endswith("declarator")
+ ),
+ None,
+ )
+
+
+def _unwrap_name(node: Node | None, lmap: LanguageNodeMap) -> tuple[Node | None, bool]:
+ """Follow a declarator chain (``*p``, ``&r``, ``a[3]``, ``x = 1``, ``f()``)
+ down to its name token. The flag says the chain declared a function."""
+ is_function = False
+ for _ in range(8):
+ if node is None or node.type in lmap.identifier_kinds:
+ return node, is_function
+ is_function = is_function or node.type == "function_declarator"
+ node = _next_in_chain(node, lmap)
+ return None, is_function
+
+
+def _variable_declarators(node: Node) -> list[Node]:
+ """C# wraps declarators in a ``variable_declaration``; Kotlin's holds the
+ name directly."""
+ if node.type not in ("variable_declarator", "variable_declaration"):
+ return []
+ inner = [c for c in node.named_children if c.type == "variable_declarator"]
+ return inner or [node]
-def _self_member_name(node: Node, lmap: LanguageNodeMap) -> str | None:
- """Extract ``member`` from a ``self.member`` / ``this.member`` access.
+def _declaration_targets(decl: Node, lmap: LanguageNodeMap) -> list[Node]:
+ """The declarator nodes of one class-body declaration. A Kotlin
+ constructor parameter is its own first name token (later ones are the
+ type and default value)."""
+ targets = decl.children_by_field_name("declarator") or decl.children_by_field_name("name")
+ if not targets:
+ targets = [d for child in decl.named_children for d in _variable_declarators(child)]
+ return targets or [c for c in decl.named_children if c.type in lmap.identifier_kinds][:1]
- Returns the member name when the receiver token is one of the
- language's ``self_identifiers``; otherwise ``None`` (so ``other.x`` and
- ``a.b.c``'s outer hops are ignored — only direct instance access
- counts toward cohesion).
+
+def _declared_members(decl: Node, lmap: LanguageNodeMap) -> tuple[list[str], list[str]]:
+ """``(fields, methods)`` one class-body declaration names.
+
+ Static and const members are class-level, not instance state, and a Kotlin
+ constructor parameter is a property only with ``val`` / ``var``. A C++
+ declarator that is a function is a method declared here and defined out
+ of line.
"""
- obj: Node | None = None
+ words = _decl_words(decl)
+ if words & _STATIC_WORDS or (decl.type == "class_parameter" and not words & {"val", "var"}):
+ return [], []
+ fields: list[str] = []
+ methods: list[str] = []
+ for target in _declaration_targets(decl, lmap):
+ name, is_function = _unwrap_name(target, lmap)
+ if name is not None:
+ (methods if is_function else fields).append(_text(name))
+ return fields, methods
+
+
+def _bound_names(node: Node, lmap: LanguageNodeMap) -> list[str]:
+ """Names a parameter or local binding node introduces."""
+ for field_name in _BINDING_NAME_FIELDS:
+ targets = node.children_by_field_name(field_name)
+ if targets:
+ names = (_unwrap_name(t, lmap)[0] for t in targets)
+ return [_text(n) for n in names if n is not None]
+ named = node.named_children
+ if not named:
+ return [_text(node)] # C#'s ``x => ...`` parameter is a bare token
+ return [_text(c) for c in named if c.type in lmap.identifier_kinds]
+
+
+def _receiver(node: Node) -> Node | None:
+ """The receiver child of a member-access node."""
for field_name in _OBJECT_FIELD_NAMES:
obj = node.child_by_field_name(field_name)
if obj is not None:
- break
- if obj is None:
- obj = next((c for c in node.children if c.is_named), None)
+ return obj
+ return next((c for c in node.children if c.is_named), None)
+
- prop: Node | None = None
+def _member(node: Node) -> Node | None:
+ """The member-name child of a member-access node."""
for field_name in _PROP_FIELD_NAMES:
prop = node.child_by_field_name(field_name)
if prop is not None:
- break
- if prop is None:
- named = [c for c in node.children if c.is_named]
- prop = next(
- (c for c in reversed(named) if c.type.endswith(_IDENTIFIER_SUFFIX)),
- None,
- )
+ return prop
+ named = [c for c in node.children if c.is_named]
+ return next((c for c in reversed(named) if c.type.endswith(_IDENTIFIER_SUFFIX)), None)
+
+
+def _self_member_name(node: Node, lmap: LanguageNodeMap) -> str | None:
+ """Extract ``member`` from a ``self.member`` / ``this.member`` access.
+ Returns the member name when the receiver token is one of the
+ language's ``self_identifiers``; otherwise ``None`` (so ``other.x`` and
+ ``a.b.c``'s outer hops are ignored — only direct instance access
+ counts toward cohesion).
+ """
+ obj, prop = _receiver(node), _member(node)
if obj is None or prop is None or obj is prop:
return None
if obj.text is None or prop.text is None:
@@ -123,6 +267,174 @@ def _collect_self_members(method_node: Node, lmap: LanguageNodeMap) -> set[str]:
return members
+def _foreign_member_id(node: Node, lmap: LanguageNodeMap) -> int | None:
+ """The id of the member-name child of ``other.name``: that name belongs
+ to another object, never to the enclosing class."""
+ if node.type not in lmap.member_access_kinds:
+ return None
+ obj, prop = _receiver(node), _member(node)
+ if obj is None or prop is None or obj.id == prop.id:
+ return None # a bare call (``id()``) has no receiver
+ return prop.id
+
+
+def _body_nodes(method_node: Node, lmap: LanguageNodeMap) -> Iterator[tuple[Node, bool]]:
+ """Every node under *method_node* with whether it sits in the signature,
+ skipping nested classes and the member side of ``other.name``."""
+ stack: list[tuple[Node, bool]] = [
+ (child, method_node.field_name_for_child(i) in _SIGNATURE_FIELDS)
+ for i, child in enumerate(method_node.children)
+ ]
+ while stack:
+ node, in_signature = stack.pop()
+ if node.type in lmap.class_kinds:
+ continue # nested class has its own members
+ yield node, in_signature
+ skip = _foreign_member_id(node, lmap)
+ stack.extend((child, in_signature) for child in node.children if child.id != skip)
+
+
+def _collect_implicit_members(
+ method_node: Node, lmap: LanguageNodeMap, declared: frozenset[str]
+) -> set[str]:
+ """Bare names in *method_node* that resolve to a declared member.
+
+ A name counts when it is in *declared* (the class's fields and methods),
+ is not the member side of ``other.name``, and no parameter or local
+ anywhere in the method binds it. Shadowing is method-wide rather than
+ scoped, which can only drop an edge, never invent one.
+ """
+ refs: set[str] = set()
+ bound: set[str] = set()
+ for node, in_signature in _body_nodes(method_node, lmap):
+ if node.type in lmap.binding_kinds:
+ bound.update(_bound_names(node, lmap))
+ elif node.type in lmap.identifier_kinds and not in_signature:
+ refs.add(_text(node))
+ return (refs & declared) - bound
+
+
+def _member_links(
+ named_decls: list[tuple[Node, list[str]]],
+ nested: list[Node],
+ lmap: LanguageNodeMap,
+ declared: frozenset[str],
+) -> dict[str, set[str]]:
+ """Members a reference to one member also reaches.
+
+ A field initializer or computed property reaches what it reads. A nested
+ class that reads several outer members ties them together: the outer
+ methods that build or call it work on all of them, which no method body
+ shows.
+ """
+ links: dict[str, set[str]] = {}
+ for decl, fields in named_decls:
+ reads = _collect_implicit_members(decl, lmap, declared) - set(fields)
+ for name in fields if reads else ():
+ links.setdefault(name, set()).update(reads)
+ for inner in nested:
+ reads = _collect_implicit_members(inner, lmap, declared)
+ for name in reads:
+ links.setdefault(name, set()).update(reads - {name})
+ return links
+
+
+def _method_refs(
+ node: Node,
+ explicit: set[str],
+ lmap: LanguageNodeMap,
+ declared: frozenset[str],
+ links: dict[str, set[str]],
+) -> set[str]:
+ """One method's references: explicit, implicit, and what they link to."""
+ if "static" in _decl_words(node):
+ return set()
+ members = explicit | _collect_implicit_members(node, lmap, declared)
+ for name in [m for m in members if m in links]:
+ members |= links[name]
+ return members
+
+
+def _class_member_refs(
+ body: _ClassBody,
+ method_fcs: list[FunctionComplexity],
+ lmap: LanguageNodeMap,
+ class_name: str,
+) -> _MemberRefs:
+ """Each method's member references.
+
+ Explicit ``self.x`` references always count. Where the map names field
+ declarations, a bare name that resolves to a declared field or method
+ counts too, and a reference reaches whatever ``_member_links`` ties to
+ it. A static method has no instance: a bare name in it (an object
+ initializer in a factory) is never this object's state.
+ """
+ explicit = [_collect_self_members(node, lmap) for node in body.methods]
+ if not lmap.field_decl_kinds:
+ return _MemberRefs(explicit, frozenset())
+ fields: set[str] = set()
+ out_of_line: set[str] = set()
+ named_decls: list[tuple[Node, list[str]]] = []
+ for decl in body.field_decls:
+ decl_fields, decl_methods = _declared_members(decl, lmap)
+ fields.update(decl_fields)
+ out_of_line.update(decl_methods)
+ named_decls.append((decl, decl_fields))
+ declared = frozenset(fields | out_of_line | {fc.name for fc in method_fcs})
+ links = _member_links(named_decls, body.nested, lmap, declared)
+ per_method = [
+ _method_refs(node, members, lmap, declared, links)
+ for node, members in zip(body.methods, explicit, strict=True)
+ ]
+ return _MemberRefs(
+ per_method, frozenset(out_of_line), _contract_indices(body.methods, method_fcs, class_name)
+ )
+
+
+def _contract_indices(
+ method_nodes: list[Node], method_fcs: list[FunctionComplexity], class_name: str
+) -> frozenset[int]:
+ """Indices of the constructors and overrides among *method_nodes*."""
+ return frozenset(
+ i
+ for i, (node, fc) in enumerate(zip(method_nodes, method_fcs, strict=True))
+ if fc.name == class_name or _is_override(node)
+ )
+
+
+def _is_override(method_node: Node) -> bool:
+ """Java ``@Override``, C#/Kotlin ``override``, C++ ``override`` / ``final``."""
+ if _decl_words(method_node) & {"@Override", "override"}:
+ return True
+ declarator = method_node.child_by_field_name("declarator")
+ while declarator is not None and declarator.type != "function_declarator":
+ declarator = declarator.child_by_field_name("declarator") # ``T* f() override``
+ return declarator is not None and any(
+ c.type == "virtual_specifier" for c in declarator.children
+ )
+
+
+def _stateful_groups(
+ indexed_groups: list[tuple[list[int], CohesionGroup]], contracts: frozenset[int]
+) -> list[CohesionGroup]:
+ """The components that are a responsibility of their own.
+
+ Where member access is implicit the graph cannot see inherited members,
+ an outer instance or a base constructor, so a method that touches no
+ visible state is unplaced rather than a split. A component counts when it
+ spans at least two fields (accessors over one field are how a data class
+ exposes state) and is not made only of constructors and overrides. A
+ constructor sets fields that properties or out-of-line methods this pass
+ cannot place may read, and ``toString`` / ``Equals`` are contracts; neither
+ is a class to extract.
+ """
+ return [
+ group
+ for idxs, group in indexed_groups
+ if len(group.fields) >= 2 and not contracts.issuperset(idxs)
+ ]
+
+
def _tcc(field_sets: list[set[str]]) -> float:
"""Tight Class Cohesion (Bieman-Kang): the fraction of method pairs that
share at least one instance field, in ``[0, 1]``.
@@ -149,10 +461,97 @@ def _tcc(field_sets: list[set[str]]) -> float:
return connected / possible
+def _member_buckets(
+ members_per_method: list[set[str]],
+ method_fcs: list[FunctionComplexity],
+ merge_overloads: bool,
+) -> dict[str, list[int]]:
+ """Method indices by each member they reference. With *merge_overloads*
+ (implicit receivers) every method also sits in its own name's bucket, so
+ same-named methods are one node: a bare call cannot say which overload it
+ reaches."""
+ buckets: dict[str, list[int]] = {}
+ for i, members in enumerate(members_per_method):
+ for m in members:
+ buckets.setdefault(m, []).append(i)
+ if merge_overloads:
+ for i, fc in enumerate(method_fcs):
+ buckets.setdefault(fc.name, []).append(i)
+ return buckets
+
+
+def _component_roots(
+ members_per_method: list[set[str]],
+ method_fcs: list[FunctionComplexity],
+ merge_overloads: bool,
+) -> list[int]:
+ """Union-find root of each method index.
+
+ Methods join when they share a bucket (``_member_buckets``); the method
+ that *defines* a referenced name (a callee) joins that bucket too, so
+ call edges and shared-field edges are both captured in one pass.
+ """
+ parent = list(range(len(method_fcs)))
+
+ def _find(i: int) -> int:
+ while parent[i] != i:
+ parent[i] = parent[parent[i]]
+ i = parent[i]
+ return i
+
+ def _union(a: int, b: int) -> None:
+ ra, rb = _find(a), _find(b)
+ if ra != rb:
+ parent[ra] = rb
+
+ name_to_idx = {fc.name: i for i, fc in enumerate(method_fcs)}
+ for member, idxs in _member_buckets(members_per_method, method_fcs, merge_overloads).items():
+ callee = name_to_idx.get(member)
+ for other in idxs[1:] + ([callee] if callee is not None else []):
+ _union(idxs[0], other)
+ return [_find(i) for i in range(len(method_fcs))]
+
+
+def _indexed_groups(
+ roots: list[int],
+ method_fcs: list[FunctionComplexity],
+ members_per_method: list[set[str]],
+ method_names: set[str],
+) -> list[tuple[list[int], CohesionGroup]]:
+ """The per-component membership behind the LCOM4 integer.
+
+ Each group's methods (and the groups themselves) are ordered by source
+ position, ``(start_line, name)`` rather than collection index, so the
+ split reads top-to-bottom and is stable across runs. Each group keeps its
+ method indices, which stay correct when method names repeat. Its fields
+ are the members its methods reference that aren't method names.
+ """
+ by_root: dict[int, list[int]] = {}
+ for i, root in enumerate(roots):
+ by_root.setdefault(root, []).append(i)
+
+ def _pos(i: int) -> tuple[int, str]:
+ return (method_fcs[i].start_line, method_fcs[i].name)
+
+ indexed: list[tuple[list[int], CohesionGroup]] = []
+ for member_idxs in by_root.values():
+ member_idxs.sort(key=_pos)
+ group_fields: set[str] = set()
+ for i in member_idxs:
+ group_fields |= members_per_method[i] - method_names
+ group = CohesionGroup(
+ methods=[method_fcs[i].name for i in member_idxs], fields=sorted(group_fields)
+ )
+ indexed.append((member_idxs, group))
+ indexed.sort(key=lambda pair: _pos(pair[0][0]))
+ return indexed
+
+
def _compute_lcom4(
method_nodes: list[Node],
method_fcs: list[FunctionComplexity],
lmap: LanguageNodeMap,
+ refs: _MemberRefs | None = None,
) -> tuple[int, int, list[CohesionGroup], float]:
"""Return ``(lcom4, field_count, components, tcc)`` for a class.
@@ -170,90 +569,34 @@ def _compute_lcom4(
an unverified language: a missing mapping yields "no signal", never a
spurious high-LCOM hit. ``components`` is empty in every no-signal case
(the integer carries no real split to expose).
+
+ *refs* defaults to the explicit ``self.x`` references. Where the map
+ names field declarations (implicit receivers), overloads are one node and
+ only ``_stateful_groups`` count toward LCOM4.
"""
- n = len(method_nodes)
- if n == 0:
+ if not method_nodes:
return 1, 0, [], 1.0
-
- members_per_method: list[set[str]] = [
- _collect_self_members(node, lmap) for node in method_nodes
- ]
- total_refs = sum(len(m) for m in members_per_method)
- method_names = {fc.name for fc in method_fcs}
- all_members: set[str] = set().union(*members_per_method) if members_per_method else set()
+ if refs is None:
+ refs = _MemberRefs([_collect_self_members(n, lmap) for n in method_nodes], frozenset())
+ members_per_method = refs.per_method
+ method_names = {fc.name for fc in method_fcs} | refs.out_of_line
+ all_members: set[str] = set().union(*members_per_method)
field_count = len(all_members - method_names)
# TCC over instance fields only (method-call edges don't count toward it),
# so it complements LCOM4 rather than restating it.
tcc = _tcc([members - method_names for members in members_per_method])
- if total_refs == 0:
+ if not all_members:
return 1, field_count, [], tcc
- # Union-find over method indices.
- parent = list(range(n))
-
- def _find(i: int) -> int:
- while parent[i] != i:
- parent[i] = parent[parent[i]]
- i = parent[i]
- return i
-
- def _union(a: int, b: int) -> None:
- ra, rb = _find(a), _find(b)
- if ra != rb:
- parent[ra] = rb
-
- name_to_idx = {fc.name: i for i, fc in enumerate(method_fcs)}
- # Bucket method indices by each member they reference; the method that
- # *defines* that name (a callee) joins the bucket too, so call edges and
- # shared-field edges are both captured in one pass.
- buckets: dict[str, list[int]] = {}
- for i, members in enumerate(members_per_method):
- for m in members:
- buckets.setdefault(m, []).append(i)
- for member, idxs in buckets.items():
- group = list(idxs)
- callee = name_to_idx.get(member)
- if callee is not None:
- group.append(callee)
- first = group[0]
- for other in group[1:]:
- _union(first, other)
-
- roots = [_find(i) for i in range(n)]
- components = set(roots)
-
- # Build the per-component membership behind the integer. Bucket method
- # indices by their union-find root, then order each group's methods (and
- # the groups themselves) by source position so the split reads
- # top-to-bottom. Ordering is by ``(start_line, name)`` rather than
- # collection index, which makes it both deterministic and stable across
- # runs. Each group's fields are the members its methods reference that
- # aren't method names.
- by_root: dict[int, list[int]] = {}
- for i in range(n):
- by_root.setdefault(roots[i], []).append(i)
-
- def _pos(i: int) -> tuple[int, str]:
- return (method_fcs[i].start_line, method_fcs[i].name)
-
- # Pair each group with its earliest member index so the inter-group sort
- # keys off that index directly (robust to duplicate method names, which a
- # name->index lookup would resolve to the wrong method).
- indexed_groups: list[tuple[int, CohesionGroup]] = []
- for member_idxs in by_root.values():
- member_idxs.sort(key=_pos)
- group_methods = [method_fcs[i].name for i in member_idxs]
- group_fields: set[str] = set()
- for i in member_idxs:
- group_fields |= members_per_method[i] - method_names
- indexed_groups.append(
- (member_idxs[0], CohesionGroup(methods=group_methods, fields=sorted(group_fields)))
- )
- indexed_groups.sort(key=lambda pair: _pos(pair[0]))
- groups = [g for _, g in indexed_groups]
- return len(components), field_count, groups, tcc
+ implicit = bool(lmap.field_decl_kinds)
+ roots = _component_roots(members_per_method, method_fcs, implicit)
+ indexed = _indexed_groups(roots, method_fcs, members_per_method, method_names)
+ if implicit:
+ groups = _stateful_groups(indexed, refs.contracts)
+ return max(len(groups), 1), field_count, groups, tcc
+ return len(indexed), field_count, [g for _, g in indexed], tcc
def _collect_classes(
@@ -272,12 +615,18 @@ def _collect_classes(
return []
classes: list[ClassComplexity] = []
for class_node in class_nodes:
- method_nodes = _collect_class_methods(class_node, lmap)
- method_fcs = [fc_by_node_id[m.id] for m in method_nodes if m.id in fc_by_node_id]
+ body = _collect_class_body(class_node, lmap)
+ method_fcs = [fc_by_node_id[m.id] for m in body.methods if m.id in fc_by_node_id]
# Keep nodes and FCs aligned (a method missing from the function
# pass — unusual — drops out of both).
- aligned_nodes = [m for m in method_nodes if m.id in fc_by_node_id]
- lcom4, field_count, components, tcc = _compute_lcom4(aligned_nodes, method_fcs, lmap)
+ body = body._replace(methods=[m for m in body.methods if m.id in fc_by_node_id])
+ if "partial" in _decl_words(class_node):
+ lcom4, field_count, components, tcc = 1, 0, [], 1.0
+ else:
+ refs = _class_member_refs(body, method_fcs, lmap, _class_name(class_node))
+ lcom4, field_count, components, tcc = _compute_lcom4(
+ body.methods, method_fcs, lmap, refs
+ )
classes.append(
ClassComplexity(
name=_class_name(class_node),
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/languages.py b/packages/core/src/repowise/core/analysis/health/complexity/languages.py
index 942ad47ee..400fcdbb8 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/languages.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/languages.py
@@ -30,12 +30,12 @@ JavaScript, Go, Java, Kotlin, Rust, C++, C#, Scala, Ruby) plus their aliases
and Dart; class-level maps cover all of those except Go (no class-grouping
node). Adding a language, at either tier, is purely additive here.
-Two cross-language heuristic limits worth noting (both degrade to "no signal",
-never a false positive): (1) instance members accessed without an explicit
-receiver (idiomatic Kotlin/C++/C#/Java bare ``field`` rather than
-``this.field``) are not counted toward LCOM4 cohesion, so ``low_cohesion``
-stays silent on receiver-less code; (2) flat ``switch``/``when``/``match``
-arms count once for the dispatch, not per arm.
+Two cross-language heuristic notes: (1) Java, C#, C++ and Kotlin reach their
+own members without a receiver (bare ``field`` rather than ``this.field``), so
+those maps name their field declarations and binding forms and LCOM4 counts a
+bare name that resolves to a declared field or sibling method; languages
+without that mapping count explicit receivers only; (2) flat
+``switch``/``when``/``match`` arms count once for the dispatch, not per arm.
"""
from __future__ import annotations
@@ -94,6 +94,23 @@ class LanguageNodeMap:
# access (both field reads and method calls — both count as a member
# reference for cohesion).
member_access_kinds: frozenset[str] = frozenset()
+ # Implicit receivers (Java / C# / C++ / Kotlin read a field as bare
+ # ``index`` and call a sibling as bare ``id()``). All four default to
+ # empty, which keeps a language on explicit ``this.x`` evidence only:
+ #
+ # * ``field_decl_kinds`` -- class-body node types that declare instance
+ # state (fields, C# properties). A bare identifier naming one of these,
+ # or a sibling method, counts as a member reference.
+ # * ``binding_kinds`` -- node types that bind a parameter or local inside
+ # a method; a name bound anywhere in the method shadows the member.
+ # * ``identifier_kinds`` -- the grammar's name token types.
+ # * ``nested_type_kinds`` -- type declarations that are not cohesion
+ # units themselves (a Java ``enum`` or ``record`` nested in a class)
+ # but own their members, so the outer class must not collect them.
+ field_decl_kinds: frozenset[str] = frozenset()
+ binding_kinds: frozenset[str] = frozenset()
+ identifier_kinds: frozenset[str] = frozenset()
+ nested_type_kinds: frozenset[str] = frozenset()
# ------------------------------------------------------------------
# Assertion detection (test-quality smells). Both fields default to
@@ -379,6 +396,30 @@ _JAVA = LanguageNodeMap(
# ``field_access`` covers ``this.field``; ``method_invocation`` covers
# ``this.foo()`` (its ``name`` field is the called method).
member_access_kinds=frozenset({"field_access", "method_invocation"}),
+ field_decl_kinds=frozenset({"field_declaration"}),
+ binding_kinds=frozenset(
+ {
+ "variable_declarator",
+ "formal_parameter",
+ "spread_parameter",
+ "catch_formal_parameter",
+ "enhanced_for_statement",
+ "lambda_expression",
+ "inferred_parameters",
+ "resource",
+ "instanceof_expression",
+ "type_pattern",
+ }
+ ),
+ identifier_kinds=frozenset({"identifier"}),
+ nested_type_kinds=frozenset(
+ {
+ "enum_declaration",
+ "record_declaration",
+ "interface_declaration",
+ "annotation_type_declaration",
+ }
+ ),
# ``assert x`` (JUnit ``assert`` keyword) + ``assertEquals(...)`` calls.
assert_kinds=frozenset({"assert_statement"}),
assert_call_kinds=frozenset({"method_invocation"}),
@@ -468,13 +509,16 @@ _KOTLIN = LanguageNodeMap(
# Methods group under a ``class_body``; ``object_declaration`` (singletons
# / companion objects) groups them the same way. Member access is
# ``receiver.member`` via ``navigation_expression``; the instance receiver
- # is a ``this_expression`` whose text is ``this``. NOTE: idiomatic Kotlin
- # accesses members WITHOUT an explicit ``this.`` receiver — those bare
- # references are not counted (the documented implicit-receiver limit), so
- # ``low_cohesion`` stays at the "no signal" value rather than mis-firing.
+ # is a ``this_expression`` whose text is ``this``. Idiomatic Kotlin omits
+ # ``this.``; bare names resolve through the declared properties (a
+ # primary-constructor ``val``/``var`` included) and sibling functions.
class_kinds=frozenset({"class_declaration", "object_declaration"}),
self_identifiers=frozenset({"this"}),
member_access_kinds=frozenset({"navigation_expression"}),
+ field_decl_kinds=frozenset({"property_declaration", "class_parameter"}),
+ binding_kinds=frozenset({"variable_declaration", "parameter", "catch_block"}),
+ identifier_kinds=frozenset({"identifier", "simple_identifier"}),
+ nested_type_kinds=frozenset({"companion_object"}),
# Kotlin has no bare ``assert`` keyword; ``assertEquals(...)`` /
# ``assertTrue(...)`` are plain calls placed directly in the statement
# list (no ``expression_statement`` wrapper).
@@ -544,11 +588,25 @@ _CPP = LanguageNodeMap(
# ``class_specifier`` / ``struct_specifier`` group methods in a
# ``field_declaration_list``. ``field_expression`` covers both
# ``this->member`` and ``obj.member``; the instance receiver is the
- # ``this`` node. Same implicit-receiver limit as Kotlin — bare member
- # access (no ``this->``) is not counted.
+ # ``this`` node. Bare ``m_x`` resolves through the class body's
+ # ``field_declaration``s; one whose declarator is a function is a method
+ # declared here and defined out of line, never a field.
class_kinds=frozenset({"class_specifier", "struct_specifier"}),
self_identifiers=frozenset({"this"}),
- member_access_kinds=frozenset({"field_expression"}),
+ # ``qualified_identifier`` (``Other::a``) names another scope's member.
+ member_access_kinds=frozenset({"field_expression", "qualified_identifier"}),
+ field_decl_kinds=frozenset({"field_declaration"}),
+ binding_kinds=frozenset(
+ {
+ "parameter_declaration",
+ "optional_parameter_declaration",
+ "init_declarator",
+ "declaration",
+ "for_range_loop",
+ "structured_binding_declarator",
+ }
+ ),
+ identifier_kinds=frozenset({"identifier", "field_identifier"}),
# GoogleTest / Catch2 / Boost.Test macros: ``EXPECT_EQ`` / ``ASSERT_EQ`` /
# ``ASSERT_TRUE`` are ordinary calls (``expect``/``assert`` prefix matched
# case-insensitively).
@@ -617,9 +675,30 @@ _CSHARP = LanguageNodeMap(
# ``class``/``struct``/``record`` declarations group methods in a
# ``declaration_list``. ``member_access_expression`` covers
# ``this.member`` (and ``obj.member``); ``this`` is the receiver token.
+ # Properties are state as much as fields are. A ``partial`` class is
+ # never scored: its other parts live in files this pass does not see.
class_kinds=frozenset({"class_declaration", "struct_declaration", "record_declaration"}),
self_identifiers=frozenset({"this"}),
member_access_kinds=frozenset({"member_access_expression"}),
+ field_decl_kinds=frozenset(
+ {"field_declaration", "property_declaration", "event_field_declaration"}
+ ),
+ binding_kinds=frozenset(
+ {
+ "variable_declarator",
+ "parameter",
+ "foreach_statement",
+ "catch_declaration",
+ "declaration_expression",
+ "declaration_pattern",
+ "tuple_pattern",
+ "single_variable_designation",
+ "implicit_parameter",
+ "lambda_expression",
+ }
+ ),
+ identifier_kinds=frozenset({"identifier"}),
+ nested_type_kinds=frozenset({"interface_declaration", "enum_declaration"}),
# xUnit / NUnit / MSTest: ``Assert.Equal(...)`` / ``Assert.True(...)`` are
# invocations whose callee chain begins with ``Assert``.
assert_call_kinds=frozenset({"invocation_expression"}),
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/extract_class.py b/packages/core/src/repowise/core/analysis/health/refactoring/extract_class.py
index 3fa9c4f8f..c9b738e0c 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/extract_class.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/extract_class.py
@@ -32,6 +32,7 @@ extracted class and are dropped from the split so the plan reads honestly.
from __future__ import annotations
+from ..complexity.class_analysis import cohesion_applies
from .models import RefactoringContext, RefactoringSuggestion
from .registry import RefactoringDetector, effort_bucket, register
@@ -68,6 +69,8 @@ class ExtractClassDetector(RefactoringDetector):
def detect(self, ctx: RefactoringContext) -> list[RefactoringSuggestion]:
out: list[RefactoringSuggestion] = []
+ if not cohesion_applies(ctx.file_path, ctx.language):
+ return out
impact_by_class = self._impact_by_class(ctx)
for cls in ctx.classes:
diff --git a/tests/fixtures/lang_samples/cpp/classes.cpp b/tests/fixtures/lang_samples/cpp/classes.cpp
index 96c6f3eba..8bc06daaa 100644
--- a/tests/fixtures/lang_samples/cpp/classes.cpp
+++ b/tests/fixtures/lang_samples/cpp/classes.cpp
@@ -1,7 +1,7 @@
// Fixtures for class-level (LCOM4 / god-class) walker tests.
//
// Uses explicit `this->` so the member-access node type is exercised; bare
-// member access (idiomatic C++) is the documented "no signal" path.
+// member access is covered in tests/unit/health/test_implicit_member_cohesion.py.
class Cohesive {
int total;
diff --git a/tests/fixtures/lang_samples/kotlin/classes.kt b/tests/fixtures/lang_samples/kotlin/classes.kt
index 5080e5157..8f651cbcb 100644
--- a/tests/fixtures/lang_samples/kotlin/classes.kt
+++ b/tests/fixtures/lang_samples/kotlin/classes.kt
@@ -2,7 +2,8 @@
//
// Kotlin accesses instance members WITHOUT a receiver idiomatically; these
// fixtures use an explicit `this.` so the member-access node type is
-// exercised. The implicit-receiver case is the documented "no signal" path.
+// exercised. The implicit-receiver case is covered in
+// tests/unit/health/test_implicit_member_cohesion.py.
class Cohesive {
var total = 0
diff --git a/tests/unit/health/test_complexity_walker.py b/tests/unit/health/test_complexity_walker.py
index 8ab55cdcf..cdf45623a 100644
--- a/tests/unit/health/test_complexity_walker.py
+++ b/tests/unit/health/test_complexity_walker.py
@@ -441,7 +441,9 @@ def test_kotlin_class_cohesion():
splintered = classes.get("Splintered")
assert cohesive is not None and splintered is not None
assert cohesive.lcom4 == 1
- assert splintered.lcom4 == 3
+ # Each cluster is an accessor pair over one field and the loner touches
+ # none: no component spans two fields, so there is no cohesion signal.
+ assert splintered.lcom4 == 1
assert splintered.method_count == 5
assert splintered.field_count == 2
@@ -471,7 +473,9 @@ def test_cpp_class_cohesion():
splintered = classes.get("Splintered")
assert cohesive is not None and splintered is not None
assert cohesive.lcom4 == 1
- assert splintered.lcom4 == 3
+ # Each cluster is an accessor pair over one field and the loner touches
+ # none: no component spans two fields, so there is no cohesion signal.
+ assert splintered.lcom4 == 1
assert splintered.method_count == 5
assert splintered.field_count == 2
@@ -501,7 +505,9 @@ def test_csharp_class_cohesion():
splintered = classes.get("Splintered")
assert cohesive is not None and splintered is not None
assert cohesive.lcom4 == 1
- assert splintered.lcom4 == 3
+ # Each cluster is an accessor pair over one field and the loner touches
+ # none: no component spans two fields, so there is no cohesion signal.
+ assert splintered.lcom4 == 1
assert splintered.method_count == 5
assert splintered.field_count == 2
diff --git a/tests/unit/health/test_implicit_member_cohesion.py b/tests/unit/health/test_implicit_member_cohesion.py
new file mode 100644
index 000000000..6a61fb76b
--- /dev/null
+++ b/tests/unit/health/test_implicit_member_cohesion.py
@@ -0,0 +1,420 @@
+"""LCOM4 over implicit receivers: Java, C#, C++ and Kotlin reach their own
+fields and sibling methods without ``this.``.
+
+Before this, only ``this.x`` counted, so a class mixing ``this.x = x`` in its
+constructor with bare reads elsewhere splintered into one component per
+method and read as low cohesion.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.analysis.health.complexity import walk_file
+
+
+def _classes(language: str, source: str, path: str = "Sample") -> dict:
+ fcx = walk_file(path, language, source.encode())
+ if not fcx.classes:
+ pytest.skip(f"tree-sitter grammar missing for {language}")
+ return {c.name: c for c in fcx.classes}
+
+
+JAVA = """
+class ShardId {
+ private final Index index;
+ private final int shardId;
+ private static final String NAME = "shard";
+
+ ShardId(Index index, int shardId) { this.index = index; this.shardId = shardId; }
+ Index getIndex() { return index; }
+ String getIndexName() { return index.getName(); }
+ int id() { return this.shardId; }
+ int getId() { return id(); }
+ String name() { return NAME; }
+ boolean sameAs(ShardId other) { return other.shardId == shardId; }
+}
+
+class Splintered {
+ int a1;
+ int a2;
+ int b1;
+ int b2;
+ void setA(int v) { a1 = v; a2 = v; }
+ int getA() { return a1 + a2; }
+ void setB(int v) { b1 = v; b2 = v; }
+ int getB() { return b1 + b2; }
+ int loner(int a1) { return a1 + 1; }
+ boolean isB() { return b1 > 0; }
+}
+"""
+
+
+def test_java_bare_field_reads_and_sibling_calls_link_methods():
+ classes = _classes("java", JAVA, "ShardId.java")
+ shard = classes["ShardId"]
+ # Every method reaches ``index`` or ``shardId``. ``name()`` reads only a
+ # static constant: it touches no visible member, so it is left out rather
+ # than counted as a component of its own.
+ assert shard.lcom4 == 1
+ assert shard.field_count == 2
+ assert [set(g.methods) for g in shard.components] == [
+ {"ShardId", "getIndex", "getIndexName", "id", "getId", "sameAs"}
+ ]
+
+
+def test_java_parameter_shadows_field_and_splinters_stay_found():
+ splintered = _classes("java", JAVA, "Splintered.java")["Splintered"]
+ # Two real field clusters. ``loner(int a1)`` reads its parameter, not the
+ # field, so it touches no member and is left out.
+ assert splintered.lcom4 == 2
+ assert splintered.field_count == 4
+ assert [set(g.methods) for g in splintered.components] == [
+ {"setA", "getA"},
+ {"setB", "getB", "isB"},
+ ]
+
+
+def test_accessors_over_one_field_are_not_a_responsibility():
+ source = """
+class Request {
+ private String id;
+ private String name;
+ private boolean refresh;
+ Request(String id, String name) { this.id = id; this.name = name; }
+ String describe() { return id + name; }
+ void setRefresh(boolean r) { refresh = r; }
+ boolean getRefresh() { return refresh; }
+}
+"""
+ request = _classes("java", source, "Request.java")["Request"]
+ assert request.lcom4 == 1
+ assert [set(g.fields) for g in request.components] == [{"id", "name"}]
+
+
+CSHARP = """
+class Settings
+{
+ private int _count;
+ public string Key { get; set; }
+ public const int Max = 3;
+
+ public void Add(int n) { _count += n; }
+ public int Count() { return _count; }
+ public string Describe() { return Key + Count(); }
+ public void Rename(string key) { Key = key; }
+ public bool Same(Settings other) { return other.Key == Key; }
+}
+
+public sealed partial class MainWindow : Window
+{
+ private int _a;
+ private int _b;
+ public void A1() { _a = 1; }
+ public void A2() { _a = 2; }
+ public void B1() { _b = 1; }
+ public void B2() { _b = 2; }
+ public void Loner() { }
+}
+"""
+
+
+def test_csharp_bare_fields_and_properties_link_methods():
+ settings = _classes("csharp", CSHARP, "Settings.cs")["Settings"]
+ assert settings.lcom4 == 1
+ assert settings.field_count == 2 # _count and Key; the const is not state
+
+
+def test_csharp_partial_class_has_no_cohesion_signal():
+ window = _classes("csharp", CSHARP, "MainWindow.xaml.cs")["MainWindow"]
+ assert window.method_count == 5
+ assert window.lcom4 == 1
+ assert window.components == []
+
+
+CPP = """
+class Module : public Iface {
+ bool m_enabled;
+ std::wstring* m_name;
+ static int s_count;
+ void refresh();
+
+public:
+ void enable() { m_enabled = true; refresh(); }
+ void disable() { m_enabled = false; }
+ bool is_enabled() { return m_enabled; }
+ const wchar_t* name() { return m_name->c_str(); }
+ void rename(std::wstring* m_name_) { m_name = m_name_; refresh(); }
+ void copy(Module& other) { other.m_enabled = true; }
+};
+"""
+
+
+def test_cpp_bare_member_access_and_out_of_line_methods():
+ module = _classes("cpp", CPP, "dllmain.cpp")["Module"]
+ # ``refresh`` is declared here and defined elsewhere: a shared call, not a field.
+ assert module.field_count == 2
+ # ``other.m_enabled`` is another instance's field, so ``copy`` touches
+ # none of ours and is left out.
+ assert [set(g.methods) for g in module.components] == [
+ {"enable", "disable", "is_enabled", "name", "rename"}
+ ]
+ assert module.lcom4 == 1
+
+
+KOTLIN = """
+class Counter(val start: Int, step: Int) {
+ var total = 0
+
+ fun add(n: Int) { total += n }
+ fun reset() { total = start }
+ fun describe(): String { return total.toString() }
+ fun copy(other: Counter) { other.total = 1 }
+ fun loner(total: Int): Int { return total }
+}
+"""
+
+
+def test_kotlin_bare_properties_and_constructor_vals():
+ counter = _classes("kotlin", KOTLIN, "Counter.kt")["Counter"]
+ # ``copy`` writes another instance and ``loner`` reads its parameter.
+ assert [set(g.methods) for g in counter.components] == [{"add", "reset", "describe"}]
+ assert counter.field_count == 2 # total and start; plain ``step`` is not a property
+
+
+def test_python_still_requires_self():
+ source = """
+class C:
+ def __init__(self):
+ self.a = 1
+ def bare(self):
+ return a
+ def own(self):
+ return self.a
+"""
+ c = _classes("python", source, "c.py")["C"]
+ assert c.lcom4 == 2
+ assert [set(g.methods) for g in c.components] == [{"__init__", "own"}, {"bare"}]
+
+
+STATELESS_AND_CONTRACTS = """
+class Retry {
+ static Policy retry(int n) { return retry(n, null); }
+ static Policy retry(int n, Handler h) { return build(n, h); }
+ static Policy forever() { return build(-1, null); }
+ private static Policy build(int n, Handler h) { return new Policy(n, h); }
+ static Policy never() { return null; }
+}
+
+class Route {
+ private String upstream;
+ private String downstream;
+ private int timeout;
+ Route(String up, String down, int t) { upstream = up; downstream = down; timeout = t; }
+ Route copy() { return new Route(upstream, downstream, timeout); }
+ int timeoutOr(int d) { return timeout > 0 ? timeout : d; }
+ String key() { return upstream + downstream; }
+ private String label;
+ private String tag;
+ @Override public String toString() { return label + tag; }
+}
+"""
+
+
+def test_java_stateless_class_has_no_cohesion_signal():
+ retry = _classes("java", STATELESS_AND_CONTRACTS, "Retry.java")["Retry"]
+ assert retry.method_count == 5
+ assert retry.lcom4 == 1
+ assert retry.components == []
+
+
+def test_java_override_only_component_is_not_a_responsibility():
+ route = _classes("java", STATELESS_AND_CONTRACTS, "Route.java")["Route"]
+ # ``toString`` alone reads ``label`` and ``tag``; it is a contract, so it
+ # does not count as a second responsibility.
+ assert route.lcom4 == 1
+ assert [set(g.fields) for g in route.components] == [{"upstream", "downstream", "timeout"}]
+
+
+def test_csharp_overloads_are_one_node_and_lone_accessors_do_not_count():
+ source = """
+class Logger
+{
+ private ILogger _logger;
+ private IScope _scope;
+ private bool _disposed;
+
+ public void LogTrace(string message) { LogTrace(() => message); }
+ public void LogTrace(Func<string> message) { Write(_logger, _scope, message); }
+ public void LogDebug(string message) { Write(_logger, _scope, () => message); }
+ private void Write(ILogger l, IScope s, Func<string> m) { }
+ public void Dispose() { _disposed = true; }
+ public override string ToString() { return _scope.Name + _logger.Name; }
+}
+"""
+ logger = _classes("csharp", source, "Logger.cs")["Logger"]
+ # ``Dispose`` alone over ``_disposed`` is an accessor, ``ToString`` an
+ # override; the rest is one component through ``_logger`` / ``_scope``.
+ assert logger.lcom4 == 1
+
+
+def test_java_nested_types_own_their_members_and_inner_classes_link_outer_state():
+ source = """
+class Cache {
+ private final Counter hits = new Counter();
+ private final Counter misses = new Counter();
+ private final Map entries;
+ private final Lock lock;
+
+ Cache(Map entries, Lock lock) { this.entries = entries; this.lock = lock; }
+ Object get(Object k) { return segment().get(k); }
+ void put(Object k, Object v) { lock.lock(); entries.put(k, v); }
+ void clear() { lock.lock(); entries.clear(); }
+ Stats stats() { return new Stats(hits.sum(), misses.sum()); }
+ Segment segment() { return new Segment(); }
+
+ class Segment {
+ Object get(Object k) {
+ Object v = entries.get(k);
+ if (v == null) { misses.increment(); } else { hits.increment(); }
+ return v;
+ }
+ }
+
+ enum Mode {
+ FAST, SAFE;
+ private int weight;
+ int weight() { return weight; }
+ Mode heavier() { weight++; return this; }
+ }
+}
+"""
+ cache = _classes("java", source, "Cache.java")["Cache"]
+ # ``Mode``'s methods are not the cache's; ``Segment`` reads the counters
+ # and the entries together, so ``stats`` is not a split of its own.
+ assert "weight" not in {m.name for m in cache.methods}
+ assert cache.lcom4 == 1
+
+
+def test_csharp_static_factory_initializers_are_not_instance_state():
+ source = """
+public class PasteFormat
+{
+ public string Name { get; init; }
+ public string Prompt { get; init; }
+ public bool IsSaved { get; init; }
+ public int Format { get; init; }
+ public bool IsEnabled { get; set; }
+
+ public PasteFormat(int format, bool enabled) { Format = format; IsEnabled = enabled; }
+ public bool Supports(int f) { return IsEnabled && Format == f; }
+ public bool Supports(string f) { return IsEnabled && Format.ToString() == f; }
+ public static PasteFormat Standard(int f) => new PasteFormat(f, true) { Name = "std" };
+ public static PasteFormat Custom(string p) => new PasteFormat(0, true) { Name = "ai", Prompt = p, IsSaved = true };
+}
+"""
+ fmt = _classes("csharp", source, "PasteFormat.cs")["PasteFormat"]
+ assert fmt.lcom4 == 1
+
+
+def test_constructor_only_component_is_not_a_split():
+ # Fields the constructor sets and only a property (C#) or an out-of-line
+ # method (C++) reads leave the constructor alone in its component.
+ csharp = """
+class Totals
+{
+ private readonly int a;
+ private readonly int b;
+ private int c;
+ private int d;
+ public int A => a + b;
+ public Totals(int x) { a = x; b = x; }
+ public void M1() { c = 1; d = 1; }
+ public void M2() { c = 2; d = 2; }
+ public int M3() { return c + d; }
+ public int M4() { return c - d; }
+}
+"""
+ assert _classes("csharp", csharp, "Totals.cs")["Totals"].lcom4 == 1
+ cpp = """
+class Totals {
+ int a;
+ int b;
+ int c;
+ int d;
+public:
+ Totals(int p) : a(p), b(p) {}
+ void m1() { c = 1; d = 1; }
+ void m2() { c = 2; d = 2; }
+ int m3() { return c + d; }
+ int m4() { return c - d; }
+ int sum();
+};
+"""
+ assert _classes("cpp", cpp, "totals.h")["Totals"].lcom4 == 1
+
+
+def test_pattern_and_scoped_names_shadow_or_skip_members():
+ java = """
+class Box {
+ private int a;
+ private int b;
+ Box(int x) { a = x; b = x; }
+ int f(Object o) { return switch (o) { case Integer a -> a; default -> 0; }; }
+}
+"""
+ box = _classes("java", java, "Box.java")["Box"]
+ f = next(g for g in box.components if "f" in g.methods) if box.components else None
+ assert f is None or "a" not in f.fields
+ csharp = """
+class Pair
+{
+ private int a;
+ private int q;
+ public void Read((int, int) t) { var (a, q) = t; }
+ public void Set() { a = 1; q = 2; }
+}
+"""
+ pair = _classes("csharp", csharp, "Pair.cs")["Pair"]
+ assert all("Read" not in g.methods for g in pair.components)
+ cpp = """
+class Node {
+ int a;
+ int b;
+ void reset() { Other::a = 1; Other::b = 2; }
+ void set() { a = 1; b = 2; }
+};
+"""
+ node = _classes("cpp", cpp, "node.h")["Node"]
+ assert all("reset" not in g.methods for g in node.components)
+
+
+def test_cohesion_does_not_apply_to_test_files_of_implicit_languages():
+ from repowise.core.analysis.health.complexity.class_analysis import cohesion_applies
+
+ assert not cohesion_applies("src/test/java/org/x/DateLiteralTest.java", "java")
+ assert not cohesion_applies("tests/Unit/LoggerTests.cs", "csharp")
+ assert cohesion_applies("src/main/java/org/x/Date.java", "java")
+ # Python keeps its old behaviour, test files included.
+ assert cohesion_applies("tests/test_thing.py", "python")
+
+
+def test_cpp_module_interface_overrides_and_constructor_are_not_a_split():
+ source = """
+class Module : public PowertoyModuleIface {
+ std::wstring app_name;
+ std::wstring app_key;
+ bool m_enabled = false;
+ PROCESS_INFORMATION p_info = {};
+ bool is_process_running() { return WaitForSingleObject(p_info.hProcess, 0) == 0; }
+ void launch_process() { CreateProcess(&p_info); }
+public:
+ Module() { app_name = L"x"; app_key = L"y"; }
+ virtual const wchar_t* get_key() override { return app_key.c_str(); }
+ virtual void set_config(const wchar_t* c) override { app_name = c; }
+ virtual void enable() { m_enabled = true; launch_process(); }
+ virtual void disable() { if (m_enabled) { TerminateProcess(p_info.hProcess, 1); } m_enabled = false; }
+ virtual bool is_enabled() override { return m_enabled; }
+};
+"""
+ assert _classes("cpp", source, "dllmain.cpp")["Module"].lcom4 == 1