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 a match guard once and skip for-each iterables in condition counts (#4783)

Raghav Chamadiya5266c8f35a4f
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py b/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py
index ddc0834be..5357edccf 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py
@@ -263,6 +263,8 @@ def _condition_subtrees(node: Node, lmap: LanguageNodeMap) -> list[Node]:
Falls back to all direct children except recognised body fields and
syntactic punctuation.
"""
+ if node.type in lmap.foreach_kinds:
+ return []
cond = node.child_by_field_name("condition")
if cond is not None:
return [cond]
@@ -275,22 +277,29 @@ def _condition_subtrees(node: Node, lmap: LanguageNodeMap) -> list[Node]:
value = node.child_by_field_name("value")
if value is not None and "case" in node.type:
return [value]
- # Fallback: direct children minus bodies / blocks.
+ return _non_body_children(node, lmap)
+
+
+_BLOCK_KINDS = frozenset({"block", "compound_statement", "statement_block"})
+
+
+def _non_body_children(node: Node, lmap: LanguageNodeMap) -> list[Node]:
+ """Direct named children of *node* minus bodies / blocks."""
body_nodes: set[int] = set()
for fname in _BODY_FIELD_NAMES:
child = node.child_by_field_name(fname)
if child is not None:
body_nodes.add(child.id)
- out: list[Node] = []
- for child in node.children:
- if child.id in body_nodes:
- continue
- if not child.is_named:
- continue
- if child.type in ("block", "compound_statement", "statement_block"):
- continue
- out.append(child)
- return out
+ # A ``case ... if guard`` guard is its own branch node and counts its
+ # condition there.
+ return [
+ child
+ for child in node.children
+ if child.is_named
+ and child.id not in body_nodes
+ and child.type not in _BLOCK_KINDS
+ and child.type not in lmap.branch_kinds
+ ]
def _collect_case_children(node: Node, lmap: LanguageNodeMap) -> list[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 5fac471e3..9e1639dc6 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/languages.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/languages.py
@@ -75,6 +75,11 @@ class LanguageNodeMap:
# the else-arm is the node's last named child, so a chain arm can still be
# located by position and recognised as flat.
ternary_arms_positional: bool = False
+ # Loop node kinds that walk a collection (``for x in xs``) and test no
+ # condition: the iterable is a value, so its boolean operators are not a
+ # compound condition. Grammars that share one node for both loop shapes
+ # (Go, Dart, Objective-C) are left out.
+ foreach_kinds: frozenset[str] = frozenset()
# ------------------------------------------------------------------
# Class-level analysis (LCOM4 / god-class). All three fields default
@@ -410,6 +415,7 @@ _PY = LanguageNodeMap(
flat_ternary_kinds=frozenset({"conditional_expression"}),
ternary_arms_positional=True,
loop_kinds=frozenset({"for_statement", "while_statement"}),
+ foreach_kinds=frozenset({"for_statement"}),
try_kinds=frozenset({"try_statement"}),
catch_kinds=frozenset({"except_clause"}),
switch_kinds=frozenset({"match_statement"}),
@@ -466,6 +472,7 @@ _TS = LanguageNodeMap(
"do_statement",
}
),
+ foreach_kinds=frozenset({"for_in_statement", "for_of_statement"}),
try_kinds=frozenset({"try_statement"}),
catch_kinds=frozenset({"catch_clause"}),
switch_kinds=frozenset({"switch_statement"}),
@@ -575,6 +582,7 @@ _JAVA = LanguageNodeMap(
"do_statement",
}
),
+ foreach_kinds=frozenset({"enhanced_for_statement"}),
try_kinds=frozenset({"try_statement", "try_with_resources_statement"}),
catch_kinds=frozenset({"catch_clause"}),
switch_kinds=frozenset({"switch_expression", "switch_statement"}),
@@ -657,6 +665,7 @@ _APEX = LanguageNodeMap(
loop_kinds=frozenset(
{"for_statement", "enhanced_for_statement", "while_statement", "do_statement"}
),
+ foreach_kinds=frozenset({"enhanced_for_statement"}),
try_kinds=frozenset({"try_statement"}),
catch_kinds=frozenset({"catch_clause"}),
switch_kinds=frozenset({"switch_expression"}),
@@ -704,6 +713,7 @@ _RUST = LanguageNodeMap(
loop_kinds=frozenset(
{"for_expression", "while_expression", "while_let_expression", "loop_expression"}
),
+ foreach_kinds=frozenset({"for_expression"}),
try_kinds=frozenset(),
catch_kinds=frozenset(),
switch_kinds=frozenset({"match_expression"}),
@@ -780,6 +790,7 @@ _KOTLIN = LanguageNodeMap(
lambda_kinds=frozenset({"lambda_literal", "anonymous_function"}),
branch_kinds=frozenset({"if_expression"}),
loop_kinds=frozenset({"for_statement", "while_statement", "do_while_statement"}),
+ foreach_kinds=frozenset({"for_statement"}),
try_kinds=frozenset({"try_expression"}),
catch_kinds=frozenset({"catch_block"}),
switch_kinds=frozenset({"when_expression"}),
@@ -842,6 +853,7 @@ _SWIFT = LanguageNodeMap(
{"if_statement", "guard_statement", "ternary_expression", "where_clause"}
),
loop_kinds=frozenset({"for_statement", "while_statement", "repeat_while_statement"}),
+ foreach_kinds=frozenset({"for_statement"}),
# ``do`` opens the guarded region and each ``catch`` is a path out of it.
# ``try`` / ``try?`` / ``try!`` mark a call that can throw and ``defer``
# schedules cleanup: neither is a decision.
@@ -917,6 +929,7 @@ _CPP = LanguageNodeMap(
lambda_kinds=frozenset({"lambda_expression"}),
branch_kinds=frozenset({"if_statement", "conditional_expression"}),
loop_kinds=frozenset({"for_statement", "while_statement", "do_statement", "for_range_loop"}),
+ foreach_kinds=frozenset({"for_range_loop"}),
try_kinds=frozenset({"try_statement"}),
catch_kinds=frozenset({"catch_clause"}),
switch_kinds=frozenset({"switch_statement"}),
@@ -1038,6 +1051,7 @@ _CSHARP = LanguageNodeMap(
lambda_kinds=frozenset({"lambda_expression"}),
branch_kinds=frozenset({"if_statement", "conditional_expression"}),
loop_kinds=frozenset({"for_statement", "while_statement", "foreach_statement", "do_statement"}),
+ foreach_kinds=frozenset({"foreach_statement"}),
try_kinds=frozenset({"try_statement"}),
catch_kinds=frozenset({"catch_clause"}),
switch_kinds=frozenset({"switch_statement", "switch_expression"}),
@@ -1119,6 +1133,7 @@ _SCALA = LanguageNodeMap(
# A for-comprehension is a loop for nesting/CCN purposes even though it
# desugars to flatMap: this matches developer intuition.
loop_kinds=frozenset({"for_expression", "while_expression", "do_while_expression"}),
+ foreach_kinds=frozenset({"for_expression"}),
try_kinds=frozenset({"try_expression"}),
# ``catch`` takes a ``case_block``; each handler is a ``case_clause`` that
# already counts via ``case_kinds`` (per-handler parity with Python's
@@ -1222,6 +1237,7 @@ _RUBY = LanguageNodeMap(
# for CCN/nesting they roll up like any other block (documented choice:
# block-heavy Ruby would otherwise nest everything).
loop_kinds=frozenset({"while", "until", "for", "while_modifier", "until_modifier"}),
+ foreach_kinds=frozenset({"for"}),
try_kinds=frozenset({"begin"}),
# A method-level ``rescue`` (no ``begin``) is the same ``rescue`` node
# nested directly in the method body — counted identically.
@@ -1263,6 +1279,7 @@ _SHELL = LanguageNodeMap(
# `until ...` parses as `while_statement` in tree-sitter-bash, so it is
# covered here; `for ((;;))` is `c_style_for_statement`.
loop_kinds=frozenset({"for_statement", "c_style_for_statement", "while_statement"}),
+ foreach_kinds=frozenset({"for_statement"}),
# No exceptions in shell (`trap` is not `try`).
try_kinds=frozenset(),
catch_kinds=frozenset(),
@@ -1298,6 +1315,7 @@ _PASCAL = LanguageNodeMap(
# distinct ``for x in collection do`` grammar node (its own node type,
# not a variant of ``for``) -- both are loops and must both count.
loop_kinds=frozenset({"for", "foreach", "while", "repeat"}),
+ foreach_kinds=frozenset({"foreach"}),
try_kinds=frozenset({"try"}),
# A bound handler (``on E: Exception do``) is an ``exceptionHandler``
# node; a bare ``except ... end`` with no ``on`` clauses has no such
@@ -1400,6 +1418,7 @@ _FSHARP = LanguageNodeMap(
local_value=_fsharp_binds_a_value,
branch_kinds=frozenset({"if_expression"}),
loop_kinds=frozenset({"for_expression", "while_expression"}),
+ foreach_kinds=frozenset({"for_expression"}),
try_kinds=frozenset({"try_expression"}),
# A ``with`` handler and a ``match`` arm are the same node types here, so
# one field has to serve both. ``case_kinds`` names ``rules``, the wrapper,
@@ -1461,6 +1480,7 @@ _PHP = LanguageNodeMap(
lambda_kinds=frozenset({"anonymous_function", "arrow_function"}),
branch_kinds=frozenset({"if_statement", "else_if_clause", "conditional_expression"}),
loop_kinds=frozenset({"for_statement", "foreach_statement", "while_statement", "do_statement"}),
+ foreach_kinds=frozenset({"foreach_statement"}),
try_kinds=frozenset({"try_statement"}),
catch_kinds=frozenset({"catch_clause"}),
switch_kinds=frozenset({"switch_statement", "match_expression"}),
diff --git a/tests/unit/health/test_complex_conditional.py b/tests/unit/health/test_complex_conditional.py
index df81b55bd..f64995df4 100644
--- a/tests/unit/health/test_complex_conditional.py
+++ b/tests/unit/health/test_complex_conditional.py
@@ -182,6 +182,61 @@ def test_python_ternary_counts_condition_only(body: str, count: int):
assert [c.operator_count for c in conds] == ([count] if count else [])
+ ("language", "src"),
+ [
+ (
+ "python",
+ "def f(v, a, b, c):\n match v:\n case 1 if a and b and c:\n return 1\n return 0\n",
+ ),
+ (
+ "scala",
+ "object O { def f(v: Int, a: Boolean, b: Boolean, c: Boolean): Int = v match {\n"
+ " case 1 if a && b && c => 1\n case _ => 0\n} }\n",
+ ),
+ (
+ "scala",
+ "object O { def f(xs: List[Int], a: Boolean, b: Boolean, c: Boolean) = "
+ "{ for (x <- xs; if a && b && c) println(x) } }\n",
+ ),
+ (
+ "swift",
+ "func f(xs: [Int], a: Bool, b: Bool, c: Bool) {\n for x in xs where a && b && c { print(x) }\n}\n",
+ ),
+ ],
+)
+def test_guard_counts_once(language: str, src: str):
+ conds = _conditions(src, language, "f").complex_conditions
+ assert [c.operator_count for c in conds] == [2]
+
+
+ ("language", "src"),
+ [
+ ("python", "def f(a, b, c):\n for x in (a and b or c):\n print(x)\n"),
+ ("python", "async def f(a, b, c):\n async for x in (a and b or c):\n print(x)\n"),
+ ("typescript", "function f(a, b, c) { for (const x of (a && b || c)) { g(x); } }\n"),
+ ("java", "class C { void f(boolean a, boolean b) { for (Object x : h(a && b || a)) { g(x); } } }\n"),
+ ("csharp", "class C { void f(bool a, bool b) { foreach (var x in H(a && b || a)) { G(x); } } }\n"),
+ ("kotlin", "fun f(a: Boolean, b: Boolean) { for (x in h(a && b || a)) g(x) }\n"),
+ ("ruby", "def f(a, b, c)\n for x in (a && b || c)\n g(x)\n end\nend\n"),
+ ("rust", "fn f(a: bool, b: bool) { for x in h(a && b || a) { g(x); } }\n"),
+ ("swift", "func f(a: Bool, b: Bool) {\n for x in h(a && b || a) { g(x) }\n}\n"),
+ ("cpp", "void f(bool a, bool b) { for (auto x : h(a && b || a)) { g(x); } }\n"),
+ ("php", "<?php function f($a, $b) { foreach (h($a && $b || $a) as $x) { g($x); } }\n"),
+ ("scala", "object O { def f(a: Boolean, b: Boolean) = { for (x <- h(a && b || a)) g(x) } }\n"),
+ ],
+)
+def test_foreach_iterable_is_not_a_condition(language: str, src: str):
+ assert _conditions(src, language, "f").complex_conditions == []
+
+
+def test_while_condition_still_counted():
+ src = "def f(a, b, c):\n while a and b or c:\n pass\n"
+ (cond,) = _conditions(src, "python", "f").complex_conditions
+ assert (cond.operator_count, cond.enclosing_construct) == (2, "while")
+
+
def test_reason_operator_count_matches_details_and_code():
# Three operators in the condition, one more in each arm.
src = "def f(a, b, c, d, e, g):\n x = a or b if c and d or e and g else a and b\n return x\n"