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): keep primitive_obsession to signatures their author can change (#2905)

Raghav Chamadiyaeda8562c5167
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/primitive_obsession.py b/packages/core/src/repowise/core/analysis/health/biomarkers/primitive_obsession.py
index 9932b8308..0bd8bc1d6 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/primitive_obsession.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/primitive_obsession.py
@@ -2,12 +2,24 @@
A proxy for the OOP smell: when a function signature carries 5+ raw
parameters, the call sites usually pass strings/ints/bools that *should*
-be a value object. We don't try to inspect parameter *types* (too much
-language-specific machinery) — the raw count is a strong-enough
-correlation in practice.
+be a value object. Where the signature declares types, the walker counts
+how many are scalars or strings (``complexity/signature.py``).
-Constructors (`__init__`, `init`) get a small grace allowance — wide
-dataclass-style ctors are an idiomatic pattern, not a smell.
+Constructors get a small grace allowance — wide dataclass-style ctors are an
+idiomatic pattern, not a smell. A constructor is known by its node kind or by
+carrying its type's name, so a Java or C# constructor gets it too.
+
+Two narrowings keep the finding to signatures someone can actually fix:
+
+- A signature set by another declaration is skipped: an override, an
+ interface or trait implementation, a native binding. Its parameters belong
+ to the base method, the interface or the foreign ABI, and an SPI hook with
+ nine parameters is not this method's smell.
+- When parameters declare types, a majority of the typed ones must be
+ scalars or strings. A wide list of rich domain types is already the value
+ objects this smell asks for. Untyped parameters are left out of that
+ majority, and a wholly untyped signature (unannotated Python or JavaScript)
+ is judged on the count alone, as before.
A wide signature only counts as obsession in a file with enough substance to
*have* a design (`_MIN_FILE_NLOC`). In a tiny module a long parameter list is
@@ -21,12 +33,12 @@ scoring weight; larger modules and the per-function param logic are unchanged.
from __future__ import annotations
+from ..complexity import FunctionComplexity
from ..models import Severity
from .base import BiomarkerResult, FileContext
_PARAM_THRESHOLD = 5
_CTOR_GRACE = 2 # constructors get +2 free params before the smell trips
-_CTOR_NAMES = frozenset({"__init__", "init", "constructor"})
# A wide signature in a module below this many non-blank lines is idiomatic
# (config/builder/DTO), not a design smell — empirically anti-predictive of
# defects on small files. Tuned on the defect benchmark's small-file size band.
@@ -42,36 +54,51 @@ class PrimitiveObsessionDetector:
return []
out: list[BiomarkerResult] = []
for fn in ctx.all_functions:
- # A test case's parameters are fixtures the runner injects, not a
- # signature anyone calls.
- if fn.is_test_case:
+ threshold = _threshold(fn)
+ if threshold is None:
continue
- threshold = _PARAM_THRESHOLD
- if fn.name in _CTOR_NAMES:
- threshold += _CTOR_GRACE
- if fn.param_count < threshold:
- continue
- severity = (
- Severity.HIGH
- if fn.param_count >= threshold + 4
- else Severity.MEDIUM
- if fn.param_count >= threshold + 2
- else Severity.LOW
- )
+ primitive = fn.primitive_param_count
+ typed = fn.typed_param_count
out.append(
BiomarkerResult(
biomarker_type=self.name,
- severity=severity,
+ severity=_severity(fn.param_count, threshold),
function_name=fn.name,
line_start=fn.start_line,
line_end=fn.end_line,
details={
"param_count": fn.param_count,
+ "typed_param_count": typed,
+ "primitive_param_count": primitive,
},
- reason=f"long parameter list: {fn.name} takes {fn.param_count} parameters",
+ reason=(
+ f"long parameter list: {fn.name} takes {fn.param_count} parameters"
+ + (f", {primitive} of {typed} typed ones scalars or strings" if typed else "")
+ ),
)
)
return out
+def _threshold(fn: FunctionComplexity) -> int | None:
+ """The parameter count *fn* is held to, or ``None`` when it does not qualify."""
+ # A test case's parameters are fixtures the runner injects, not a
+ # signature anyone calls.
+ if fn.is_test_case or fn.signature_fixed:
+ return None
+ threshold = _PARAM_THRESHOLD + (_CTOR_GRACE if fn.is_constructor else 0)
+ if fn.param_count < threshold:
+ return None
+ typed = fn.typed_param_count
+ if typed and fn.primitive_param_count * 2 <= typed:
+ return None
+ return threshold
+
+
+def _severity(param_count: int, threshold: int) -> Severity:
+ if param_count >= threshold + 4:
+ return Severity.HIGH
+ return Severity.MEDIUM if param_count >= threshold + 2 else Severity.LOW
+
+
BIOMARKER = PrimitiveObsessionDetector()
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.py
index 5559bf83c..23da38570 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
@@ -236,37 +236,73 @@ def _collect_function_nodes(root: Node, lmap: LanguageNodeMap) -> list[Node]:
return out
-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.
- """
+def _parameter_list(fn_node: Node) -> Node | None:
+ """The node holding *fn_node*'s declared parameters, or ``None``."""
params = fn_node.child_by_field_name("parameters")
if params is None:
- for child in fn_node.children:
- if child.type in ("parameters", "parameter_list", "formal_parameters"):
- params = child
- break
- if params is None and fn_node.type == "function_body":
+ params = next(
+ (
+ c
+ for c in fn_node.children
+ if c.type in ("parameters", "parameter_list", "formal_parameters")
+ ),
+ None,
+ )
+ return params if params is not None else _dialect_parameter_list(fn_node)
+
+
+def _dialect_parameter_list(fn_node: Node) -> Node | None:
+ """Dart and Pascal keep the parameter list off the function node."""
+ if fn_node.type == "function_body":
# Dart: the parameter list lives on the preceding signature sibling.
sig = _dart_signature_sibling(fn_node)
if sig is not None:
- params = next((c for c in sig.children if c.type == "formal_parameter_list"), None)
- if params is None and fn_node.type == "lambda":
+ return next((c for c in sig.children if c.type == "formal_parameter_list"), None)
+ if fn_node.type == "lambda":
# Pascal anonymous procedure/function: the arg list is its own
# ``args`` field directly (parameterless procedures omit it).
- params = fn_node.child_by_field_name("args")
- if params is None and fn_node.type == "defProc":
+ return fn_node.child_by_field_name("args")
+ if fn_node.type == "defProc":
# Pascal named procedure/function: the arg list lives on the
# ``header`` field's own ``args`` field, not on ``defProc`` itself.
header = fn_node.child_by_field_name("header")
if header is not None:
- params = header.child_by_field_name("args")
+ return header.child_by_field_name("args")
+ return None
+
+
+# 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.
+_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)
+ if first is None:
+ return None
+ if first.type == "self_parameter":
+ return first
+ if first.type == "identifier" and (first.text or b"").decode() in _RECEIVER_NAMES:
+ return first
+ return 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.
+ """
+ params = _parameter_list(fn_node)
if params is None:
return 0
count = 0
+ receiver = _receiver_parameter(params)
for child in params.children:
+ 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
@@ -278,8 +314,6 @@ def _count_parameters(fn_node: Node) -> int:
"(",
")",
",",
- "self",
- "cls",
":",
"*",
"**",
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/languages.py b/packages/core/src/repowise/core/analysis/health/complexity/languages.py
index 400fcdbb8..2f26dbe4e 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/languages.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/languages.py
@@ -248,8 +248,52 @@ class LanguageNodeMap:
decorator_kinds: frozenset[str] = frozenset()
decorated_definition_kinds: frozenset[str] = frozenset()
+ # -- Signature ownership (``primitive_obsession``, ``signature.py``) -----
+ # All empty by default: a language with no row has no constructor beyond a
+ # function named like its type, nothing fixes its signatures, and no
+ # parameter counts as a scalar, so a typed signature there never fires.
+ # * ``ctor_kinds`` / ``ctor_names`` -- a constructor by node or by name.
+ # * ``fixed_signature_markers`` -- modifier, annotation, attribute or
+ # decorator words saying the parameter list belongs to another
+ # declaration: an override, a native or generated binding, a
+ # data-driven test whose arguments the runner supplies.
+ # * ``explicit_impl_kinds`` / ``trait_impl_kinds`` -- an explicit
+ # interface implementation on the member, an enclosing trait impl.
+ # * ``public_api_modifiers`` / ``public_api_type_kinds`` -- a member
+ # carrying one of these, inside types that all carry one too, is
+ # published API. Only for a language with an assembly-internal level
+ # (C# ``internal``), where ``public`` is a deliberate export; Java's
+ # ``public`` is how one package reaches another and says nothing.
+ # * ``scalar_type_names`` -- scalar and string type names, matched per
+ # word once qualifiers, pointers, nullability and brackets are gone.
+ ctor_kinds: frozenset[str] = frozenset()
+ ctor_names: frozenset[str] = frozenset()
+ fixed_signature_markers: frozenset[str] = frozenset()
+ explicit_impl_kinds: frozenset[str] = frozenset()
+ trait_impl_kinds: frozenset[str] = frozenset()
+ public_api_modifiers: frozenset[str] = frozenset()
+ public_api_type_kinds: frozenset[str] = frozenset()
+ scalar_type_names: frozenset[str] = frozenset()
+
+
+
+# Scalar type names C and C++ share, Win32's typedefs included because C/C++ on
+# Windows spells ints and strings that way.
+_C_SCALARS = frozenset(
+ {
+ "char", "short", "int", "long", "float", "double", "signed", "unsigned", "bool",
+ "_Bool", "wchar_t", "char8_t", "char16_t", "char32_t", "size_t", "ssize_t",
+ "ptrdiff_t", "intptr_t", "uintptr_t", "int8_t", "int16_t", "int32_t", "int64_t",
+ "uint8_t", "uint16_t", "uint32_t", "uint64_t", "BOOL", "BYTE", "WORD", "DWORD", "UINT",
+ "ULONG", "LONG", "INT", "WCHAR", "LPCWSTR", "LPWSTR", "LPCSTR", "LPSTR", "PCWSTR",
+ "PWSTR",
+ }
+)
_PY = LanguageNodeMap(
+ ctor_names=frozenset({"__init__"}),
+ fixed_signature_markers=frozenset({"override"}),
+ scalar_type_names=frozenset({"str", "int", "float", "bool", "bytes"}),
function_kinds=frozenset({"function_definition", "async_function_definition"}),
lambda_kinds=frozenset({"lambda"}),
# ``if_clause`` is a comprehension filter (``[x for x in xs if a if b]``);
@@ -286,6 +330,9 @@ _PY = LanguageNodeMap(
)
_TS = LanguageNodeMap(
+ ctor_names=frozenset({"constructor"}),
+ fixed_signature_markers=frozenset({"override"}),
+ scalar_type_names=frozenset({"string", "number", "boolean", "bigint"}),
function_kinds=frozenset(
{
"function_declaration",
@@ -340,6 +387,12 @@ _TS = LanguageNodeMap(
_JS = _TS # identical control-flow nodes; tree-sitter-javascript shares shape.
_GO = LanguageNodeMap(
+ scalar_type_names=frozenset(
+ {
+ "string", "bool", "byte", "rune", "int", "int8", "int16", "int32", "int64",
+ "uint", "uint8", "uint16", "uint32", "uint64", "uintptr", "float32", "float64",
+ }
+ ),
function_kinds=frozenset({"function_declaration", "method_declaration"}),
lambda_kinds=frozenset({"func_literal"}),
branch_kinds=frozenset({"if_statement"}),
@@ -374,6 +427,9 @@ _GO = LanguageNodeMap(
)
_JAVA = LanguageNodeMap(
+ ctor_kinds=frozenset({"constructor_declaration"}),
+ fixed_signature_markers=frozenset({"Override"}),
+ scalar_type_names=frozenset({"boolean", "byte", "short", "int", "long", "float", "double", "char", "String", "Boolean", "Byte", "Short", "Integer", "Long", "Float", "Double", "Character"}),
function_kinds=frozenset({"method_declaration", "constructor_declaration"}),
lambda_kinds=frozenset({"lambda_expression"}),
branch_kinds=frozenset({"if_statement", "ternary_expression"}),
@@ -442,6 +498,13 @@ _JAVA = LanguageNodeMap(
)
_RUST = LanguageNodeMap(
+ trait_impl_kinds=frozenset({"impl_item"}),
+ scalar_type_names=frozenset(
+ {
+ "i8", "i16", "i32", "i64", "i128", "isize", "u8", "u16", "u32", "u64", "u128",
+ "usize", "f32", "f64", "bool", "char", "str", "String",
+ }
+ ),
function_kinds=frozenset({"function_item"}),
lambda_kinds=frozenset({"closure_expression"}),
branch_kinds=frozenset({"if_expression", "if_let_expression"}),
@@ -496,6 +559,11 @@ _RUST = LanguageNodeMap(
_KOTLIN = LanguageNodeMap(
+ ctor_kinds=frozenset({"secondary_constructor"}),
+ fixed_signature_markers=frozenset({"override"}),
+ scalar_type_names=frozenset(
+ {"Int", "Long", "Short", "Byte", "Boolean", "Char", "Float", "Double", "String", "UInt", "ULong"}
+ ),
function_kinds=frozenset({"function_declaration"}),
lambda_kinds=frozenset({"lambda_literal", "anonymous_function"}),
branch_kinds=frozenset({"if_expression"}),
@@ -533,6 +601,7 @@ _KOTLIN = LanguageNodeMap(
)
_DART = LanguageNodeMap(
+ scalar_type_names=frozenset({"int", "double", "num", "bool", "String"}),
# Dart splits a function into a ``function_signature`` node whose body is
# a SIBLING ``function_body`` node (members wrap the signature in
# ``method_signature``). Keying ``function_kinds`` on the body measures
@@ -575,6 +644,9 @@ _DART = LanguageNodeMap(
)
_CPP = LanguageNodeMap(
+ fixed_signature_markers=frozenset({"override", "final"}),
+ scalar_type_names=_C_SCALARS
+ | frozenset({"string", "wstring", "string_view", "wstring_view"}),
function_kinds=frozenset({"function_definition"}),
lambda_kinds=frozenset({"lambda_expression"}),
branch_kinds=frozenset({"if_statement", "conditional_expression"}),
@@ -634,6 +706,7 @@ _CPP = LanguageNodeMap(
)
_C = LanguageNodeMap(
+ scalar_type_names=_C_SCALARS,
function_kinds=frozenset({"function_definition"}),
lambda_kinds=frozenset(),
branch_kinds=frozenset({"if_statement", "conditional_expression"}),
@@ -660,6 +733,32 @@ _C = LanguageNodeMap(
)
_CSHARP = LanguageNodeMap(
+ ctor_kinds=frozenset({"constructor_declaration"}),
+ # ``override`` and ``extern`` modifiers; P/Invoke and source-generated
+ # bindings, whose parameters a native ABI or a message template fixes; and
+ # data-driven tests, whose arguments the runner supplies.
+ fixed_signature_markers=frozenset(
+ {
+ "override", "extern", "DllImport", "LibraryImport", "LoggerMessage",
+ "Theory", "InlineData", "MemberData", "ClassData", "DataRow", "DataTestMethod",
+ "DynamicData", "TestCase", "TestCaseSource",
+ }
+ ),
+ explicit_impl_kinds=frozenset({"explicit_interface_specifier"}),
+ public_api_modifiers=frozenset({"public", "protected"}),
+ public_api_type_kinds=frozenset(
+ {
+ "class_declaration", "struct_declaration", "record_declaration",
+ "record_struct_declaration", "interface_declaration",
+ }
+ ),
+ scalar_type_names=frozenset(
+ {
+ "bool", "byte", "sbyte", "char", "short", "ushort", "int", "uint", "long", "ulong",
+ "float", "double", "decimal", "string", "nint", "nuint", "String", "Boolean",
+ "Int16", "Int32", "Int64", "UInt16", "UInt32", "UInt64", "Double", "Single",
+ }
+ ),
function_kinds=frozenset(
{"method_declaration", "constructor_declaration", "local_function_statement"}
),
@@ -707,6 +806,10 @@ _CSHARP = LanguageNodeMap(
_SCALA = LanguageNodeMap(
+ fixed_signature_markers=frozenset({"override"}),
+ scalar_type_names=frozenset(
+ {"Int", "Long", "Short", "Byte", "Boolean", "Char", "Float", "Double", "String"}
+ ),
# ``function_definition`` is a ``def`` with a body (expression or block);
# abstract ``def``s parse as ``function_declaration`` (no body, nothing to
# measure). ``given_definition`` is deliberately NOT a function kind: a
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 afc7efab8..a58582d86 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/models.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/models.py
@@ -46,6 +46,16 @@ class FunctionComplexity:
# ``primitive_obsession``. Counted via the tree-sitter ``parameters``
# field; 0 when the language lacks an explicit list or extraction fails.
param_count: int = 0
+ # Of those, the ones that declare a type, and the ones among them declared
+ # as a scalar or a string; untyped parameters are in neither. With the two
+ # flags below, read only by ``primitive_obsession``. ``complexity/signature.py``.
+ typed_param_count: int = 0
+ primitive_param_count: int = 0
+ # A constructor, by node kind, conventional name, or its type's name.
+ is_constructor: bool = False
+ # The parameter list is set by another declaration (an override, an
+ # interface or trait implementation, a native binding).
+ signature_fixed: bool = False
# Per-condition boolean-operator counts collected during the walk.
# Empty when no branch/loop carries compound boolean expressions.
complex_conditions: list[ConditionComplexity] = None # type: ignore[assignment]
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/signature.py b/packages/core/src/repowise/core/analysis/health/complexity/signature.py
new file mode 100644
index 000000000..5656e835a
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/complexity/signature.py
@@ -0,0 +1,196 @@
+"""What a function's parameter list says about who owns it.
+
+Facts read by ``primitive_obsession`` and nothing else. The per-language
+knowledge (constructor kinds, the markers that fix a signature, the scalar type
+names, C#'s public-API rule) lives on ``LanguageNodeMap``; this module only
+reads the tree with it.
+
+- **constructor**: a constructor node or conventional constructor name of the
+ language, or a function named like its enclosing type, which is how C++ and
+ Java spell one (``Foo::Foo`` out of line).
+- **signature fixed elsewhere**: the parameter list is set by something other
+ than this declaration, so "group these parameters" is advice nobody can take
+ here. Read from the declaration's modifier, annotation, attribute and
+ decorator nodes only, never from its name or from string arguments, so a
+ function *named* ``override`` is not one.
+- **typed / scalar parameters**: how many parameters declare a type, and how
+ many of those are a scalar or a string. An untyped parameter is in neither
+ count.
+"""
+
+from __future__ import annotations
+
+import re
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from tree_sitter import Node
+
+ from .languages import LanguageNodeMap
+
+# A type declaration whose ``name`` a constructor repeats. Broader than any
+# one language's ``class_kinds``, which leave out records, structs and enums.
+_TYPE_DECL_RE = re.compile(r"class|struct|record|enum|interface|object")
+
+# Nodes holding a declaration's modifiers, annotations and attributes across
+# the grammars, and the subtrees inside them that are arguments, not markers.
+_MARKER_CONTAINERS = frozenset(
+ {
+ "modifiers",
+ "modifier",
+ "attribute_list",
+ "override_modifier",
+ "accessibility_modifier",
+ "virtual_specifier",
+ "decorator",
+ }
+)
+_MARKER_ARGUMENTS = re.compile(r"argument|string|literal")
+
+# Words that qualify a type without changing what it holds, nullability
+# spelled as a union or as ``Optional[...]`` included.
+_TYPE_QUALIFIERS = frozenset(
+ {
+ "const", "volatile", "final", "ref", "in", "out", "readonly", "scoped", "mut", "params",
+ "None", "null", "undefined", "Optional",
+ }
+)
+_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"}
+)
+
+
+def _text(node: Node) -> str:
+ return (node.text or b"").decode("utf-8", errors="replace")
+
+
+def _marker_words(node: Node) -> set[str]:
+ """Leaf words of *node*'s marker containers, arguments and strings left out."""
+ stack = [c for c in node.children if c.type in _MARKER_CONTAINERS]
+ # C++ keeps ``override`` on the declarator, after the parameters.
+ declarator = node.child_by_field_name("declarator")
+ if declarator is not None:
+ stack += [c for c in declarator.children if c.type in _MARKER_CONTAINERS]
+ words: set[str] = set()
+ while stack:
+ cur = stack.pop()
+ if _MARKER_ARGUMENTS.search(cur.type):
+ continue
+ if cur.child_count == 0:
+ words.add(_text(cur))
+ stack.extend(cur.children)
+ return words
+
+
+def _declaration_markers(fn_node: Node, lmap: LanguageNodeMap) -> set[str]:
+ words = _marker_words(fn_node)
+ # Python keeps decorators on a wrapper beside the definition.
+ if fn_node.parent is not None and fn_node.parent.type in lmap.decorated_definition_kinds:
+ words |= _marker_words(fn_node.parent)
+ return words
+
+
+def _enclosing_type_name(fn_node: Node) -> str | None:
+ node = fn_node.parent
+ while node is not None:
+ if _TYPE_DECL_RE.search(node.type):
+ name = node.child_by_field_name("name")
+ if name is not None:
+ return _text(name)
+ node = node.parent
+ return 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
+ parts = name.split("::")
+ if len(parts) >= 2 and parts[-1] == parts[-2]:
+ return True
+ return name == _enclosing_type_name(fn_node)
+
+
+def _in_trait_impl(fn_node: Node, lmap: LanguageNodeMap) -> bool:
+ node = fn_node.parent
+ while node is not None and node.type not in lmap.trait_impl_kinds:
+ if node.type in lmap.function_kinds:
+ return False
+ node = node.parent
+ return node is not None and node.child_by_field_name("trait") is not None
+
+
+def _is_published(node: Node, lmap: LanguageNodeMap) -> bool:
+ access = _marker_words(node)
+ return bool(access & lmap.public_api_modifiers) and "private" not in access
+
+
+def _is_public_api(fn_node: Node, lmap: LanguageNodeMap) -> bool:
+ """A published member whose every enclosing type is published too."""
+ if not lmap.public_api_modifiers or not _is_published(fn_node, lmap):
+ return False
+ node = fn_node.parent
+ seen_type = False
+ while node is not None:
+ if node.type in lmap.public_api_type_kinds:
+ if not _is_published(node, lmap):
+ return False
+ seen_type = True
+ node = node.parent
+ return seen_type
+
+
+def is_signature_fixed(fn_node: Node, lmap: LanguageNodeMap) -> bool:
+ """Whether *fn_node*'s parameters are dictated by another declaration."""
+ if _declaration_markers(fn_node, lmap) & lmap.fixed_signature_markers:
+ return True
+ if any(c.type in lmap.explicit_impl_kinds for c in fn_node.children):
+ return True
+ return _in_trait_impl(fn_node, lmap) or _is_public_api(fn_node, lmap)
+
+
+def _param_type(param: Node) -> Node | None:
+ declared = param.child_by_field_name("type")
+ if declared is not None:
+ return declared
+ # Kotlin, Dart and Pascal keep the type as a child with no field name.
+ return next((c for c in param.named_children if "type" in c.type), None)
+
+
+def _is_scalar(type_node: Node, scalars: frozenset[str]) -> bool:
+ text = _text(type_node)
+ if "<" in text or "(" in text:
+ return False
+ words = [
+ w.rsplit("::", 1)[-1].rsplit(".", 1)[-1]
+ for w in _TYPE_PUNCT_RE.sub(" ", text.lstrip(":")).split()
+ if w not in _TYPE_QUALIFIERS
+ ]
+ return bool(words) and all(w in scalars for w in words)
+
+
+def _arity(param: Node) -> int:
+ """Names one parameter node declares. Pascal declares ``A, B: Integer`` as
+ one node, and ``_count_parameters`` counts its names."""
+ if param.type != "declArg":
+ return 1
+ return sum(1 for c in param.children if c.type == "identifier")
+
+
+def typed_param_counts(params: Node | None, lmap: LanguageNodeMap) -> tuple[int, int]:
+ """``(typed, scalar)``: parameters of *params* that declare a type, and the
+ ones among them declared as a scalar or a string. ``(0, 0)`` for a language
+ with no scalar vocabulary: its types cannot be read, so none count."""
+ typed = scalar = 0
+ if not lmap.scalar_type_names or params is None:
+ return typed, scalar
+ for param in params.named_children:
+ if param.type in _NON_PARAMS or (type_node := _param_type(param)) is None:
+ continue
+ arity = _arity(param)
+ typed += arity
+ if _is_scalar(type_node, lmap.scalar_type_names):
+ scalar += arity
+ return typed, scalar
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 d886b206d..0be2a45dc 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/walker.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/walker.py
@@ -48,6 +48,7 @@ from .ast_utils import (
_collect_function_nodes,
_count_parameters,
_find_function_entry_name,
+ _parameter_list,
)
from .class_analysis import _collect_classes
from .cyclomatic import _walk_function_body
@@ -74,6 +75,7 @@ from .models import (
# which imports it directly from this module.
from .nloc import _count_file_nloc
from .perf_walk import _collect_perf_hits, perf_pass_runs
+from .signature import is_constructor, is_signature_fixed, typed_param_counts
from .test_case import is_test_case
__all__ = [
@@ -174,6 +176,7 @@ def walk_file(
bare_called,
) = _collect_assertion_facts(body, lmap, asserts)
name = _find_function_entry_name(fn_node, lmap)
+ typed, scalar = typed_param_counts(_parameter_list(fn_node), lmap)
fc = FunctionComplexity(
name=name,
start_line=fn_node.start_point[0] + 1,
@@ -184,6 +187,10 @@ def walk_file(
nloc=scan.lines.count(body, source),
bumps=bumps,
param_count=_count_parameters(fn_node),
+ typed_param_count=typed,
+ primitive_param_count=scalar,
+ is_constructor=is_constructor(fn_node, name, lmap),
+ signature_fixed=is_signature_fixed(fn_node, lmap),
complex_conditions=conditions,
assertion_blocks=assertion_blocks,
assertion_count=assertion_count,
diff --git a/tests/unit/health/test_ff_track_bch_complexity.py b/tests/unit/health/test_ff_track_bch_complexity.py
index a6acc3230..60b8c7ea6 100644
--- a/tests/unit/health/test_ff_track_bch_complexity.py
+++ b/tests/unit/health/test_ff_track_bch_complexity.py
@@ -233,3 +233,26 @@ def test_docstring_heavy_function_nloc_excludes_docs():
# And so the function stays well under the large_method threshold despite
# spanning ~64 physical lines.
assert nloc < _LARGE_METHOD_THRESHOLD
+
+
+# --- the explicit receiver is not a parameter a caller passes ---------------
+
+
+def test_python_self_and_cls_receivers_not_counted():
+ fns, _ = _parse(
+ "python",
+ "class C:\n"
+ " def m(self, a, b):\n pass\n"
+ " @classmethod\n"
+ " def k(cls, a):\n pass\n",
+ )
+ fns = sorted(fns, key=lambda f: f.start_point)
+ assert [_count_parameters(f) for f in fns] == [2, 1]
+ # Only a leading ``self`` is the receiver.
+ fns, _ = _parse("python", "def f(a, self):\n pass\n")
+ assert _count_parameters(fns[0]) == 2
+
+
+def test_rust_self_parameter_not_counted():
+ fns, _ = _parse("rust", "impl X { fn m(&mut self, a: i32, b: u8) {} }")
+ assert _count_parameters(fns[0]) == 2
diff --git a/tests/unit/health/test_signature_facts.py b/tests/unit/health/test_signature_facts.py
new file mode 100644
index 000000000..3cdcecfc5
--- /dev/null
+++ b/tests/unit/health/test_signature_facts.py
@@ -0,0 +1,150 @@
+"""Walker facts behind ``primitive_obsession``: constructors, signatures fixed
+by another declaration, and how many parameters are typed scalars or strings."""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.analysis.health.complexity import walk_file
+
+FIVE = "a: int, b: int, c: int, d: int, e: int"
+
+
+def _fns(path: str, language: str, source: str) -> dict[str, object]:
+ return {f.name: f for f in walk_file(path, language, source.encode()).functions}
+
+
+def test_java_constructor_override_and_scalar_count():
+ fns = _fns(
+ "Foo.java",
+ "java",
+ """class Foo {
+ Foo(int a, String b, long c, Bar d, Baz e, int f, int g) {}
+ @Override public void run(int a, int b, int c, int d, int e) {}
+ public void pub(int a, int b, int c, int d, int e) {}
+ @SuppressWarnings("override") void quiet(int a, int b, int c, int d, int e) {}
+ void override(int a, int b, int c, int d, int e) {}
+ void mix(int[] a, final String b, java.lang.String c, List<String> d, Map<A, B> e, int... f) {}
+ }""",
+ )
+ assert fns["Foo"].is_constructor and not fns["Foo"].signature_fixed
+ assert (fns["Foo"].typed_param_count, fns["Foo"].primitive_param_count) == (7, 5)
+ assert fns["run"].signature_fixed
+ # Java ``public`` is not read as published API.
+ assert not fns["pub"].signature_fixed
+ # A string argument or a name that says "override" marks nothing.
+ assert not fns["quiet"].signature_fixed
+ assert not fns["override"].signature_fixed
+ # A generic container is not a scalar; an array or varargs of one is.
+ assert fns["mix"].primitive_param_count == 4 and not fns["mix"].is_constructor
+
+
+ ("member", "fixed"),
+ [
+ ("public override void M(int a, int b, int c, int d, int e) {}", True),
+ ('[DllImport("x")] static extern int M(int a, int b, int c, int d, int e);', True),
+ ("void IBar.M(int a, int b, int c, int d, int e) {}", True),
+ ("[DataRow(1, 2, 3, 4, 5)] public void M(int a, int b, int c, int d, int e) {}", True),
+ ('[LoggerMessage(1, "{a}")] static partial void M(int a, int b, int c, int d, int e);', True),
+ ("public void M(int a, int b, int c, int d, int e) {}", True),
+ ("protected void M(int a, int b, int c, int d, int e) {}", True),
+ ('[Obsolete("override")] void M(int a, int b, int c, int d, int e) {}', False),
+ ("internal void M(int a, int b, int c, int d, int e) {}", False),
+ ("private void M(int a, int b, int c, int d, int e) {}", False),
+ ("private protected void M(int a, int b, int c, int d, int e) {}", False),
+ ],
+)
+def test_csharp_fixed_signatures(member: str, fixed: bool):
+ fns = _fns("A.cs", "csharp", f"public class A {{ {member} }}")
+ assert fns["M"].signature_fixed is fixed
+
+
+def test_csharp_public_member_of_internal_type_is_not_api():
+ fns = _fns(
+ "A.cs",
+ "csharp",
+ "internal class A { public void M(int a, int b, int c, int d, int e) {} }",
+ )
+ assert not fns["M"].signature_fixed
+
+
+def test_csharp_scalar_count_strips_modifiers_and_nullability():
+ fns = _fns(
+ "A.cs",
+ "csharp",
+ "class A { A(int a, string b, long c, int d, int e, int f, int g) {}"
+ " void M(int a, int b, int? c, ref int d, out string e, Task t) {} }",
+ )
+ assert fns["A"].is_constructor
+ assert (fns["M"].typed_param_count, fns["M"].primitive_param_count) == (6, 5)
+
+
+def test_python_override_decorator_and_name():
+ fns = _fns(
+ "a.py",
+ "python",
+ "class C:\n"
+ " @override\n"
+ f" def run(self, {FIVE}):\n pass\n"
+ " @typing.override\n"
+ f" def walk(self, {FIVE}):\n pass\n"
+ f" def override(self, {FIVE}):\n pass\n",
+ )
+ assert fns["run"].signature_fixed and fns["walk"].signature_fixed
+ assert not fns["override"].signature_fixed
+
+
+def test_typescript_override_modifier_and_name():
+ five = "a: number, b: number, c: number, d: number, e: number"
+ fns = _fns(
+ "a.ts",
+ "typescript",
+ f"class A extends B {{ override run({five}) {{}} public pub({five}) {{}} }}\n"
+ f"function override({five}) {{}}\n",
+ )
+ assert fns["run"].signature_fixed
+ assert not fns["pub"].signature_fixed
+ assert not fns["override"].signature_fixed
+
+
+def test_kotlin_override_modifier():
+ source = "class A : B() {\n override fun run(a: Int) {}\n fun own(a: Int) {}\n}\n"
+ fns = _fns("A.kt", "kotlin", source)
+ assert fns["run"].signature_fixed and not fns["own"].signature_fixed
+
+
+def test_rust_trait_impl_is_fixed_and_inherent_impl_is_not():
+ fns = _fns(
+ "a.rs",
+ "rust",
+ "impl Tr for X { fn run(&self, a: i32, b: &str, c: u64, d: String, e: &mut Vec<u8>) {} }\n"
+ "impl X { fn own(&self, a: i32, b: &str, c: u64, d: String, e: Vec<u8>) {} }",
+ )
+ assert fns["run"].signature_fixed
+ assert not fns["own"].signature_fixed
+ assert (fns["own"].typed_param_count, fns["own"].primitive_param_count) == (5, 4)
+
+
+def test_untyped_parameters_are_in_neither_count():
+ fns = _fns("a.py", "python", "def f(a, b, c, d, e: int):\n pass\n")
+ assert (fns["f"].typed_param_count, fns["f"].primitive_param_count) == (1, 1)
+ fns = _fns("b.py", "python", "def g(a, b, c, d, e):\n pass\n")
+ assert fns["g"].typed_param_count == 0
+ typed = _fns("c.py", "python", "class C:\n def __init__(self, a: int, b: str):\n pass\n")
+ assert typed["__init__"].is_constructor
+ assert typed["__init__"].primitive_param_count == 2
+
+
+def test_optional_scalars_count_as_scalars():
+ fns = _fns(
+ "a.py",
+ "python",
+ "def f(a: str, b: str | None, c: Optional[int], d: Path, e: int):\n pass\n",
+ )
+ assert fns["f"].primitive_param_count == 4
+
+
+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)
diff --git a/tests/unit/health/test_structural_biomarkers.py b/tests/unit/health/test_structural_biomarkers.py
index 3fe333e7a..67c805b71 100644
--- a/tests/unit/health/test_structural_biomarkers.py
+++ b/tests/unit/health/test_structural_biomarkers.py
@@ -83,12 +83,13 @@ def test_primitive_obsession_flags_wide_signature():
def test_primitive_obsession_grace_for_constructors():
- # 6 params on a regular fn fires; on __init__ it doesn't (grace = 2).
+ # 6 params on a regular fn fires; on a constructor it doesn't (grace = 2).
regular = FunctionComplexity(
"build", 1, 20, ccn=1, max_nesting=0, cognitive=0, nloc=14, param_count=6
)
ctor = FunctionComplexity(
- "__init__", 1, 20, ccn=1, max_nesting=0, cognitive=0, nloc=14, param_count=6
+ "__init__", 1, 20, ccn=1, max_nesting=0, cognitive=0, nloc=14, param_count=6,
+ is_constructor=True,
)
d = PrimitiveObsessionDetector()
assert d.detect(_ctx([regular, _FILLER]))
@@ -112,3 +113,30 @@ def test_primitive_obsession_skips_tiny_files():
assert PrimitiveObsessionDetector().detect(_ctx([fn])) == []
# The same wide signature in a substantial module still fires.
assert PrimitiveObsessionDetector().detect(_ctx([fn, _FILLER]))
+
+
+def test_primitive_obsession_skips_fixed_signatures():
+ fn = FunctionComplexity(
+ "getRestHandlers", 1, 20, ccn=1, max_nesting=0, cognitive=0, nloc=14, param_count=9,
+ signature_fixed=True,
+ )
+ assert PrimitiveObsessionDetector().detect(_ctx([fn, _FILLER])) == []
+
+
+def test_primitive_obsession_needs_mostly_primitive_params_when_typed():
+ def fn(typed: int, primitive: int) -> FunctionComplexity:
+ return FunctionComplexity(
+ "run", 1, 20, ccn=1, max_nesting=0, cognitive=0, nloc=14, param_count=6,
+ typed_param_count=typed, primitive_param_count=primitive,
+ )
+
+ d = PrimitiveObsessionDetector()
+ # Three of six is not a majority: rich types already group the values.
+ assert d.detect(_ctx([fn(6, 3), _FILLER])) == []
+ out = d.detect(_ctx([fn(6, 4), _FILLER]))
+ assert out and out[0].details["primitive_param_count"] == 4
+ assert "4 of 6 typed ones scalars or strings" in out[0].reason
+ # Untyped parameters leave the majority: one typed int of six still fires.
+ assert d.detect(_ctx([fn(1, 1), _FILLER]))
+ # An untyped signature has nothing to count and is judged on size alone.
+ assert d.detect(_ctx([fn(0, 0), _FILLER]))