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): hold a flat boolean chain at low in complex_conditional (#3665)

Swati Ahuja57ceca85538d
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/complex_conditional.py b/packages/core/src/repowise/core/analysis/health/biomarkers/complex_conditional.py
index 6c9c4ecb0..657cf178f 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/complex_conditional.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/complex_conditional.py
@@ -7,6 +7,10 @@ already harder to read at a glance than a single equality; six-operator
conditions are routinely cited in defect-mining studies as the noisy
end of a branch's lifetime.
+A flat chain of one operator with no negation (``a || b || c || d``)
+reads as a list of alternatives, not a knot, so it stays LOW however
+long it runs; ``details.flat_chain`` says so.
+
Category: ``structural_complexity``.
Consumes ``FunctionComplexity.complex_conditions`` — collected by the
@@ -47,13 +51,18 @@ class ComplexConditionalDetector:
out.append(
BiomarkerResult(
biomarker_type=self.name,
- severity=_severity_for(cond.operator_count),
+ severity=(
+ Severity.LOW
+ if cond.flat_chain
+ else _severity_for(cond.operator_count)
+ ),
function_name=fc.name,
line_start=cond.line,
line_end=cond.line,
details={
"operator_count": cond.operator_count,
"enclosing_construct": cond.enclosing_construct,
+ "flat_chain": cond.flat_chain,
"dispatch_share": fc.dispatch_share,
},
reason=(
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 f7adba95f..a5e2b8e35 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py
@@ -181,16 +181,48 @@ def _is_flat_ternary(node: Node, lmap: LanguageNodeMap, in_markup: bool) -> bool
)
-def _count_boolean_ops_in_condition(node: Node, lmap: LanguageNodeMap) -> int:
+_AND_TOKENS = (b"&&", b"and")
+_OR_TOKENS = (b"||", b"or")
+# A prefix ``!`` / ``not`` (Swift spells it ``bang``). A postfix one (``a!``)
+# has a sibling before it, and Python's ``is not`` / ``not in`` are unnamed
+# operator nodes: neither negates a condition.
+_NEGATION_TOKENS = frozenset({"!", "not", "bang"})
+
+
+def _operator_kind(node: Node) -> str:
+ """``"and"`` / ``"or"`` for a boolean operator node, else its node type."""
+ for tok in (node, *node.children):
+ if tok.child_count == 0 and tok.text in _AND_TOKENS:
+ return "and"
+ if tok.child_count == 0 and tok.text in _OR_TOKENS:
+ return "or"
+ # Grammars with one node type per operator (Kotlin, Dart) name the kind.
+ return node.type
+
+
+def _is_negation(node: Node) -> bool:
+ if node.type not in _NEGATION_TOKENS or node.prev_sibling is not None:
+ return False
+ return node.parent is not None and node.parent.is_named
+
+
+def _count_boolean_ops_in_condition(
+ node: Node, lmap: LanguageNodeMap
+) -> tuple[int, set[str], bool]:
"""Count ``&&`` / ``||`` / ``and`` / ``or`` operators in a condition.
+ Returns ``(count, operator kinds, negated)``. One kind and no negation
+ is a flat chain (``a || b || c``) that reads as a list, not a knot.
+
Walks the subtree rooted at *node* but does not descend into nested
function bodies (lambdas / closures used as condition values are
rare and would skew the count).
"""
- if node is None:
- return 0
count = 0
+ kinds: set[str] = set()
+ negated = False
+ if node is None:
+ return count, kinds, negated
stack: list[Node] = [node]
while stack:
cur = stack.pop()
@@ -201,9 +233,12 @@ def _count_boolean_ops_in_condition(node: Node, lmap: LanguageNodeMap) -> int:
continue
if _is_boolean_operator(cur, lmap):
count += 1
+ kinds.add(_operator_kind(cur))
+ elif _is_negation(cur):
+ negated = True
for child in cur.children:
stack.append(child)
- return count
+ return count, kinds, negated
def _enclosing_construct(node: Node, lmap: LanguageNodeMap) -> str:
@@ -427,14 +462,20 @@ def _walk_function_body(
# (boolean operators are still tallied independently by
# the regular recursion below).
op_count = 0
+ op_kinds: set[str] = set()
+ negated = False
for sub in _condition_subtrees(node):
- op_count += _count_boolean_ops_in_condition(sub, lmap)
+ sub_count, sub_kinds, sub_negated = _count_boolean_ops_in_condition(sub, lmap)
+ op_count += sub_count
+ op_kinds |= sub_kinds
+ negated = negated or sub_negated
if op_count > 0:
conditions.append(
ConditionComplexity(
line=node.start_point[0] + 1,
operator_count=op_count,
enclosing_construct=_enclosing_construct(node, lmap),
+ flat_chain=len(op_kinds) == 1 and not negated,
)
)
elif node.is_named and node.type in lmap.try_kinds:
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/models.py b/packages/core/src/repowise/core/analysis/health/complexity/models.py
index 443dfea14..42654d71f 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/models.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/models.py
@@ -27,6 +27,8 @@ class ConditionComplexity:
line: int # 1-indexed start line of the enclosing construct
operator_count: int
enclosing_construct: str # "if" | "while" | "for" | "ternary" | "case"
+ # One operator kind and no negation (``a || b || c``): a list, not a knot.
+ flat_chain: bool = False
@dataclass
diff --git a/tests/unit/health/test_complex_conditional.py b/tests/unit/health/test_complex_conditional.py
index 23b75d409..39003441f 100644
--- a/tests/unit/health/test_complex_conditional.py
+++ b/tests/unit/health/test_complex_conditional.py
@@ -53,10 +53,11 @@ def _assert_three_six_two(metrics, three: str, six: str, two: str):
assert by_fn[three].severity == Severity.LOW
assert by_fn[three].details["operator_count"] == 3
- # 6-op → CRITICAL
+ # 6-op flat ``&&`` chain → flagged, but held at LOW
assert six in by_fn, f"expected finding on {six} (6-op condition)"
- assert by_fn[six].severity == Severity.CRITICAL
+ assert by_fn[six].severity == Severity.LOW
assert by_fn[six].details["operator_count"] == 6
+ assert by_fn[six].details["flat_chain"] is True
# 2-op → not flagged
assert two not in by_fn, f"{two} (2-op) should not flag"
@@ -99,3 +100,62 @@ def test_walker_emits_complex_conditions_field():
assert cond.enclosing_construct == "while"
# Existing CCN field must still be populated (regression guard).
assert fc.ccn >= 7 # entry + while + 6 booleans
+
+
+def _conditions(source: str, language: str, name: str):
+ results = walk_file_complexity(f"x.{language}", language, source.encode())
+ if not results:
+ pytest.skip(f"tree-sitter language pack missing for {language}")
+ fc = _find(results, name)
+ assert fc is not None
+ return fc
+
+
+ ("condition", "count", "flat"),
+ [
+ ("a === 1 || b === 2 || c === 3 || d === 4 || e === 5 || g === 6 || h === 7", 6, True),
+ ("a && b && c && d && e && g && h", 6, True),
+ ("a && b || c && d || e && g || h", 6, False),
+ ("a || b || c || !d || e || g || h", 6, False),
+ ("a !== b || c != d || e || g || h || i || j!", 6, True),
+ ],
+)
+def test_flat_chain_typescript(condition: str, count: int, flat: bool):
+ src = f"function f(a, b, c, d, e, g, h, i, j) {{ if ({condition}) {{ return 1; }} return 0; }}"
+ cond = _conditions(src, "typescript", "f").complex_conditions[0]
+ assert cond.operator_count == count
+ assert cond.flat_chain is flat
+
+
+ ("condition", "flat"),
+ [
+ ("a or b or c or d", True),
+ ("a and b and c is not None and d not in e", True),
+ ("a and b or c and d", False),
+ ("a and not b and c and d", False),
+ ],
+)
+def test_flat_chain_python(condition: str, flat: bool):
+ src = f"def f(a, b, c, d, e):\n if {condition}:\n return 1\n return 0\n"
+ cond = _conditions(src, "python", "f").complex_conditions[0]
+ assert cond.operator_count == 3
+ assert cond.flat_chain is flat
+
+
+def test_flat_chain_holds_low_and_mixed_keeps_count_severity():
+ src = (
+ "function flat(a, b, c, d, e, g, h) { if (a || b || c || d || e || g || h) { return 1; } }\n"
+ "function knot(a, b, c, d, e, g, h) { if (a && b || c && !d || e && g || h) { return 1; } }\n"
+ "function mixedLow(a, b, c, d) { if (a && b || c && d) { return 1; } }\n"
+ )
+ results = walk_file_complexity("x.ts", "typescript", src.encode())
+ if not results:
+ pytest.skip("tree-sitter language pack missing for typescript")
+ by_fn = {f.function_name: f for f in ComplexConditionalDetector().detect(_ctx(results))}
+ assert by_fn["flat"].severity == Severity.LOW
+ assert by_fn["flat"].details["operator_count"] == 6
+ assert by_fn["knot"].severity == Severity.CRITICAL
+ assert by_fn["knot"].details["flat_chain"] is False
+ assert by_fn["mixedLow"].severity == Severity.LOW