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): count declared parameters across languages (#3848)
박재홍df96945a9371
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 887db360b..24d31a8fb 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@@ -14,6 +14,7 @@ both ask the same question of a listed receiver.from __future__ import annotationsimport re+from collections.abc import Iteratorfrom typing import TYPE_CHECKINGfrom .languages import LanguageNodeMap@@ -44,6 +45,10 @@ _MAX_CALLEE_PATH = 100_PLAIN_PATH = re.compile(r"[\w$#]+(?:\.[\w$#]+)*")+def is_comment(node: Node) -> bool:+ return "comment" in node.type++def member_object(node: Node) -> Node | None:"""The receiver child of a member-access (or index) node."""for field_name in _OBJECT_FIELD_NAMES:@@ -367,7 +372,9 @@ def _parameter_list(fn_node: Node) -> Node | None:(cfor c in fn_node.children- if c.type in ("parameters", "parameter_list", "formal_parameters")+ if c.type in (+ "parameters", "parameter_list", "formal_parameters", "function_value_parameters",+ )),None,)@@ -375,7 +382,9 @@ def _parameter_list(fn_node: Node) -> Node | None:def _dialect_parameter_list(fn_node: Node) -> Node | None:- """Dart and Pascal keep the parameter list off the function node."""+ """C, C++, Dart and Pascal keep the parameter list off the function node."""+ if fn_node.type == "function_definition":+ return _declarator_parameter_list(fn_node)if fn_node.type == "function_body":# Dart: the parameter list lives on the preceding signature sibling.sig = _dart_signature_sibling(fn_node)@@ -394,6 +403,50 @@ def _dialect_parameter_list(fn_node: Node) -> Node | None:return None+def _declarator_parameter_list(fn_node: Node) -> Node | None:+ """Follow only the C/C++ declarator spine, never a callback parameter.++ The innermost function declarator owns the function's parameters; an+ outer one can instead describe the function pointer it returns.+ """+ node = fn_node.child_by_field_name("declarator")+ params = None+ while node is not None:+ if node.type == "function_declarator":+ params = node.child_by_field_name("parameters")+ inner = node.child_by_field_name("declarator")+ if inner is None and node.type in ("parenthesized_declarator", "reference_declarator"):+ inner = next((c for c in node.named_children if not is_comment(c)), None)+ node = inner+ return params+++def _parameter_nodes(params: Node) -> Iterator[Node]:+ """Declared parameters, excluding comments and grammar-only siblings."""+ if params.type == "function_value_parameters":+ # Kotlin defaults and modifiers (e.g. ``vararg``) are siblings of+ # the parameters, not children of them.+ yield from (c for c in params.named_children if c.type == "parameter")+ return+ for child in params.children:+ if is_comment(child) or _is_void_parameter(child):+ continue+ # C++ represents a bare variadic parameter as an unnamed token.+ if child.is_named or child.type == "...":+ yield child+++def _is_void_parameter(node: Node) -> bool:+ """C/C++ ``(void)`` denotes an empty list; a ``void *`` still has arity."""+ return (+ node.type == "parameter_declaration"+ and node.child_by_field_name("declarator") is None+ and (type_node := node.child_by_field_name("type")) is not None+ and type_node.type == "primitive_type"+ and type_node.text == b"void"+ )++# A method's explicit receiver: Python's conventional first ``self`` / ``cls``# and Rust's ``self`` / ``&self`` / ``&mut self``. No caller passes it, so it is# no part of the parameter list anyone reads at a call site.@@ -402,7 +455,7 @@ _RECEIVER_NAMES = frozenset({"self", "cls"})def _receiver_parameter(params: Node) -> Node | None:"""The receiver among *params*' children, when the first parameter is one."""- first = next((c for c in params.named_children if c.type != "comment"), None)+ first = next(_parameter_nodes(params), None)if first is None:return Noneif first.type == "self_parameter":@@ -415,8 +468,8 @@ def _receiver_parameter(params: Node) -> Node | None:def _count_parameters(fn_node: Node) -> int:"""Best-effort parameter-list size for *fn_node*.- Looks at tree-sitter ``parameters`` / ``parameter_list`` / ``parameters_list`` fields and counts non-punctuation- children. Returns 0 when no parameter list is found.+ Counts declared parameters, excluding receivers, comments and separators.+ Returns 0 when no parameter list is found (apart from Swift's flat list)."""params = _parameter_list(fn_node)if params is None:@@ -428,27 +481,13 @@ def _count_parameters(fn_node: Node) -> int:return sum(1 for child in holder.children if child.type == "parameter")count = 0receiver = _receiver_parameter(params)- for child in params.children:+ for child in _parameter_nodes(params):if child == receiver:continue# A bare ``*`` (keyword-only marker) and a bare ``/`` (positional-only# marker) parse as named ``keyword_separator`` / ``positional_separator``- # nodes but carry no arity, so they must be skipped alongside the- # ``*``/``**`` splat tokens and the punctuation. A ``comment`` node is- # also named but carries no arity — an explanatory comment block inside- # the parameter list (idiomatic for a validation pattern) must not- # count as a parameter (#1775).- if child.type in (- "(",- ")",- ",",- ":",- "*",- "**",- "keyword_separator",- "positional_separator",- "comment",- ):+ # nodes but carry no arity.+ if child.type in ("keyword_separator", "positional_separator"):continueif child.type == "declArg":# Pascal groups same-typed parameters under one ``declArg``@@ -458,8 +497,7 @@ def _count_parameters(fn_node: Node) -> int:# is a different node type and never matches).count += sum(1 for gc in child.children if gc.type == "identifier")continue- if child.is_named:- count += 1+ count += 1return countdiff --git a/packages/core/src/repowise/core/analysis/health/complexity/signature.py b/packages/core/src/repowise/core/analysis/health/complexity/signature.pyindex 672e71cd2..d8a04c5d1 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/signature.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/signature.py@@ -26,6 +26,8 @@ from __future__ import annotationsimport refrom typing import TYPE_CHECKING+from .ast_utils import _parameter_nodes+if TYPE_CHECKING:from tree_sitter import Node@@ -62,7 +64,7 @@ _TYPE_PUNCT_RE = re.compile(r"[*&?|\[\]]|'\w+")# Nodes of a parameter list that are not parameters, as ``_count_parameters``# skips them._NON_PARAMS = frozenset(- {"comment", "keyword_separator", "positional_separator", "self_parameter"}+ {"keyword_separator", "positional_separator", "self_parameter"})@@ -199,7 +201,7 @@ def typed_param_counts(params: Node | None, lmap: LanguageNodeMap) -> tuple[int,typed = scalar = 0if not lmap.scalar_type_names or params is None:return typed, scalar- for param in params.named_children:+ for param in _parameter_nodes(params):if param.type in _NON_PARAMS or (type_node := _param_type(param)) is None:continueif _is_bound(param, lmap):diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/span.py b/packages/core/src/repowise/core/analysis/health/dataflow/span.pyindex 16bac3aac..2239aa386 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/span.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/span.py@@ -9,6 +9,7 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING+from ..complexity.ast_utils import is_commentfrom .slice import all_blocksif TYPE_CHECKING:@@ -75,7 +76,3 @@ def exiting_guard(st: Node, lmap: LanguageNodeMap, exits: frozenset[str]) -> Nodstmts = [c for c in body.named_children if not is_comment(c)]last = body if body.type in exits or not stmts else stmts[-1]return st.child_by_field_name("condition") if last.type in exits else None---def is_comment(node: Node) -> bool:- return "comment" in node.typediff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.pyindex c678441ea..a4df13a2c 100644--- a/packages/core/src/repowise/core/analysis/health/engine.py+++ b/packages/core/src/repowise/core/analysis/health/engine.py@@ -115,7 +115,11 @@ log = structlog.get_logger(__name__)# Not a licence to move a calibrated scoring weight — those are frozen# independently of this stamp.#-# Current stamp (v40): an Extract Method plan names its helper with a placeholder+# Current stamp (v41): parameter counts exclude every comment kind and discover+# C/C++ declarators and Kotlin lists. Cached walks must refresh the total,+# typed and scalar counts, enabling primitive_obsession in those languages.+#+# v40: an Extract Method plan names its helper with a placeholder# (``extracted_helper``, numbered when taken in scope) and asks the agent applying# it to rename it, so every stored plan's ``suggested_name``, header and call text# change. Plan ids do not depend on the name and hold.diff --git a/tests/unit/health/test_signature_facts.py b/tests/unit/health/test_signature_facts.pyindex 3529d1191..3ff5c733a 100644--- a/tests/unit/health/test_signature_facts.py+++ b/tests/unit/health/test_signature_facts.py@@ -6,6 +6,9 @@ from __future__ import annotationsimport pytestfrom repowise.core.analysis.health.complexity import walk_file+from repowise.core.analysis.health.complexity.ast_utils import _count_parameters, _parameter_list+from repowise.core.analysis.health.complexity.languages import get_language_map+from repowise.core.analysis.health.complexity.signature import typed_param_countsFIVE = "a: int, b: int, c: int, d: int, e: int"@@ -181,3 +184,106 @@ def test_optional_scalars_count_as_scalars():def test_dart_num_is_a_scalar():fns = _fns("a.dart", "dart", "void f(num a, int b, String c, Foo d) {}\n")assert (fns["f"].typed_param_count, fns["f"].primitive_param_count) == (4, 3)+++ ("language", "path", "source", "expected"),+ [+ (+ "java", "A.java",+ "class A {\n A(String a, // String b,\n"+ " String c, /* String d, */ String e) {}\n}\n",+ 3,+ ),+ (+ "rust", "a.rs",+ "fn f(a: i32, // b: i32,\n c: i32, /* d: i32, */ e: i32) {}\n",+ 3,+ ),+ (+ "csharp", "A.cs",+ "class A {\n void F(int a, // int b,\n"+ " int c, /* int d, */ int e) {}\n}\n",+ 3,+ ),+ (+ "c", "a.c",+ "int f(int a, int b, int c, int d, int e, int g, int h)\n{\n return a;\n}\n",+ 7,+ ),+ (+ "cpp", "a.cpp",+ "int f(int a, int b, int c, int d, int e, int g, int h)\n{\n return a;\n}\n",+ 7,+ ),+ (+ "kotlin", "A.kt",+ "fun f(a: Int, b: Int, c: Int, d: Int, e: Int, g: Int, h: Int): Int {\n"+ " return a\n}\n",+ 7,+ ),+ ],+ ids=["java-comments", "rust-comments", "csharp-comments", "c", "cpp", "kotlin"],+)+def test_reported_parameter_counts(language: str, path: str, source: str, expected: int):+ (fn,) = walk_file(path, language, source.encode()).functions+ assert (fn.param_count, fn.typed_param_count, fn.primitive_param_count) == (expected,) * 3+++ ("language", "source", "expected"),+ [+ ("c", "int f(void) { return 0; }", (0, 0, 0)),+ ("c", "int f(void /* no parameters */) { return 0; }", (0, 0, 0)),+ ("c", "int f(void *p) { return 0; }", (1, 1, 0)),+ ("cpp", "int A::f(int a, int b) { return a; }", (2, 2, 2)),+ ("c", "char *f(int a, int b) { return 0; }", (2, 2, 2)),+ ("cpp", "int &f(int a, int b) { return a; }", (2, 2, 2)),+ ("cpp", "int f(int a, ...) { return a; }", (2, 1, 1)),+ ("cpp", "int f(...) { return 0; }", (1, 0, 0)),+ (+ "c", "int f(void (*cb)(int a, int b, int c), int x) { return x; }",+ (2, 2, 1),+ ),+ ("c", "int (*f(int a, int b))(int c) { return 0; }", (2, 2, 2)),+ ],+ ids=[+ "void", "commented-void", "void-pointer", "out-of-line", "pointer-return",+ "reference-return", "variadic", "only-variadic", "callback", "callback-return",+ ],+)+def test_c_declarator_parameter_counts(language: str, source: str, expected: tuple[int, int, int]):+ (fn,) = walk_file(f"a.{language}", language, source.encode()).functions+ assert (fn.param_count, fn.typed_param_count, fn.primitive_param_count) == expected+++def test_rust_comment_before_receiver():+ fns = _fns("a.rs", "rust", "impl A { fn f(/* receiver */ &self, a: i32) {} }")+ fn = fns["f"]+ assert (fn.param_count, fn.typed_param_count, fn.primitive_param_count) == (1, 1, 1)+++def test_kotlin_defaults_and_modifiers_are_not_parameters():+ fns = _fns(+ "A.kt", "kotlin",+ 'fun f(a: Int = 3, b: String = "x", vararg c: Int) {}\n',+ )+ fn = fns["f"]+ assert (fn.param_count, fn.typed_param_count, fn.primitive_param_count) == (3, 3, 3)+++def test_kotlin_constructor_parameter_list():+ from tree_sitter import Parser++ from repowise.core.ingestion.parser import _get_language++ # Constructors are not standalone walker units in Kotlin yet. Exercise+ # the shared signature helpers on the secondary constructor's actual AST.+ source = b'class A {\n constructor(a: Int, b: String = "x") {}\n}\n'+ tree = Parser(_get_language("kotlin")).parse(source)+ assert not tree.root_node.has_error+ cls = tree.root_node.named_children[0]+ body = next(c for c in cls.named_children if c.type == "class_body")+ ctor = next(c for c in body.named_children if c.type == "secondary_constructor")+ assert _count_parameters(ctor) == 2+ assert typed_param_counts(_parameter_list(ctor), get_language_map("kotlin")) == (2, 2)diff --git a/tests/unit/health/test_structural_biomarkers.py b/tests/unit/health/test_structural_biomarkers.pyindex a05908a12..283c29748 100644--- a/tests/unit/health/test_structural_biomarkers.py+++ b/tests/unit/health/test_structural_biomarkers.py@@ -82,6 +82,26 @@ def test_primitive_obsession_flags_wide_signature():assert out[0].details["param_count"] == 7+def test_primitive_obsession_finds_cpp_scalar_signature():+ source = (+ "int f(int a, int b, int c, int d, int e, int g, int h) {\n"+ + "\n".join(f" a += {i};" for i in range(61))+ + "\n return a;\n}\n"+ )+ walked = walk_file("a.cpp", "cpp", source.encode())+ assert walked.file_nloc > 60+ ctx = FileContext(+ file_path="a.cpp", language="cpp", nloc=walked.file_nloc,+ has_test_file=False, module=None, all_functions=tuple(walked.functions),+ )+ (finding,) = PrimitiveObsessionDetector().detect(ctx)+ assert finding.function_name == "f"+ assert finding.details == {+ "param_count": 7, "typed_param_count": 7, "primitive_param_count": 7,+ "bound_param_count": 0,+ }++def test_primitive_obsession_grace_for_constructors():# 6 params on a regular fn fires; on a constructor it doesn't (grace = 2).regular = FunctionComplexity(