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): name C++ reference, operator, destructor and macro-prefixed functions (#4766)

Raghav Chamadiya4d3a81dee1b1
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 8bc0b3119..8b219f60d 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
@@ -34,8 +34,20 @@ _OBJECT_FIELD_NAMES = ("object", "value", "argument", "operand", "expression")
# Leaf node types that carry a declared name at the bottom of a C/C++
# ``declarator`` chain.
_DECLARATOR_NAME_KINDS = frozenset(
- {"identifier", "field_identifier", "type_identifier", "qualified_identifier"}
+ {
+ "identifier",
+ "field_identifier",
+ "type_identifier",
+ "qualified_identifier",
+ "destructor_name",
+ "operator_name",
+ "operator_cast",
+ }
)
+# Declarators whose inner declarator is a plain child, not a ``declarator`` field.
+_FIELDLESS_DECLARATORS = ("parenthesized_declarator", "reference_declarator")
+# C++ ``= default`` / ``= delete`` bodies: a declaration, not a function unit.
+_NO_BODY_CLAUSES = frozenset({"default_method_clause", "delete_method_clause"})
# Longest callee path a callback's name carries. A longer chain keeps its
# trailing segments, which name the call the callback is handed to.
@@ -167,8 +179,8 @@ def _find_name(node: Node) -> str:
hops = 0
while decl is not None and hops < 6:
if decl.type in _DECLARATOR_NAME_KINDS and decl.text is not None:
- return decl.text.decode("utf-8", errors="replace")
- decl = decl.child_by_field_name("declarator") or decl.child_by_field_name("name")
+ return _declarator_name(decl)
+ decl = _inner_declarator(decl) or decl.child_by_field_name("name")
hops += 1
for child in node.children:
if (
@@ -179,6 +191,66 @@ def _find_name(node: Node) -> str:
return "<anonymous>"
+def _inner_declarator(decl: Node) -> Node | None:
+ """The next declarator down a C/C++ declarator spine, or ``None``."""
+ inner = decl.child_by_field_name("declarator")
+ if inner is None and decl.type in _FIELDLESS_DECLARATORS:
+ inner = next((c for c in decl.named_children if not is_comment(c)), None)
+ return inner
+
+
+def _declarator_name(decl: Node) -> str:
+ """The name a C/C++ declarator leaf spells, without return type or signature."""
+ if decl.type == "qualified_identifier":
+ leaf = decl
+ while leaf.type == "qualified_identifier":
+ name = leaf.child_by_field_name("name")
+ if name is None:
+ return _node_text(decl)
+ leaf = name
+ # ``EXPORT T* f()`` nests the function declarator under the name.
+ while leaf.type not in _DECLARATOR_NAME_KINDS and (inner := _inner_declarator(leaf)):
+ leaf = inner
+ head = (decl.text or b"")[: leaf.start_byte - decl.start_byte]
+ prefix = head.decode("utf-8", errors="replace")
+ return prefix[_scope_start(prefix) :] + _declarator_name(leaf)
+ if decl.type == "operator_cast":
+ # ``operator bool() const`` is named ``operator bool``.
+ return " ".join(_node_text(decl).split("(", 1)[0].split())
+ return _node_text(decl)
+
+
+def _scope_start(prefix: str) -> int:
+ """Where the ``A::B<T>::`` run that ends *prefix* starts.
+
+ A macro before the return type (``EXPORT bool A::f``,
+ ``EXPORT std::string f``) makes the grammar read the return type as part
+ of the qualified name; only the ``::``-joined run before the name is scope.
+ """
+ start = len(prefix)
+ while prefix.endswith("::", 0, start):
+ end = start - 2
+ if end > 0 and prefix[end - 1] == ">":
+ end = _template_open(prefix, end - 1)
+ seg = end
+ while seg > 0 and (prefix[seg - 1].isalnum() or prefix[seg - 1] == "_"):
+ seg -= 1
+ start = seg
+ if seg == end:
+ break
+ return start
+
+
+def _template_open(text: str, close: int) -> int:
+ """Index of the ``<`` matching the ``>`` at *close*, or *close* + 1 if none."""
+ depth = 0
+ for i in range(close, -1, -1):
+ depth += {">": 1, "<": -1}.get(text[i], 0)
+ if depth == 0:
+ return i
+ return close + 1
+
+
_SWIFT_PROPERTY_UNITS = frozenset({"computed_property", "willset_didset_block", "accessor_list"})
@@ -317,6 +389,13 @@ def is_function_node(node: Node, lmap: LanguageNodeMap) -> bool:
return node.type in lmap.function_kinds and not is_misread_scope(node, lmap)
+def _is_function_unit(node: Node, lmap: LanguageNodeMap) -> bool:
+ """A function with code of its own: not a C++ ``= default`` / ``= delete`` member."""
+ return is_function_node(node, lmap) and not any(
+ c.type in _NO_BODY_CLAUSES for c in node.children
+ )
+
+
def _collect_function_nodes(root: Node, lmap: LanguageNodeMap) -> list[Node]:
"""All function / method definition nodes in the file.
@@ -334,7 +413,7 @@ def _collect_function_nodes(root: Node, lmap: LanguageNodeMap) -> list[Node]:
if node.type in lmap.lambda_kinds and _is_test_suite_callback(node, lmap):
stack.extend(node.children)
continue
- if is_function_node(node, lmap) or node.type in lmap.lambda_kinds:
+ if _is_function_unit(node, lmap) or node.type in lmap.lambda_kinds:
out.append(node)
continue
for child in node.children:
@@ -363,7 +442,7 @@ def _nested_function_nodes(
node
for node in candidates
if node.id not in seen
- and is_function_node(node, lmap)
+ and _is_function_unit(node, lmap)
and not (local_value is not None and local_value(node))
]
@@ -418,10 +497,7 @@ def _declarator_parameter_list(fn_node: Node) -> Node | 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
+ node = _inner_declarator(node)
return params
diff --git a/tests/unit/health/test_complexity_walker.py b/tests/unit/health/test_complexity_walker.py
index 43654d975..96c8fd510 100644
--- a/tests/unit/health/test_complexity_walker.py
+++ b/tests/unit/health/test_complexity_walker.py
@@ -678,6 +678,82 @@ EXPORT_API const struct S *fn5(int a) { if (a) { return 0; } return 0; }
assert expected <= {r.name for r in results}
+def _names_by_line(tmp_path, language: str, source: bytes) -> dict[int, str]:
+ p = tmp_path / ("unit.cpp" if language == "cpp" else "unit.c")
+ p.write_bytes(source)
+ results = walk_file_complexity(str(p), language, source)
+ if not results:
+ pytest.skip(f"tree-sitter language pack missing for {language}")
+ return {r.start_line: r.name for r in results}
+
+
+ ("source", "name"),
+ [
+ (b"const T& A::f() const { return x; }", "A::f"),
+ (b"T& f() { return x; }", "f"),
+ (b"A& operator=(const A& o) { return *this; }", "operator="),
+ (b"bool operator==(const A& o) const { return true; }", "operator=="),
+ (b"struct A { int operator()(int x) { return x; } };", "operator()"),
+ (b"struct A { operator bool() const { return true; } };", "operator bool"),
+ (b"A::operator const char*() const { return 0; }", "A::operator const char*"),
+ (b"struct A { ~A() {} };", "~A"),
+ (b"A::~A() {}", "A::~A"),
+ (b"template <typename T> int Foo<T>::g() { return 1; }", "Foo<T>::g"),
+ ],
+)
+def test_cpp_declarator_names(tmp_path, source, name):
+ assert list(_names_by_line(tmp_path, "cpp", source).values()) == [name]
+
+
+ ("source", "name"),
+ [
+ (b"CLI11_INLINE bool\nApp::_parse_arg(int a) { return true; }", "App::_parse_arg"),
+ (b"CLI11_INLINE std::string App::q() { return s; }", "App::q"),
+ (b"API_ std::string Convert(const char* s) { return s; }", "Convert"),
+ (b"API_ Cardinality AtMost(int n) { return n; }", "AtMost"),
+ (b"API_ W W::Get() { return W(); }", "W::Get"),
+ (b"API_ Reporter* GetReporter() { return 0; }", "GetReporter"),
+ ],
+)
+def test_cpp_macro_prefixed_definition_is_named_by_its_qualified_identifier(
+ tmp_path, source, name
+):
+ assert list(_names_by_line(tmp_path, "cpp", source).values()) == [name]
+
+
+ ("prefix", "scope"),
+ [
+ ("bool ", ""),
+ ("A<B<int>>::", "A<B<int>>::"),
+ ("EXPORT std::vector<int> A<B<int>>::", "A<B<int>>::"),
+ # An unmatched ``>`` ends the scope run there.
+ ("x>::", "::"),
+ ],
+)
+def test_scope_start_keeps_only_the_trailing_scope_run(prefix, scope):
+ from repowise.core.analysis.health.complexity.ast_utils import _scope_start
+
+ assert prefix[_scope_start(prefix) :] == scope
+
+
+def test_c_function_returning_a_function_pointer_is_named(tmp_path):
+ source = b"int (*fp(int a))(int) { return 0; }\n"
+ assert list(_names_by_line(tmp_path, "c", source).values()) == ["fp"]
+
+
+def test_cpp_defaulted_and_deleted_members_are_not_function_units(tmp_path):
+ source = b"""struct A {
+ A() = default;
+ A(const A&) = delete;
+ int get() { return 1; }
+};
+"""
+ assert _names_by_line(tmp_path, "cpp", source) == {4: "get"}
+
+
def test_cpp_class_body_skips_a_nested_type_read_as_a_function(tmp_path):
source = b"""class Outer {
public: