Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(health): give Dart constructors, accessors and operators distinct names and count bare on handlers (#4782)
Raghav Chamadiya9df572bf446f
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/ast_utils.py b/packages/core/src/repowise/core/analysis/health/complexity/ast_utils.pyindex a200adbe4..5b1875c8b 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/ast_utils.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/ast_utils.py@@ -364,12 +364,37 @@ def _dart_signature_sibling(body: Node) -> Node | None:return sib+_DART_ACCESSOR_PREFIX = {"getter_signature": "get", "setter_signature": "set"}+++def _dart_signature_name(sig: Node) -> str:+ """``A`` / ``A.named`` for a constructor, ``get x`` / ``set x`` for an+ accessor, ``operator ==`` for an operator, so no two members of one+ class share a name."""+ if sig.type in ("constructor_signature", "factory_constructor_signature"):+ return ".".join(_node_text(c) for c in sig.children if c.type == "identifier")+ if sig.type in _DART_ACCESSOR_PREFIX:+ return f"{_DART_ACCESSOR_PREFIX[sig.type]} {_find_name(sig)}"+ if sig.type == "operator_signature":+ # The symbol sits between the ``operator`` keyword and the parameters.+ kinds = [c.type for c in sig.children]+ start = kinds.index("operator") + 1 if "operator" in kinds else len(kinds)+ symbol = "".join(+ _node_text(c) for c in sig.children[start:] if c.type != "formal_parameter_list"+ )+ params = next((c for c in sig.children if c.type == "formal_parameter_list"), None)+ if symbol == "-" and params is not None and params.named_child_count == 0:+ symbol = "unary-" # Dart's own name, apart from binary ``-``+ return f"operator {symbol}"+ return _find_name(sig)++def _find_function_entry_name(node: Node, lmap: LanguageNodeMap) -> str:if node.type not in lmap.lambda_kinds:if node.type == "function_body":sig = _dart_signature_sibling(node)if sig is not None:- return _find_name(sig)+ return _dart_signature_name(sig)return _find_name(node)assigned = _find_assigned_lambda_name(node)if assigned:diff --git a/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py b/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.pyindex 5357edccf..a94101c7b 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py@@ -415,6 +415,8 @@ def _walk_function_body(# switch count toward CCN but sit in the level their switch opened.flat_arm_ids: set[int] = set()switch_arm_ids: set[int] = set()+ # Dart ``on T { }`` handlers with no ``catch``: see ``_bare_on_handlers``.+ bare_handler_ids: set[int] = set()deepest_depth = 0deepest_node: list[Node] = []@@ -463,32 +465,17 @@ def _walk_function_body(or _is_flat_ternary(node, lmap, in_markup)):nesting_increment = 1- # Side-channel: count compound boolean ops in this- # construct's condition. Does not affect ccn/cognitive- # (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, 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,- )- )+ # Side-channel: does not affect ccn/cognitive (boolean operators+ # are still tallied independently by the regular recursion below).+ conditions.extend(_compound_condition(node, lmap))+ elif node.id in bare_handler_ids:+ # A bare ``on T { }`` handler branches and nests like a catch clause.+ ccn_increment = nesting_increment = 1elif node.is_named and node.type in lmap.try_kinds:# TRY neither branches nor nests: each catch opens the level for# its own body, and the guarded and finally bodies stay at the# try's depth (Sonar's cognitive complexity spec).- pass+ bare_handler_ids.update(_bare_on_handlers(node))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.@@ -558,6 +545,51 @@ def _walk_function_body(return ccn, max_nesting, cognitive, bumps, conditions+def _compound_condition(node: Node, lmap: LanguageNodeMap) -> list[ConditionComplexity]:+ """The compound boolean ops in *node*'s condition, as one record or none."""+ op_count = 0+ op_kinds: set[str] = set()+ negated = False+ for sub in _condition_subtrees(node, 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:+ return []+ return [+ 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,+ )+ ]+++def _bare_on_handlers(try_node: Node) -> list[int]:+ """Ids of the type node opening each Dart ``on T { }`` handler.++ The grammar gives ``on T catch (e)`` and ``catch (e)`` a ``catch_clause``+ but leaves a bare ``on T`` as loose tokens beside its block, so the walk+ counts the type node in its place. Other grammars have no ``on`` token here.+ """+ out: list[int] = []+ arm: Node | None = None+ after_on = False+ for child in try_node.children:+ if child.type == "on":+ after_on, arm = True, None+ elif child.type == "catch_clause":+ after_on, arm = False, None+ elif after_on and arm is None and child.is_named:+ arm = child+ elif child.type == "block" and arm is not None:+ out.append(arm.id)+ after_on, arm = False, None+ return out++#: The smallest block named as the place to start flattening a function.MIN_BLOCK_LINES = 4diff --git a/packages/core/src/repowise/core/analysis/health/complexity/languages.py b/packages/core/src/repowise/core/analysis/health/complexity/languages.pyindex eba6d8134..afe41cd60 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/languages.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/languages.py@@ -889,6 +889,8 @@ _DART = LanguageNodeMap(# and parameter count come from the preceding signature sibling (see the# ``function_body`` handling in ``ast_utils`` / ``perf_walk``).function_kinds=frozenset({"function_body"}),+ # Matched on the signature sibling, not the body (``signature.is_constructor``).+ ctor_kinds=frozenset({"constructor_signature", "factory_constructor_signature"}),lambda_kinds=frozenset({"function_expression"}),# ``if_element`` is the collection-literal ``if`` (``[if (x) y]``);# ``conditional_expression`` is the ternary.@@ -896,8 +898,8 @@ _DART = LanguageNodeMap(loop_kinds=frozenset({"for_statement", "while_statement", "do_statement", "for_element"}),try_kinds=frozenset({"try_statement"}),# A bare ``on FormatException {}`` arm without ``catch`` has no- # catch_clause node (the block hangs off try_statement directly), so it- # is undercounted — the safe direction.+ # catch_clause node; the CCN walk counts it on its own+ # (``cyclomatic._bare_on_handlers``).catch_kinds=frozenset({"catch_clause"}),switch_kinds=frozenset({"switch_statement", "switch_expression"}),case_kinds=frozenset(@@ -1324,8 +1326,7 @@ _PASCAL = LanguageNodeMap(# A bound handler (``on E: Exception do``) is an ``exceptionHandler``# node; a bare ``except ... end`` with no ``on`` clauses has no such# node at all (the statements sit directly under ``except``), so a- # parameterless catch-all is undercounted -- the safe direction, same- # posture Dart takes for its bare ``on FormatException {}``.+ # parameterless catch-all is undercounted -- the safe direction.catch_kinds=frozenset({"exceptionHandler"}),switch_kinds=frozenset({"case"}),# The ``else`` branch of a ``case`` has no dedicated node (itsdiff --git a/packages/core/src/repowise/core/analysis/health/complexity/signature.py b/packages/core/src/repowise/core/analysis/health/complexity/signature.pyindex b0fbec339..aa67c4779 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/signature.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/signature.py@@ -29,7 +29,7 @@ from __future__ import annotationsimport refrom typing import TYPE_CHECKING-from .ast_utils import _parameter_nodes+from .ast_utils import _dart_signature_sibling, _parameter_nodesif TYPE_CHECKING:from collections.abc import Iterator@@ -121,6 +121,10 @@ def _enclosing_type_name(fn_node: Node) -> str | None:def is_constructor(fn_node: Node, name: str, lmap: LanguageNodeMap) -> bool:if fn_node.type in lmap.ctor_kinds or name in lmap.ctor_names:return True+ # Dart: the kind is on the signature beside the body (``A.named`` is one).+ sig = _dart_signature_sibling(fn_node) if fn_node.type == "function_body" else None+ if sig is not None and sig.type in lmap.ctor_kinds:+ return Trueparts = name.split("::")if len(parts) >= 2 and parts[-1] == parts[-2]:return Truediff --git a/tests/unit/health/test_complexity_walker.py b/tests/unit/health/test_complexity_walker.pyindex deb3567a3..2c6fce1bf 100644--- a/tests/unit/health/test_complexity_walker.py+++ b/tests/unit/health/test_complexity_walker.py@@ -891,6 +891,55 @@ def test_dart_assertion_blocks():assert few is not None and few.assertion_blocks == []+_DART_MEMBERS = """\+class A {+ int _x = 0;+ A() {}+ A.named(int v) {}+ factory A.make() { return A(); }+ int get x => _x;+ set x(int v) { _x = v; }+ int f() => 1;+ bool operator ==(Object o) => true;+ int operator [](int i) => i;+ A operator -() => this;+ A operator -(A o) => this;+}+"""+++def test_dart_members_get_distinct_names():+ _require_language("dart")+ results = walk_file_complexity("a.dart", "dart", _DART_MEMBERS.encode())+ names = sorted(r.name for r in results)+ assert names == sorted(+ [+ "A", "A.named", "A.make", "get x", "set x", "f",+ "operator ==", "operator []", "operator unary-", "operator -",+ ]+ )+++def test_dart_named_and_factory_constructors_are_constructors():+ results = _walk_source(_DART_MEMBERS, "dart", "a.dart")+ assert all(results[n].is_constructor for n in ("A", "A.named", "A.make"))+ assert not any(results[n].is_constructor for n in ("get x", "set x", "f"))+++ "handler", ["on StateError { h(); }", "on StateError catch (e) { h(); }", "catch (e) { h(); }"]+)+def test_dart_every_handler_shape_adds_one_ccn(handler: str):+ source = f"void f() {{\n try {{ g(); }} {handler}\n}}\n"+ fn = _walk_source(source, "dart", "f.dart")["f"]+ assert (fn.ccn, fn.cognitive) == (2, 1)+++def test_dart_bare_on_handlers_count_each_arm():+ source = "void f() {\n try { g(); } on A {} on p.B<int> {} on C catch (e) {} catch (e) {} finally {}\n}\n"+ assert _walk_source(source, "dart", "f.dart")["f"].ccn == 5++def test_scala_nesting_and_ccn():results = _walk("scala/nested.scala", "scala")deep = _find(results, "deeplyNested")