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): a switch opens one nesting level, its case arms none (#4762)

Raghav Chamadiya99986b27dbbe
diff --git a/docs/architecture/code-health.md b/docs/architecture/code-health.md
index f7a3e1b9b..9cf0f56fe 100644
--- a/docs/architecture/code-health.md
+++ b/docs/architecture/code-health.md
@@ -330,10 +330,11 @@ language because it does not transfer:
### 5.5 Worked example: the dispatch rule
-`nested_complexity` adds a level per `if` / `for` / `while` / `try` / `switch`. A
+`nested_complexity` adds a level per `if` / `for` / `while` / `try` / `switch`; a `case`
+arm adds none. A
function mostly one dispatch on one value (a `switch`, `match` or same-subject `if` chain
with ≥ 60% of its decision points) is judged by the code around it plus its heaviest arm:
-`nested_complexity` skips the `switch` and `case` levels, and `complex_method`,
+`nested_complexity` skips the dispatch's level and the loop it usually sits in, and `complex_method`,
`brain_method` and `repeated_nesting` read the outer CCN plus the worst arm's.
<details>
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/README.md b/packages/core/src/repowise/core/analysis/health/complexity/README.md
index ca0b348e4..c93c2a683 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/README.md
+++ b/packages/core/src/repowise/core/analysis/health/complexity/README.md
@@ -32,7 +32,8 @@ Tree-sitter AST walker. Single AST pass per file computes:
`else if` arms and, in TS/JS, ternary chain arms and ternaries choosing
JSX (`flat_ternary_kinds`), plus Python conditional-expression chains
(`1 if a else 2 if b else 3`), add CCN and a flat +1 cognitive but no
- level.
+ level. A `switch` / `match` / `when` opens one level for its body; its
+ case arms add CCN only, no level and no cognitive.
- **cognitive complexity** — SonarSource-style weighted nesting cost
(each level adds an incrementing penalty, plus +1 for each break in
control flow).
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 5cdef3ccb..ddc0834be 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py
@@ -402,9 +402,10 @@ def _walk_function_body(
bumps = 0
conditions: list[ConditionComplexity] = []
- # Track match_expression nodes identified as "flat" so their arms
- # are not individually counted as branch points.
- flat_match_ids: set[int] = set()
+ # Arms of a "flat" match are not counted at all; arms of any other
+ # switch count toward CCN but sit in the level their switch opened.
+ flat_arm_ids: set[int] = set()
+ switch_arm_ids: set[int] = set()
deepest_depth = 0
deepest_node: list[Node] = []
@@ -423,22 +424,8 @@ def _walk_function_body(
nesting_increment = 0
ccn_increment = 0
- # Check if this is a case/arm inside a flat match — skip it.
- # In Rust the parent chain is match_arm → match_block → match_expression,
- # so we check both parent and grandparent. ``node.parent`` costs far
- # more than the rest of this visit, so it is read only for a case node
- # once a flat match exists for it to belong to.
- is_flat_match_arm = False
- if (
- flat_match_ids
- and node.type in lmap.case_kinds
- and (_parent := node.parent) is not None
- and (
- _parent.id in flat_match_ids
- or (_parent.parent is not None and _parent.parent.id in flat_match_ids)
- )
- ):
- is_flat_match_arm = True
+ is_flat_match_arm = node.id in flat_arm_ids
+ is_switch_arm = node.id in switch_arm_ids
# ``node.is_named`` guards grammars (Ruby) whose keyword tokens share
# the node-type name of their parent node (an ``if`` node contains an
@@ -458,10 +445,11 @@ def _walk_function_body(
# An ``else if`` / ``elif`` chain arm, a ternary chain arm or
# markup choice, and a comprehension / case-guard filter are flat:
# charge the extra branch (ccn) but do not open a new nesting
- # level for them. This parallels the flat-``switch``/``match``
- # special-case above.
+ # level for them. So is a switch arm: its switch already opened
+ # the level (Sonar's cognitive complexity spec).
if not (
- node.type in _FLAT_BRANCH_KINDS
+ is_switch_arm
+ or node.type in _FLAT_BRANCH_KINDS
or _is_elif_continuation(node)
or _is_flat_ternary(node, lmap, in_markup)
):
@@ -493,13 +481,17 @@ def _walk_function_body(
# try's depth (Sonar's cognitive complexity spec).
pass
elif node.is_named and node.type in lmap.switch_kinds:
+ arm_ids = {c.id for c in _collect_case_children(node, lmap)}
# Detect flat match: all arms are simple single-expression arms.
if _is_flat_match(node, lmap):
- flat_match_ids.add(node.id)
+ flat_arm_ids.update(arm_ids)
# Flat match: count 1 CCN point for the match itself,
# open a nesting level, but arms won't be counted.
ccn_increment = 1
- # Switch opens nesting; each case contributes its own +1.
+ else:
+ switch_arm_ids.update(arm_ids)
+ # The switch opens one nesting level for its whole body; each
+ # case adds CCN only.
nesting_increment = 1
elif _is_boolean_operator(node, lmap):
ccn_increment = 1
@@ -509,8 +501,9 @@ def _walk_function_body(
if nesting_increment:
# Cognitive complexity: each nesting node adds (1 + depth).
cognitive += 1 + depth
- elif ccn_increment:
- # Flat +1 for boolean operators (no nesting impact).
+ elif ccn_increment and not is_switch_arm:
+ # Flat +1 for boolean operators (no nesting impact). A switch arm
+ # adds none: its switch carries the cognitive cost.
cognitive += 1
if new_depth > max_nesting:
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/dispatch.py b/packages/core/src/repowise/core/analysis/health/complexity/dispatch.py
index 68c7410c4..35e819c56 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/dispatch.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/dispatch.py
@@ -49,8 +49,9 @@ if TYPE_CHECKING:
#: decision points is mostly that dispatch. Fitted on the dev labels only:
#: share >= 0.6 held 9 labelled complexity rows, 8 of them rejected.
DISPATCH_SHARE = 0.6
-#: Nesting levels a dispatch opens before its arms' own code: a ``switch`` and
-#: its ``case``. A same-subject ``if`` chain opens one, so this is the bound.
+#: Nesting levels taken off a dominated function. A dispatch opens one (a
+#: ``switch`` or a same-subject ``if`` chain); the second covers the loop a
+#: per-case handler usually sits in. At 1, dispatch-in-a-loop parsers re-flag.
_DISPATCH_LEVELS = 2
# An ``if`` with one ``elif`` is a decision, not a dispatch; the same holds for
@@ -320,7 +321,7 @@ def judged_nesting(fn: FunctionComplexity) -> int:
"""The nesting a marker judges *fn* by: less the dispatch's own levels once it dominates.
The deepest block of a dominated function is almost always in an arm, so
- this subtracts the most a dispatch opens. A block that deep outside the
+ this subtracts :data:`_DISPATCH_LEVELS`. A block that deep outside the
dispatch is under-read by the same amount (the ceiling of not tracking
which side the deepest block is on).
"""
diff --git a/tests/unit/health/golden/health_engine.json b/tests/unit/health/golden/health_engine.json
index 7c7fc4d5e..168eee65b 100644
--- a/tests/unit/health/golden/health_engine.json
+++ b/tests/unit/health/golden/health_engine.json
@@ -1703,7 +1703,7 @@
"file_path": "python/match.py",
"score": 10.0,
"max_ccn": 5,
- "max_nesting": 2,
+ "max_nesting": 1,
"nloc": 19,
"has_test_file": false,
"module": "python",
@@ -1874,7 +1874,7 @@
"file_path": "rust/flat_match.rs",
"score": 10.0,
"max_ccn": 5,
- "max_nesting": 3,
+ "max_nesting": 2,
"nloc": 31,
"has_test_file": false,
"module": "rust",
diff --git a/tests/unit/health/test_dispatch_and_deprecation.py b/tests/unit/health/test_dispatch_and_deprecation.py
index d641673fe..3a5721bab 100644
--- a/tests/unit/health/test_dispatch_and_deprecation.py
+++ b/tests/unit/health/test_dispatch_and_deprecation.py
@@ -552,7 +552,7 @@ def test_a_switch_with_a_tangled_arm_keeps_complex_method() -> None:
def test_nesting_inside_a_switch_arm_is_not_nested_complexity() -> None:
- # switch, case, if, if: four levels, two of them the dispatch's own.
+ # switch, if, if, if: four levels, one of them the dispatch's own.
fns = _functions(
"csharp",
"""class A {
@@ -561,7 +561,7 @@ def test_nesting_inside_a_switch_arm_is_not_nested_complexity() -> None:
case 1: return 1;
case 2: return 2;
default:
- if (ins > 3) { if (fmt == 4) { return 4; } }
+ if (ins > 3) { if (fmt == 4) { if (fmt > 5) { return 4; } } }
return fmt;
}
}
diff --git a/tests/unit/health/test_ff_track_bch_complexity.py b/tests/unit/health/test_ff_track_bch_complexity.py
index 60b8c7ea6..d56c4eebb 100644
--- a/tests/unit/health/test_ff_track_bch_complexity.py
+++ b/tests/unit/health/test_ff_track_bch_complexity.py
@@ -196,7 +196,8 @@ def test_comprehension_filter_does_not_inflate_nesting():
def test_match_case_guard_does_not_inflate_nesting():
# A ``case ... if guard:`` also parses as an ``if_clause``; the guard is a
- # branch point but must not open a nesting level beyond match + case.
+ # branch point but must not open a nesting level beyond the match's one
+ # (its case arms open none).
ccn, max_nesting, _cog, _b, _c = _walk(
"python",
"def f(v):\n"
@@ -204,7 +205,7 @@ def test_match_case_guard_does_not_inflate_nesting():
" case 1 if v > 0:\n return 1\n"
" case _:\n return 0\n",
)
- assert max_nesting == 2
+ assert max_nesting == 1
# The guard still counts toward CCN.
assert ccn >= 3
diff --git a/tests/unit/health/test_switch_arm_nesting.py b/tests/unit/health/test_switch_arm_nesting.py
new file mode 100644
index 000000000..6b16398b2
--- /dev/null
+++ b/tests/unit/health/test_switch_arm_nesting.py
@@ -0,0 +1,139 @@
+"""A switch / match / when opens one nesting level; its case arms open none.
+
+``if { switch { case: if {} } }`` is three levels deep and costs 6 cognitive
+(if +1, switch +2, inner if +3), in every language that has case arms. Arms
+still count toward CCN.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.analysis.health.complexity import walk_file_complexity
+
+_C_LIKE_SWITCH = b"""%s f(%s) {
+ if (y > 0) {
+ switch (x) {
+ case 1:
+ if (y > 2) { return 1; }
+ return 3;
+ default: return 0;
+ }
+ }
+ return 0;
+}"""
+
+# language -> (file name, source, expected ccn)
+_SOURCES = {
+ "c": ("a.c", _C_LIKE_SWITCH % (b"int", b"int x, int y"), 5),
+ "cpp": ("a.cpp", _C_LIKE_SWITCH % (b"int", b"int x, int y"), 5),
+ "javascript": ("a.js", _C_LIKE_SWITCH % (b"function", b"x, y"), 5),
+ "typescript": ("a.ts", _C_LIKE_SWITCH % (b"function", b"x: number, y: number"), 5),
+ "java": ("A.java", b"class A { " + _C_LIKE_SWITCH % (b"int", b"int x, int y") + b" }", 5),
+ "csharp": ("A.cs", b"class A { " + _C_LIKE_SWITCH % (b"int", b"int x, int y") + b" }", 5),
+ "php": (
+ "a.php",
+ b"<?php function f($x, $y) { if ($y > 0) { switch ($x) {"
+ b" case 1: if ($y > 2) { return 1; } return 3; default: return 0; } } return 0; }",
+ 4,
+ ),
+ "go": (
+ "a.go",
+ b"package a\nfunc f(x int, y int) int {\n if y > 0 {\n switch x {\n case 1:\n"
+ b" if y > 2 { return 1 }\n return 3\n default:\n return 0\n }\n }\n return 0\n}\n",
+ 5,
+ ),
+ "swift": (
+ "a.swift",
+ b"func f(x: Int, y: Int) -> Int {\n if y > 0 {\n switch x {\n case 1:\n"
+ b" if y > 2 { return 1 }\n return 3\n default:\n return 0\n }\n }\n return 0\n}\n",
+ 5,
+ ),
+ "rust": (
+ "a.rs",
+ b"fn f(x: i32, y: i32) -> i32 {\n if y > 0 {\n match x {\n"
+ b" 1 => { if y > 2 { return 1; } 3 }\n _ => 0,\n }\n } else { 0 }\n}\n",
+ 5,
+ ),
+ "kotlin": (
+ "a.kt",
+ b"fun f(x: Int, y: Int): Int {\n if (y > 0) {\n when (x) {\n"
+ b" 1 -> { if (y > 2) { return 1 }; return 3 }\n else -> return 0\n }\n }\n return 0\n}\n",
+ 5,
+ ),
+ "ruby": (
+ "a.rb",
+ b"def f(x, y)\n if y > 0\n case x\n when 1\n if y > 2\n return 1\n"
+ b" end\n 3\n else\n 0\n end\n end\nend\n",
+ 4,
+ ),
+ "python": (
+ "a.py",
+ b"def f(x, y):\n if y > 0:\n match x:\n case 1:\n"
+ b" if y > 2:\n return 1\n return 3\n"
+ b" case _:\n return 0\n return 0\n",
+ 5,
+ ),
+}
+
+
+def _walk_one(name: str, language: str, source: bytes):
+ results = walk_file_complexity(name, language, source)
+ if not results:
+ pytest.skip(f"tree-sitter language pack missing for {language}")
+ (fn,) = results
+ return fn
+
+
[email protected]("language", sorted(_SOURCES))
+def test_case_arm_adds_no_nesting_level(language: str) -> None:
+ name, source, ccn = _SOURCES[language]
+ fn = _walk_one(name, language, source)
+ assert (fn.max_nesting, fn.cognitive, fn.ccn) == (3, 6, ccn)
+
+
+def test_java_arrow_switch_expression() -> None:
+ source = b"""class B { int f(int x, int y) {
+ if (y > 0) {
+ return switch (x) {
+ case 1 -> { if (y > 2) { yield 1; } yield 3; }
+ default -> 0;
+ };
+ }
+ return 0;
+} }"""
+ fn = _walk_one("B.java", "java", source)
+ assert (fn.max_nesting, fn.cognitive) == (3, 6)
+
+
+def test_scala_match_guard_adds_no_level() -> None:
+ source = b"""object A { def f(x: Int, y: Int): Int = {
+ if (y > 0) {
+ x match {
+ case 1 if y > 5 => { if (y > 2) { return 1 }; 3 }
+ case _ => 0
+ }
+ } else 0
+} }"""
+ fn = _walk_one("a.scala", "scala", source)
+ # The guard is a flat +1 cognitive, no level.
+ assert (fn.max_nesting, fn.cognitive) == (3, 7)
+
+
+def test_scala_catch_case_still_nests() -> None:
+ # A ``catch`` handler is a ``case_clause`` with no ``match`` above it:
+ # it opens its body's level like any catch.
+ source = b"""object A { def f(y: Int): Int = {
+ try { y } catch { case e: Exception => if (y > 2) { 1 } else { 0 } }
+} }"""
+ fn = _walk_one("a.scala", "scala", source)
+ assert fn.max_nesting == 2
+
+
+def test_python_nesting_without_switch_unchanged() -> None:
+ source = (
+ b"def g(x, y):\n if y > 0:\n for i in x:\n while y:\n"
+ b" if i:\n return 1\n return 0\n"
+ )
+ fn = _walk_one("b.py", "python", source)
+ assert (fn.max_nesting, fn.cognitive) == (4, 10)