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): judge a function that is one dispatch by the code outside it and its heaviest arm (#2915)

Raghav Chamadiya7db2e89e12c9
diff --git a/docs/layers/CODE_HEALTH.md b/docs/layers/CODE_HEALTH.md
index 2356925eb..6ec9ddc30 100644
--- a/docs/layers/CODE_HEALTH.md
+++ b/docs/layers/CODE_HEALTH.md
@@ -42,9 +42,14 @@ this is not a linter.
**`nested_complexity` — pure AST.** tree-sitter parses the file into a syntax
tree. A walker descends it tracking control-flow depth, incrementing on each
`if` / `for` / `while` / `try` / `switch` node. If any function reaches depth 4
-or more, the marker fires, and severity scales with the depth it reached. No
-heuristics about intent, no model, no sampling. The same commit produces the
-same finding forever.
+or more, the marker fires, and severity scales with the depth it reached. A
+function that is mostly one dispatch on one value (a `switch`, `match` or
+same-subject `if` chain holding at least 60% of its decision points) is judged
+by the code around that dispatch and its heaviest arm: `nested_complexity`
+does not count the two levels the `switch` and its `case` open, and
+`complex_method`, `brain_method` and `bumpy_road` read the CCN outside the
+dispatch plus the CCN of its most complex arm. No heuristics about intent, no model, no
+sampling. The same commit produces the same finding forever.
**`io_in_loop` — AST plus call graph.** The walker finds a call inside a loop
body and resolves the callee through the same resolver the dependency graph
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/brain_method.py b/packages/core/src/repowise/core/analysis/health/biomarkers/brain_method.py
index 27ee44166..bc416e539 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/brain_method.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/brain_method.py
@@ -27,6 +27,7 @@ simple synchronous API).
from __future__ import annotations
+from ..complexity.dispatch import judged_ccn
from ..models import Severity
from .base import BiomarkerResult, FileContext
@@ -70,7 +71,7 @@ class BrainMethodDetector:
out: list[BiomarkerResult] = []
for fn in ctx.all_functions:
- severity = self.severity_for(fn.ccn, fn.nloc)
+ severity = self.severity_for(judged_ccn(fn), fn.nloc)
if severity is None:
continue
out.append(
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/bumpy_road.py b/packages/core/src/repowise/core/analysis/health/biomarkers/bumpy_road.py
index fc2d0614d..2b580b1c3 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/bumpy_road.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/bumpy_road.py
@@ -12,6 +12,7 @@ configurable threshold while CCN is also non-trivial.
from __future__ import annotations
+from ..complexity.dispatch import judged_ccn
from ..models import Severity
from .base import BiomarkerResult, FileContext
@@ -28,7 +29,7 @@ class BumpyRoadDetector:
for fn in ctx.all_functions:
if fn.bumps < self._BUMP_THRESHOLD:
continue
- if fn.ccn < self._CCN_THRESHOLD:
+ if judged_ccn(fn) < self._CCN_THRESHOLD:
continue
severity = (
Severity.HIGH
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/complex_method.py b/packages/core/src/repowise/core/analysis/health/biomarkers/complex_method.py
index 2f764cb2d..05253edb3 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/complex_method.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/complex_method.py
@@ -1,11 +1,13 @@
"""Complex Method — high cyclomatic complexity.
Flags functions with CCN ≥ 9. A conservative threshold for the boundary
-between "ok" and "complex".
+between "ok" and "complex". A function that is mostly one dispatch on one
+value is judged on the CCN outside it (``complexity/dispatch.py``).
"""
from __future__ import annotations
+from ..complexity.dispatch import judged_ccn
from ..models import Severity
from .base import BiomarkerResult, FileContext
@@ -26,7 +28,7 @@ class ComplexMethodDetector:
def detect(self, ctx: FileContext) -> list[BiomarkerResult]:
out: list[BiomarkerResult] = []
for fn in ctx.all_functions:
- severity = self.severity_for(fn.ccn, fn.nloc)
+ severity = self.severity_for(judged_ccn(fn), fn.nloc)
if severity is None:
continue
out.append(
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/nested_complexity.py b/packages/core/src/repowise/core/analysis/health/biomarkers/nested_complexity.py
index 87be6a23a..a28af8506 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/nested_complexity.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/nested_complexity.py
@@ -6,6 +6,7 @@ strongly correlated with defect density in published studies.
from __future__ import annotations
+from ..complexity.dispatch import judged_nesting
from ..models import Severity
from .base import BiomarkerResult, FileContext
@@ -19,13 +20,14 @@ class NestedComplexityDetector:
def detect(self, ctx: FileContext) -> list[BiomarkerResult]:
out: list[BiomarkerResult] = []
for fn in ctx.all_functions:
- if fn.max_nesting < self._NESTING_THRESHOLD:
+ depth = judged_nesting(fn)
+ if depth < self._NESTING_THRESHOLD:
continue
severity = (
Severity.CRITICAL
- if fn.max_nesting >= 7
+ if depth >= 7
else Severity.HIGH
- if fn.max_nesting >= 5
+ if depth >= 5
else Severity.MEDIUM
)
out.append(
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 806ba1d62..68c7410c4 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/dispatch.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/dispatch.py
@@ -7,19 +7,22 @@ construction: a per-node-type handler adds one arm per case, and the arms are
independent of each other. ``dispatch_share`` lets a reader tell that shape
apart from a function that is complex all over.
+A complexity marker reads a function at or above :data:`DISPATCH_SHARE`
+through :func:`judged_ccn` and :func:`judged_nesting`: the decision points
+outside its one dispatch plus those of its heaviest arm, and its nesting less
+the levels the dispatch opens. A per-case handler is flagged when the code
+around the dispatch, or one of its arms, is complex on its own.
+
The share is the decision points inside that one branch, arms and everything
nested in them, over the function's decision points (CCN minus the entry
path). It counts the same nodes :mod:`.cyclomatic` charged, so a flat switch
-that CCN charges one point is one point here too. It is a fact read beside
-CCN; it changes no CCN, threshold or score.
+that CCN charges one point is one point here too. It changes no stored CCN.
"Top level" means not nested inside another branch, case or catch. Loops,
``try`` / ``with`` blocks and closures are walked through, since a visitor's
dispatch usually sits inside the loop that reads the next token, and a
middleware factory's inside the closure it returns.
-The 0.6 cut a consumer reads it against was fitted on labelled dev repos (see
-the tests); it is not a property of the fact.
"""
from __future__ import annotations
@@ -40,11 +43,22 @@ if TYPE_CHECKING:
from tree_sitter import Node
from .languages import LanguageNodeMap
+ from .models import FunctionComplexity
+
+#: A function whose largest dispatch on one value holds this share of its
+#: 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.
+_DISPATCH_LEVELS = 2
# An ``if`` with one ``elif`` is a decision, not a dispatch; the same holds for
# a run of guards.
_MIN_ARMS = 3
+# The ``else`` part of an ``if`` where a grammar gives it no ``alternative`` field.
+_ELSE_KINDS = frozenset({"else_clause", "else"})
_WRAPPER_KINDS = frozenset({"parenthesized_expression", "condition_clause"})
_COMPARISON_KINDS = frozenset(
{
@@ -62,8 +76,11 @@ _COMPARISON_KINDS = frozenset(
_TYPE_TEST_FUNCTIONS = frozenset({"isinstance", "issubclass", "type", "hasattr"})
# Methods that test their receiver.
_RECEIVER_TESTS = frozenset(
- {"equals", "equalsignorecase", "is_a?", "kind_of?", "instance_of?", "startswith"}
+ {"equals", "equalsignorecase", "matches", "is_a?", "kind_of?", "instance_of?", "startswith"}
)
+# A receiver that names a constant (``FormatNames.ISO8601.matches(input)``) is
+# the arm's key, so the test is on its argument.
+_CONSTANT_RE = re.compile(r"^[A-Z][A-Z0-9_]*$")
_LITERAL_MARKERS = ("string", "integer", "number", "float", "true", "false", "null", "nil", "char")
_MAX_SUBJECT_CHARS = 80
_SPACE_RE = re.compile(r"\s+")
@@ -111,6 +128,14 @@ def _call_parts(node: Node) -> tuple[str, Node | None, list[Node]]:
return name.rsplit(".", 1)[-1].lower(), receiver, args
+def _receiver_test_subject(receiver: Node | None, args: list[Node]) -> str | None:
+ """``x.equals(y)`` tests ``x``, unless ``x`` is a literal or a constant key."""
+ subject = _name(receiver)
+ if subject is not None and _CONSTANT_RE.match(subject.rsplit(".", 1)[-1]):
+ subject = None
+ return subject or (_name(args[0]) if args else None)
+
+
def _subject(node: Node | None, lmap: LanguageNodeMap) -> str | None:
"""The one name a condition tests, ``None`` when it tests no single one."""
node = _unwrap(node)
@@ -132,7 +157,7 @@ def _subject(node: Node | None, lmap: LanguageNodeMap) -> str | None:
if name in _TYPE_TEST_FUNCTIONS and receiver is None and args:
return _name(args[0])
if name in _RECEIVER_TESTS:
- return _name(receiver) or (_name(args[0]) if args else None)
+ return _receiver_test_subject(receiver, args)
return None
@@ -159,13 +184,14 @@ def _one_subject(arms: list[Node], lmap: LanguageNodeMap) -> bool:
return len(subjects) == 1 and None not in subjects
+def _is_chain_head(node: Node) -> bool:
+ """An ``if`` that starts a chain rather than continuing one."""
+ return node.type in _ELSE_IF_NODE_KINDS and not _is_elif_continuation(node)
+
+
def _is_lone_if(node: Node) -> bool:
"""An ``if`` that neither continues nor is continued by an ``elif``."""
- return (
- node.type in _ELSE_IF_NODE_KINDS
- and not _is_elif_continuation(node)
- and len(_chain_arms(node)) == 1
- )
+ return _is_chain_head(node) and len(_chain_arms(node)) == 1
def _has_subject(node: Node) -> bool:
@@ -185,11 +211,43 @@ class _Siblings(NamedTuple):
children: list[Node]
+class Dispatch(NamedTuple):
+ """A function's largest dispatch: its decision points and its heaviest arm's."""
+
+ points: int = 0
+ arm: int = 0
+
+
def _points(nodes: list[Node], lmap: LanguageNodeMap) -> int:
"""Decision points the CCN walk charges inside *nodes*."""
return _walk_function_body(_Siblings(nodes), lmap)[0] - 1 # type: ignore[arg-type]
+def _if_arm_points(node: Node, lmap: LanguageNodeMap) -> int:
+ """Decision points in one ``if`` arm's body, not its condition or ``else``."""
+ skip = {
+ c.id
+ for c in (node.child_by_field_name("condition"), node.child_by_field_name("alternative"))
+ if c is not None
+ }
+ body = [
+ c
+ for c in node.named_children
+ if c.id not in skip and c.type not in _ELSE_KINDS and not _is_elif_continuation(c)
+ ]
+ return _points(body, lmap)
+
+
+def _if_dispatch(nodes: list[Node], arms: list[Node], lmap: LanguageNodeMap) -> Dispatch:
+ """A same-subject ``if`` chain (one node) or guard run (its ``if`` nodes)."""
+ return Dispatch(_points(nodes, lmap), max(_if_arm_points(a, lmap) for a in arms))
+
+
+def _switch_dispatch(node: Node, cases: list[Node], lmap: LanguageNodeMap) -> Dispatch:
+ """A ``switch`` / ``match``; an arm's own case point is the dispatch's, not the arm's."""
+ return Dispatch(_points([node], lmap), max(_points([c], lmap) - 1 for c in cases))
+
+
def _guard_runs(children: list[Node], lmap: LanguageNodeMap) -> list[list[Node]]:
"""Runs of three or more consecutive sibling ``if`` guards on one subject."""
runs: list[list[Node]] = []
@@ -210,36 +268,62 @@ def _guard_runs(children: list[Node], lmap: LanguageNodeMap) -> list[list[Node]]
return runs
-def dispatch_points(body: Node, lmap: LanguageNodeMap) -> int:
- """Decision points inside the largest top-level dispatch on one subject."""
+def _node_dispatch(node: Node, lmap: LanguageNodeMap) -> Dispatch | None:
+ """*node* as a ``switch`` on a subject or the head of a same-subject ``if`` chain."""
+ if node.type in lmap.switch_kinds:
+ cases = [c for c in _collect_case_children(node, lmap) if c.is_named]
+ return _switch_dispatch(node, cases, lmap) if cases and _has_subject(node) else None
+ if node.type not in lmap.branch_kinds or not _is_chain_head(node):
+ return None
+ arms = _chain_arms(node)
+ return _if_dispatch([node], arms, lmap) if _one_subject(arms, lmap) else None
+
+
+def _dispatches(children: list[Node], lmap: LanguageNodeMap) -> list[Dispatch]:
+ """Every dispatch among one parent's *children*: guard runs, chains, switches."""
+ found = [_if_dispatch(run, run, lmap) for run in _guard_runs(children, lmap)]
+ found.extend(d for c in children if (d := _node_dispatch(c, lmap)) is not None)
+ return found
+
+
+def dispatch_points(body: Node, lmap: LanguageNodeMap) -> Dispatch:
+ """The largest top-level dispatch on one subject, by decision points."""
stop_kinds = lmap.case_kinds | lmap.catch_kinds | lmap.function_kinds
- best = 0
+ descend_past = stop_kinds | lmap.switch_kinds | lmap.branch_kinds
+ best = Dispatch()
stack: list[Node] = [body]
while stack:
- parent = stack.pop()
- children = [c for c in parent.children if c.is_named]
- for run in _guard_runs(children, lmap):
- best = max(best, _points(run, lmap))
- for node in children:
- if node.type in lmap.switch_kinds:
- if _has_subject(node) and any(
- c.is_named for c in _collect_case_children(node, lmap)
- ):
- best = max(best, _points([node], lmap))
- continue
- if node.type in lmap.branch_kinds:
- if (
- node.type in _ELSE_IF_NODE_KINDS
- and not _is_elif_continuation(node)
- and _one_subject(_chain_arms(node), lmap)
- ):
- best = max(best, _points([node], lmap))
- continue
- if node.type not in stop_kinds:
- stack.append(node)
+ children = [c for c in stack.pop().children if c.is_named]
+ best = max([best, *_dispatches(children, lmap)])
+ stack.extend(c for c in children if c.type not in descend_past)
return best
def dispatch_share(points: int, ccn: int) -> float:
"""*points* as a fraction of the function's decision points, to two decimals."""
return round(points / (ccn - 1), 2) if ccn > 1 and points > 0 else 0.0
+
+
+def judged_ccn(fn: FunctionComplexity) -> int:
+ """The CCN a complexity marker judges *fn* by.
+
+ Below :data:`DISPATCH_SHARE` that is its CCN. At or above it, the points
+ outside the dispatch plus its heaviest arm's: a switch of one-line cases
+ reads as the code around it, one with a tangled arm as that arm.
+ """
+ if fn.dispatch_share < DISPATCH_SHARE:
+ return fn.ccn
+ return fn.ccn - round(fn.dispatch_share * (fn.ccn - 1)) + fn.dispatch_arm
+
+
+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
+ dispatch is under-read by the same amount (the ceiling of not tracking
+ which side the deepest block is on).
+ """
+ if fn.dispatch_share < DISPATCH_SHARE:
+ return fn.max_nesting
+ return max(fn.max_nesting - _DISPATCH_LEVELS, 0)
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 f108187b9..ad179b9e5 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/models.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/models.py
@@ -112,9 +112,12 @@ class FunctionComplexity:
bare_called_names: frozenset[str] = frozenset()
# CCN points of the largest top-level ``switch`` / ``match`` / same-subject
# ``if`` chain, over ``ccn``, to two decimals. Near 1.0 the function is
- # one dispatch on one value. Read beside CCN, never in place of it.
- # ``complexity/dispatch.py``.
+ # one dispatch on one value. At ``DISPATCH_SHARE`` and above the size and
+ # complexity markers judge the function outside it. ``complexity/dispatch.py``.
dispatch_share: float = 0.0
+ # CCN points inside that dispatch's heaviest arm, its own case point not
+ # counted: a switch of one-line cases has 0.
+ dispatch_arm: int = 0
# True when the declaration is marked deprecated or the body's top level
# issues a deprecation warning. ``complexity/deprecation.py``.
deprecated: bool = False
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/walker.py b/packages/core/src/repowise/core/analysis/health/complexity/walker.py
index 34107f647..25f18b0a1 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/walker.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/walker.py
@@ -177,6 +177,7 @@ def walk_file(
) = _collect_assertion_facts(body, lmap, asserts)
name = _find_function_entry_name(fn_node, lmap)
typed, scalar = typed_param_counts(_parameter_list(fn_node), lmap)
+ dispatch = dispatch_points(body, lmap)
fc = FunctionComplexity(
name=name,
start_line=fn_node.start_point[0] + 1,
@@ -200,7 +201,8 @@ def walk_file(
is_test_case=is_test_case(fn_node, name, language),
called_names=called,
bare_called_names=bare_called,
- dispatch_share=dispatch_share(dispatch_points(body, lmap), ccn),
+ dispatch_share=dispatch_share(dispatch.points, ccn),
+ dispatch_arm=dispatch.arm,
deprecated=is_deprecated(fn_node, body, name, lmap, source),
deepest_block=(deepest[0], deepest[1]) if deepest else None,
)
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 e0355b775..a99e5ef71 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
@@ -51,6 +51,7 @@ from dataclasses import dataclass
from typing import Any
from repowise.core.analysis.finding_registry import excluded_types
+from repowise.core.analysis.health.complexity.dispatch import DISPATCH_SHARE
from repowise.core.analysis.health.models import primary_finding, split_by_origin
from repowise.core.analysis.health.perf.causal import code_context
from repowise.core.analysis.health.perf.opportunity_rank import (
@@ -131,10 +132,6 @@ DEFAULT_LIMIT = 10
SIZE_MARKERS = frozenset(
{"complex_method", "nested_complexity", "brain_method", "large_method", "bumpy_road"}
)
-#: A function whose largest dispatch on one value holds this share of its
-#: decision points is usually fine as it is. Fitted on the dev labels only:
-#: share >= 0.6 held 9 labelled complexity rows, 8 of them rejected.
-DISPATCH_SHARE = 0.6
#: A function-level complexity unit needs this many code lines or this CCN.
#: Picked on the dev labels (67 complexity rows): 30 / 15 drops 13 rejected
#: small functions and 4 accepted ones; no cut that keeps every accepted row
diff --git a/tests/unit/change_health/conftest.py b/tests/unit/change_health/conftest.py
index 11069ce40..2cd20d384 100644
--- a/tests/unit/change_health/conftest.py
+++ b/tests/unit/change_health/conftest.py
@@ -70,13 +70,14 @@ def make_repo(tmp_path: Path) -> Callable[[str], Repo]:
# -- source builders --------------------------------------------------------
# Each returns a function body whose complexity is driven by *branches*, so a
# test can ask for "the same function, more complex" in any language without
-# hand-writing both revisions.
+# hand-writing both revisions. Every guard tests a different expression, so the
+# body is complex all over rather than one dispatch on ``value``.
def python_complex(name: str, branches: int, *, indent: str = "") -> str:
lines = [f"{indent}def {name}(value):"]
for i in range(branches):
- lines.append(f"{indent} if value == {i} and value > {i - 1}:")
+ lines.append(f"{indent} if value % {i + 2} == 0 and value > {i - 1}:")
lines.append(f"{indent} value = value + {i}")
lines.append(f"{indent} return value")
return "\n".join(lines) + "\n"
@@ -85,7 +86,7 @@ def python_complex(name: str, branches: int, *, indent: str = "") -> str:
def typescript_complex(name: str, branches: int) -> str:
lines = [f"export function {name}(value: number): number {{"]
for i in range(branches):
- lines.append(f" if (value === {i} && value > {i - 1}) {{")
+ lines.append(f" if (value % {i + 2} === 0 && value > {i - 1}) {{")
lines.append(f" value = value + {i};")
lines.append(" }")
lines.append(" return value;")
@@ -96,7 +97,7 @@ def typescript_complex(name: str, branches: int) -> str:
def go_complex(name: str, branches: int) -> str:
lines = ["package main", "", f"func {name}(value int) int {{"]
for i in range(branches):
- lines.append(f"\tif value == {i} && value > {i - 1} {{")
+ lines.append(f"\tif value%{i + 2} == 0 && value > {i - 1} {{")
lines.append(f"\t\tvalue = value + {i}")
lines.append("\t}")
lines.append("\treturn value")
diff --git a/tests/unit/health/test_dispatch_and_deprecation.py b/tests/unit/health/test_dispatch_and_deprecation.py
index b17583455..a6e72f965 100644
--- a/tests/unit/health/test_dispatch_and_deprecation.py
+++ b/tests/unit/health/test_dispatch_and_deprecation.py
@@ -2,7 +2,8 @@
``dispatch_share`` is the share of a function's decision points that sit
inside its largest top-level dispatch on one subject, arms and what they nest. ``deprecated`` is a declaration marker or a
-top-level deprecation warning. Neither moves a CCN, threshold or score.
+top-level deprecation warning. The size and complexity markers judge a function
+mostly made of one dispatch outside it.
"""
from __future__ import annotations
@@ -11,7 +12,10 @@ from types import SimpleNamespace
import pytest
+from repowise.core.analysis.health.biomarkers.complex_method import ComplexMethodDetector
+from repowise.core.analysis.health.biomarkers.nested_complexity import NestedComplexityDetector
from repowise.core.analysis.health.complexity import walk_file
+from repowise.core.analysis.health.complexity.dispatch import judged_ccn, judged_nesting
from repowise.core.analysis.health.duplication import DuplicationReport
from repowise.core.analysis.health.engine import HealthAnalyzer
from repowise.core.analysis.health.finding_identity import finding_public_id
@@ -205,10 +209,22 @@ def test_java_switch_and_equals_chain() -> None:
if ("a".equals(cmd)) {} else if ("b".equals(cmd)) {} else if ("c".equals(cmd)) {}
return 0;
}
+ int h(String p) {
+ if (Names.ISO.matches(p)) {} else if (Names.BASIC_DATE.matches(p)) {} else if (Names.TIME.matches(p)) {}
+ return 0;
+ }
+ int k(String p) {
+ if (iso.matches(p)) {} else if (basic.matches(p)) {} else if (time.matches(p)) {}
+ return 0;
+ }
}""",
)
assert fns["f"].dispatch_share == 0.75
assert fns["g"].dispatch_share == 1.0
+ # A constant receiver is the arm's key: the chain tests ``p``.
+ assert fns["h"].dispatch_share == 1.0
+ # Three different variables test ``p``; nothing says they are keys.
+ assert fns["k"].dispatch_share == 0.0
def test_csharp_flat_switch_expression_is_one_point() -> None:
@@ -377,7 +393,7 @@ export const serveStatic = (options: {
_TANGLED = b"""
import warnings
-def tangled(x):
+def tangled(x, y):
warnings.warn("tangled is deprecated", DeprecationWarning)
total = 0
if x == 1:
@@ -390,16 +406,37 @@ def tangled(x):
total += 4
elif x == 5:
total += 5
- elif x == 6:
+ if y == 6:
total += 6
- elif x == 7:
+ elif y == 7:
total += 7
- elif x == 8:
+ elif y == 8:
total += 8
- elif x == 9:
+ elif y == 9:
total += 9
return total
+def lookup(x):
+ if x == 1:
+ return 1
+ elif x == 2:
+ return 2
+ elif x == 3:
+ return 3
+ elif x == 4:
+ return 4
+ elif x == 5:
+ return 5
+ elif x == 6:
+ return 6
+ elif x == 7:
+ return 7
+ elif x == 8:
+ return 8
+ elif x == 9:
+ return 9
+ return 0
+
def fine():
return 1
"""
@@ -428,11 +465,17 @@ def _evaluate(path: str):
def test_complexity_findings_carry_dispatch_share_and_deprecated() -> None:
_, findings, _ = _evaluate("src/tangled.py")
complex_method = next(f for f in findings if f.biomarker_type == "complex_method")
- # The chain holds all nine decision points.
- assert complex_method.details["dispatch_share"] == 1.0
+ # The larger chain holds five of the nine decision points.
+ assert complex_method.details["dispatch_share"] == 0.56
assert complex_method.details["deprecated"] is True
+def test_a_function_that_is_one_dispatch_earns_no_complex_method() -> None:
+ # ``lookup`` is CCN 10, every point in one chain on ``x``.
+ _, findings, _ = _evaluate("src/tangled.py")
+ assert not [f for f in findings if f.function_name == "lookup"]
+
+
def test_metric_carries_code_origin() -> None:
assert _evaluate("src/tangled.py")[0].code_origin == "production"
assert _evaluate("docs_src/tutorial/tangled.py")[0].code_origin == "docs_example"
@@ -453,3 +496,83 @@ def test_new_detail_keys_leave_the_finding_id_unchanged() -> None:
**{**base.__dict__, "details": {**base.details, "dispatch_share": 0.8, "deprecated": True}}
)
assert finding_public_id(annotated) == finding_public_id(base)
+
+
+ ("ccn", "share", "arm", "judged"),
+ [(30, 0.5, 0, 30), (30, 0.6, 0, 13), (12, 1.0, 0, 1), (250, 0.87, 0, 33), (37, 0.94, 12, 15)],
+)
+def test_judged_ccn_reads_outside_a_dominant_dispatch_and_its_heaviest_arm(
+ ccn: int, share: float, arm: int, judged: int
+) -> None:
+ fn = SimpleNamespace(ccn=ccn, dispatch_share=share, dispatch_arm=arm)
+ assert judged_ccn(fn) == judged
+
+
+def test_judged_nesting_drops_the_dispatch_levels() -> None:
+ assert judged_nesting(SimpleNamespace(max_nesting=4, dispatch_share=0.59)) == 4
+ assert judged_nesting(SimpleNamespace(max_nesting=4, dispatch_share=1.0)) == 2
+ assert judged_nesting(SimpleNamespace(max_nesting=7, dispatch_share=0.97)) == 5
+
+
+def test_heaviest_arm_is_what_the_arm_itself_charges() -> None:
+ fns = _functions(
+ "csharp",
+ """class A {
+ int Flat(int k) { switch (k) { case 1: return 1; case 2: return 2; case 3: return 3; } return 0; }
+ int Fat(int k, int a, int b) {
+ switch (k) {
+ case 1: if (a > 0) { if (b > 0) { return 1; } } return 0;
+ case 2: return 2;
+ case 3: return 3;
+ }
+ return 0;
+ }
+ int Chain(int k, int a) {
+ if (k == 1) { if (a > 0) { return 1; } } else if (k == 2) { return 2; } else if (k == 3) { return 3; }
+ return 0;
+ }
+}""",
+ )
+ assert fns["Flat"].dispatch_arm == 0
+ assert fns["Fat"].dispatch_arm == 2
+ assert fns["Chain"].dispatch_arm == 1
+
+
+def test_a_switch_with_a_tangled_arm_keeps_complex_method() -> None:
+ arm = "".join(f"if (a > {i}) {{ total += {i}; }} " for i in range(9))
+ cases = "".join(f"case {i}: return {i}; " for i in range(2, 12))
+ fns = _functions(
+ "csharp",
+ f"class A {{ int F(int k, int a) {{ int total = 0; switch (k) {{ case 1: {arm}return total; {cases}}} return 0; }} }}",
+ )
+ fn = fns["F"]
+ assert fn.dispatch_share >= 0.6 and fn.dispatch_arm == 9
+ ctx = SimpleNamespace(all_functions=[fn])
+ assert [r.function_name for r in ComplexMethodDetector().detect(ctx)] == ["F"]
+
+
+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.
+ fns = _functions(
+ "csharp",
+ """class A {
+ int F(int ins, int fmt) {
+ switch (ins) {
+ case 1: return 1;
+ case 2: return 2;
+ default:
+ if (ins > 3) { if (fmt == 4) { return 4; } }
+ return fmt;
+ }
+ }
+ int G(int a, int b, int c, int d) {
+ if (a > 0) { if (b > 0) { if (c > 0) { if (d > 0) { return 1; } } } }
+ return 0;
+ }
+}""",
+ )
+ ctx = SimpleNamespace(all_functions=list(fns.values()))
+ flagged = {r.function_name for r in NestedComplexityDetector().detect(ctx)}
+ assert fns["F"].max_nesting == 4 and fns["F"].dispatch_share >= 0.6
+ assert flagged == {"G"}