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.

feat(cpp): dead-code hardening — reachability, never-flag, contracts, dynamic markers (#284)

Raghav Chamadiya769cefca5aea
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
index 1ed574323..94b82d2c1 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -28,6 +28,11 @@ from .constants import (
_is_fixture_path,
)
from .contract_methods import is_contract_method
+from .cpp_reachability import (
+ build_cpp_package_files,
+ is_cpp_file_reachable,
+ is_cpp_path,
+)
from .go_reachability import build_go_package_files, is_go_file_reachable
from .jvm_reachability import build_jvm_package_files, is_jvm_file_reachable
@@ -150,6 +155,11 @@ _ENTRY_POINT_SYMBOL_NAMES: frozenset[str] = frozenset({
"WinMain", # ANSI WinMain
"wmain", # Unicode console main
"ServiceMain", # Win32 service entry
+ # ---- libFuzzer / Honggfuzz / AFL fuzz harness entries ------------
+ # The fuzzer driver invokes these by name via dlsym; no static
+ # caller will ever exist.
+ "LLVMFuzzerTestOneInput",
+ "LLVMFuzzerInitialize",
# ---- Windows hook / ETW callbacks invoked by macros / runtime ----
"LowLevelKeyboardProc",
"LowLevelMouseProc",
@@ -308,6 +318,8 @@ class DeadCodeAnalyzer:
# Lazily-built JVM (``.java`` + ``.kt``) package-directory map; see
# :mod:`jvm_reachability`.
self._jvm_package_files: dict[str, list[str]] | None = None
+ # Lazily-built C/C++ directory map; see :mod:`cpp_reachability`.
+ self._cpp_package_files: dict[str, list[str]] | None = None
def _go_packages(self) -> dict[str, list[str]]:
"""Return the cached Go package map, building it on first use."""
@@ -321,6 +333,12 @@ class DeadCodeAnalyzer:
self._jvm_package_files = build_jvm_package_files(self.graph)
return self._jvm_package_files
+ def _cpp_packages(self) -> dict[str, list[str]]:
+ """Return the cached C/C++ directory map, building it on first use."""
+ if self._cpp_package_files is None:
+ self._cpp_package_files = build_cpp_package_files(self.graph)
+ return self._cpp_package_files
+
def analyze(
self,
config: dict | None = None,
@@ -476,6 +494,13 @@ class DeadCodeAnalyzer:
# files surface as live even with no direct importer.
if is_jvm_file_reachable(node_str, self.graph, self._jvm_packages()):
continue
+ elif is_cpp_path(node_str):
+ # C/C++ reachability rescues public-API headers, ``main``-
+ # bearing TUs (apps/demos/benchmarks/fuzzers), internal
+ # headers next to their implementation files, and
+ # conditional-compile alternates that share a stem prefix.
+ if is_cpp_file_reachable(node_str, self.graph, self._cpp_packages()):
+ continue
elif self.graph.in_degree(node) > 0:
continue
diff --git a/packages/core/src/repowise/core/analysis/dead_code/constants.py b/packages/core/src/repowise/core/analysis/dead_code/constants.py
index 5d1b90baf..e06e314cb 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/constants.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/constants.py
@@ -171,10 +171,274 @@ _NEVER_FLAG_PATTERNS: tuple[str, ...] = (
# activated by Windows, so it has no static caller.
"*/pch.h",
"*/pch.cpp",
+ "*/pch.cc",
+ "*/PrecompiledHeader.cpp",
+ "*/PrecompiledHeader.cc",
"*/stdafx.h",
"*/stdafx.cpp",
"*ClassFactory.cpp",
"*ClassFactory.h",
+ # ---- C / C++ conventions ---------------------------------------------
+ # ``fnmatch`` ``*`` spans ``/`` so a leading ``*`` matches both nested
+ # module paths and repo-root layouts.
+ # Apps / demos / examples / tools / benchmarks — every file under these
+ # trees compiles to a standalone binary by CMake/Bazel ``add_executable``
+ # / ``cc_binary``. They have no static importer by design.
+ "*/apps/*.cc",
+ "*/apps/*.cpp",
+ "*/apps/*.cxx",
+ "*/apps/*.c",
+ "*/apps/*.h",
+ "*/apps/*.hpp",
+ "*/apps/**/*.cc",
+ "*/apps/**/*.cpp",
+ "*/apps/**/*.cxx",
+ "*/apps/**/*.c",
+ "*/apps/**/*.h",
+ "*/apps/**/*.hpp",
+ "apps/*.cc",
+ "apps/*.cpp",
+ "apps/*.c",
+ "apps/**/*.cc",
+ "apps/**/*.cpp",
+ "apps/**/*.cxx",
+ "apps/**/*.c",
+ "apps/**/*.h",
+ "apps/**/*.hpp",
+ "*/demos/*.cc",
+ "*/demos/*.cpp",
+ "*/demos/*.cxx",
+ "*/demos/*.c",
+ "*/demos/**/*.cc",
+ "*/demos/**/*.cpp",
+ "*/demos/**/*.cxx",
+ "*/demos/**/*.c",
+ "demos/*.cc",
+ "demos/*.cpp",
+ "demos/*.c",
+ "demos/**/*.cc",
+ "demos/**/*.cpp",
+ "demos/**/*.cxx",
+ "demos/**/*.c",
+ "*/examples/*.cc",
+ "*/examples/*.cpp",
+ "*/examples/*.cxx",
+ "*/examples/*.c",
+ "*/examples/*.h",
+ "*/examples/**/*.cc",
+ "*/examples/**/*.cpp",
+ "*/examples/**/*.cxx",
+ "*/examples/**/*.c",
+ "*/examples/**/*.h",
+ "*/examples/**/*.hpp",
+ "examples/*.cc",
+ "examples/*.cpp",
+ "examples/**/*.cc",
+ "examples/**/*.cpp",
+ "examples/**/*.cxx",
+ "examples/**/*.c",
+ "examples/**/*.h",
+ "*/sample/*.cc",
+ "*/sample/*.cpp",
+ "*/samples/*.cc",
+ "*/samples/*.cpp",
+ "*/samples/**/*.cc",
+ "*/samples/**/*.cpp",
+ "samples/**/*.cc",
+ "samples/**/*.cpp",
+ "*/benchmarks/*.cc",
+ "*/benchmarks/*.cpp",
+ "*/benchmarks/*.cxx",
+ "*/benchmarks/*.c",
+ "*/benchmarks/**/*.cc",
+ "*/benchmarks/**/*.cpp",
+ "benchmarks/*.cc",
+ "benchmarks/*.cpp",
+ "benchmarks/*.c",
+ "benchmarks/**/*.cc",
+ "benchmarks/**/*.cpp",
+ "*/bench/*.cc",
+ "*/bench/*.cpp",
+ "bench/*.cc",
+ "bench/*.cpp",
+ # C/C++ tool directories (``leveldbutil.cc`` / ``db_repair.cc`` shape).
+ "*/tools/*.cc",
+ "*/tools/*.cpp",
+ "*/tools/**/*.cc",
+ "*/tools/**/*.cpp",
+ "tools/*.cc",
+ "tools/*.cpp",
+ "tools/**/*.cc",
+ "tools/**/*.cpp",
+ # C/C++ test trees — every framework (GoogleTest / Catch2 / Boost.Test
+ # / doctest / Google Benchmark / libFuzzer) discovers tests by glob, not
+ # by static import.
+ "*/tests/**/*_test.cc",
+ "*/tests/**/*_test.cpp",
+ "*/tests/**/*_test.cxx",
+ "*/tests/**/*_test.c",
+ "*/tests/**/*_unittest.cc",
+ "*/tests/**/*_unittest.cpp",
+ "*/tests/**/*_perftest.cc",
+ "*/tests/**/*_perftest.cpp",
+ "*/tests/**/*_perf.cc",
+ "*/tests/**/*_perf.cpp",
+ "*/tests/**/*_benchmark.cc",
+ "*/tests/**/*_benchmark.cpp",
+ "*/tests/**/*_fuzz.cc",
+ "*/tests/**/*_fuzz.cpp",
+ "*/tests/perf/*.cc",
+ "*/tests/perf/*.cpp",
+ "*/tests/unit/*.cc",
+ "*/tests/unit/*.cpp",
+ "*/tests/unit/*.h",
+ "*/tests/unit/*.hpp",
+ "*/tests/fuzz/*.cc",
+ "*/tests/fuzz/*.cpp",
+ "*/tests/integration/*.cc",
+ "*/tests/integration/*.cpp",
+ "*/tests/manual/*",
+ "tests/**/*_test.cc",
+ "tests/**/*_test.cpp",
+ "tests/**/*_unittest.cc",
+ "tests/**/*_unittest.cpp",
+ "tests/**/*_perf.cc",
+ "tests/**/*_perf.cpp",
+ "tests/**/*_fuzz.cc",
+ "tests/**/*_fuzz.cpp",
+ "tests/perf/*.cc",
+ "tests/perf/*.cpp",
+ "tests/unit/*.cc",
+ "tests/unit/*.cpp",
+ "tests/unit/*.h",
+ "tests/fuzz/*.cc",
+ "tests/fuzz/*.cpp",
+ "tests/manual/*",
+ # File-suffix conventions for tests dropped outside a standard test
+ # directory (GoogleTest / Google Benchmark / libFuzzer / Catch2).
+ "*_test.cc",
+ "*_test.cpp",
+ "*_test.cxx",
+ "*_test.h",
+ "*_unittest.cc",
+ "*_unittest.cpp",
+ "*_perftest.cc",
+ "*_perftest.cpp",
+ "*_perf.cc",
+ "*_perf.cpp",
+ "*_benchmark.cc",
+ "*_benchmark.cpp",
+ "*_fuzz.cc",
+ "*_fuzz.cpp",
+ # Conventional port / example skeleton headers — projects ship them
+ # to document a portability layer; never actually built.
+ "*/port_example.h",
+ "*/port/port_example.h",
+ "*_example.h",
+ "*_example.hpp",
+ "*_example.cc",
+ # Generated source roots (CMake build dirs, autoconf / out-of-tree
+ # builds). The walker normally skips them but, when they leak in,
+ # they're never importers.
+ "*/build/**",
+ "build/**",
+ "*/cmake-build-*/**",
+ "cmake-build-*/**",
+ "*/_deps/**",
+ "_deps/**",
+ "*/out/build/**",
+ "*/out/Debug/**",
+ "*/out/Release/**",
+ # Generated source-file patterns. Wired in at build time, no static
+ # importer; the analyzer should silence them universally.
+ "moc_*.cpp", # Qt MOC
+ "moc_*.cc",
+ "ui_*.h", # Qt UIC
+ "qrc_*.cpp", # Qt RCC
+ "qrc_*.cc",
+ "*.moc", # inline MOC includes
+ "*.pb.cc", # protoc generated
+ "*.pb.h",
+ "*.pb-c.c", # protobuf-c
+ "*.pb-c.h",
+ "*.grpc.pb.cc", # protoc-gen-grpc
+ "*.grpc.pb.h",
+ "*.capnp.c++", # Cap'n Proto
+ "*.capnp.h",
+ "*.flatbuffers.h",
+ "*_generated.h", # FlatBuffers convention
+ "*.tab.c", # Bison / Yacc
+ "*.tab.h",
+ "*.yy.c", # Flex / Lex
+ "*_lex.cc",
+ "*_wrap.cxx", # SWIG
+ "*_wrap.cpp",
+ "*.cython.cpp", # Cython
+ # Vendored / third-party roots. The existing ``vendor`` / ``third_party``
+ # / ``deps`` globs only cover ``.c`` / ``.h``; extend them to the full
+ # C++ extension set, and add the additional vendor conventions
+ # ``external/`` / ``extern/`` / ``contrib/`` / ``submodules/``.
+ "*/vendor/**/*.cc",
+ "*/vendor/**/*.cpp",
+ "*/vendor/**/*.cxx",
+ "*/vendor/**/*.hpp",
+ "*/vendor/**/*.hxx",
+ "vendor/**/*.cc",
+ "vendor/**/*.cpp",
+ "vendor/**/*.cxx",
+ "vendor/**/*.hpp",
+ "*/third_party/**/*.cc",
+ "*/third_party/**/*.cpp",
+ "*/third_party/**/*.cxx",
+ "*/third_party/**/*.hpp",
+ "*/third_party/**/*.hxx",
+ "third_party/**/*.cc",
+ "third_party/**/*.cpp",
+ "third_party/**/*.cxx",
+ "third_party/**/*.hpp",
+ "*/deps/**/*.cc",
+ "*/deps/**/*.cpp",
+ "*/deps/**/*.cxx",
+ "*/deps/**/*.hpp",
+ "deps/**/*.cc",
+ "deps/**/*.cpp",
+ "deps/**/*.cxx",
+ "deps/**/*.hpp",
+ "*/external/**/*.c",
+ "*/external/**/*.h",
+ "*/external/**/*.cc",
+ "*/external/**/*.cpp",
+ "*/external/**/*.cxx",
+ "*/external/**/*.hpp",
+ "*/external/**/*.hxx",
+ "external/**/*.c",
+ "external/**/*.h",
+ "external/**/*.cc",
+ "external/**/*.cpp",
+ "external/**/*.cxx",
+ "external/**/*.hpp",
+ "*/extern/**/*.c",
+ "*/extern/**/*.h",
+ "*/extern/**/*.cc",
+ "*/extern/**/*.cpp",
+ "*/extern/**/*.hpp",
+ "extern/**/*.c",
+ "extern/**/*.h",
+ "extern/**/*.cc",
+ "extern/**/*.cpp",
+ "*/contrib/**/*.c",
+ "*/contrib/**/*.h",
+ "*/contrib/**/*.cc",
+ "*/contrib/**/*.cpp",
+ "*/contrib/**/*.cxx",
+ "*/contrib/**/*.hpp",
+ "contrib/**/*.c",
+ "contrib/**/*.h",
+ "contrib/**/*.cc",
+ "contrib/**/*.cpp",
+ "*/submodules/**",
+ "submodules/**",
+ "*/.deps/**",
# ---- Rust / Cargo conventions ----------------------------------------
# Build scripts (executed by Cargo at compile time, never imported)
"**/build.rs",
diff --git a/packages/core/src/repowise/core/analysis/dead_code/contract_methods.py b/packages/core/src/repowise/core/analysis/dead_code/contract_methods.py
index 4d294bdcd..99c67a1bb 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/contract_methods.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/contract_methods.py
@@ -107,6 +107,81 @@ _JVM_CONTRACT_METHOD_NAMES = _JVM_CONTRACT_METHOD_NAMES | frozenset(
_JVM_LANGUAGES: frozenset[str] = frozenset({"java", "kotlin"})
+# Method / function names reserved by the C++ language, the STL
+# customization-point protocol, the coroutine machinery, and standard
+# library traits. Each is dispatched by the compiler, the standard
+# library, or a hidden friend lookup — never via a static call edge the
+# graph can observe. A user class overriding ``operator==`` or
+# providing ``begin()`` / ``end()`` for range-for support is live even
+# when the explicit call sites read as ``std::sort(v.begin(), v.end())``
+# in another TU.
+#
+# ``<ctor>`` / ``<dtor>`` are sentinel placeholders — the analyzer
+# matches constructors and destructors by symbol *kind* rather than by
+# name, because the parser emits the bare class name for constructors
+# and ``~ClassName`` for destructors.
+_CPP_CONTRACT_METHOD_NAMES: frozenset[str] = frozenset({
+ # ---- Comparison & arithmetic operator overloads -----------------
+ "operator=",
+ "operator==", "operator!=",
+ "operator<", "operator<=", "operator>", "operator>=", "operator<=>",
+ "operator+", "operator-", "operator*", "operator/", "operator%",
+ "operator&", "operator|", "operator^", "operator~",
+ "operator!", "operator&&", "operator||",
+ "operator++", "operator--",
+ "operator+=", "operator-=", "operator*=", "operator/=", "operator%=",
+ "operator&=", "operator|=", "operator^=",
+ "operator<<", "operator>>", "operator<<=", "operator>>=",
+ "operator,",
+ # ---- Indexing / call / member-access operators ------------------
+ "operator[]",
+ "operator()",
+ "operator->",
+ "operator->*",
+ "operator*", # also dereference; deduped by set
+ # ---- Allocation operators (overloaded new/delete) ---------------
+ "operator new",
+ "operator new[]",
+ "operator delete",
+ "operator delete[]",
+ # ---- Conversion operators (typed by the parser as operator T) ----
+ "operator bool",
+ "operator int",
+ "operator double",
+ "operator float",
+ # ---- STL container / iteration customization points -------------
+ "begin", "end",
+ "cbegin", "cend",
+ "rbegin", "rend",
+ "crbegin", "crend",
+ "size", "max_size", "empty",
+ "data", "swap",
+ "hash_value",
+ "to_string",
+ # ---- Hash specialization customization (called via std::hash) ----
+ # ``operator()`` already covered above.
+ # ---- Coroutine customization points -----------------------------
+ "await_ready", "await_suspend", "await_resume",
+ "promise_type",
+ "get_return_object",
+ "initial_suspend", "final_suspend",
+ "return_void", "return_value",
+ "unhandled_exception",
+ "yield_value",
+ # ---- std::format / std::print customization ---------------------
+ "format", "format_to", "parse",
+ # ---- std::error_code / std::error_category interface ------------
+ "message", "name", "default_error_condition",
+ # ---- Standard library tag / trait override methods --------------
+ "value_type", "key_type", "mapped_type",
+ "iterator", "const_iterator",
+ "reference", "const_reference",
+})
+
+
+_CPP_LANGUAGES: frozenset[str] = frozenset({"cpp", "c"})
+
+
def is_contract_method(sym_name: str, sym_kind: str | None, language: str | None) -> bool:
"""Return True if *sym_name* is a reserved contract-method name in *language*.
@@ -118,10 +193,29 @@ def is_contract_method(sym_name: str, sym_kind: str | None, language: str | None
# class body (e.g. ``STDMETHODIMP CFoo::QueryInterface(...)``) as
# kind=function rather than method. Accept both — the name + COM
# language combination is restrictive enough on its own.
+ if sym_kind in ("constructor", "destructor"):
+ # The parser emits constructors as ``kind="method"`` with the
+ # bare class name, and destructors as ``kind="method"`` with a
+ # leading ``~``. Either way, the language runtime dispatches
+ # them (construction site / object teardown / RAII unwind), not
+ # a static caller. Treat both as contract methods for C/C++.
+ if language in _CPP_LANGUAGES:
+ return True
if sym_kind not in ("method", "function"):
return False
if language in _COM_LANGUAGES and sym_name in _COM_CONTRACT_METHOD_NAMES:
return True
if language in _JVM_LANGUAGES and sym_name in _JVM_CONTRACT_METHOD_NAMES:
return True
+ if language in _CPP_LANGUAGES:
+ if sym_name in _CPP_CONTRACT_METHOD_NAMES:
+ return True
+ # Destructor names land as ``~ClassName`` in the symbol name —
+ # match by prefix so we don't have to enumerate every class.
+ if sym_name.startswith("~"):
+ return True
+ # Generic conversion operator: ``operator Foo`` where ``Foo`` is
+ # a user type. The prefix is sufficient evidence.
+ if sym_name.startswith("operator "):
+ return True
return False
diff --git a/packages/core/src/repowise/core/analysis/dead_code/cpp_reachability.py b/packages/core/src/repowise/core/analysis/dead_code/cpp_reachability.py
new file mode 100644
index 000000000..5622de530
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/dead_code/cpp_reachability.py
@@ -0,0 +1,233 @@
+"""Directory-granular reachability for C and C++ source.
+
+The generic ``in_degree == 0`` view misses four real C/C++ shapes the
+file-level import graph cannot see:
+
+- **Header-as-API**. A public header (``include/leveldb/cache.h``) is a
+ pure declaration file. Without a ``compile_commands.json``, the
+ consumers of ``leveldb::Cache`` reach the declaration only through
+ type-use, ``extends``, ``implements``, or ``reads`` edges on its
+ declared symbols — never through a file-level ``imports`` edge. A
+ header whose symbols are referenced anywhere is live.
+- **``int main`` carriers.** Every ``apps/io_tester/io_tester.cc``,
+ ``demos/foo_demo.cc``, ``benchmarks/db_bench.cc``, and
+ ``LLVMFuzzerTestOneInput``-bearing fuzz harness defines its own
+ binary entry. They are the entry point and have no importer by
+ design.
+- **Sibling-rescued directories.** Internal headers in the same
+ directory as their sibling implementation files share an inclusion
+ relationship the resolver may miss when ``compile_commands.json`` is
+ absent. If the directory has any live source file, internal headers
+ alongside it are part of the same compilation unit.
+- **Conditional-compile alternatives.** CMake ``option(WITH_OPENSSL)``
+ selects one of ``crypto_openssl.cc`` / ``crypto_gnutls.cc`` at
+ configure time. Whichever was *not* picked by the local configure
+ still ships as live source. Detected heuristically as same-directory
+ siblings whose filenames share a stem prefix (``env_posix.cc`` /
+ ``env_windows.cc``, ``crypto_openssl.cc`` / ``crypto_gnutls.cc``).
+
+The helper derives directories from the graph itself; the
+:class:`CppWorkspaceIndex` populated during ingestion is not threaded
+into the analyzer. Workspace-discovered conditional sources surface
+through the warmup as ``is_never_flag`` / ``is_entry_point`` graph
+attributes instead.
+"""
+
+from __future__ import annotations
+
+from pathlib import PurePosixPath
+from typing import Any
+
+# File extensions this module rescues. The C/C++ tree-sitter grammar
+# tag covers all of these; the resolver shares them too.
+_CPP_HEADER_EXTS: tuple[str, ...] = (
+ ".h", ".hpp", ".hxx", ".hh", ".h++", ".inc",
+)
+_CPP_SOURCE_EXTS: tuple[str, ...] = (
+ ".c", ".cc", ".cpp", ".cxx", ".c++", ".C",
+)
+_CPP_ALL_EXTS: tuple[str, ...] = _CPP_HEADER_EXTS + _CPP_SOURCE_EXTS
+
+
+# Function names that mark a translation unit as a binary entry point.
+# A file defining one of these is the program / DLL / fuzzer entry — no
+# importer will ever exist by design.
+_CPP_ENTRY_FUNCTION_NAMES: frozenset[str] = frozenset({
+ "main",
+ "WinMain",
+ "wWinMain",
+ "wmain",
+ "LLVMFuzzerTestOneInput",
+ "LLVMFuzzerInitialize",
+ "DllMain",
+})
+
+
+# Edge types that count as "this symbol is used by something". A header
+# whose declared symbols carry any of these inbound edges is live, even
+# without a file-level ``imports`` edge from the consumer.
+_SYMBOL_USE_EDGE_TYPES: frozenset[str] = frozenset({
+ "calls",
+ "method_implements",
+ "reads",
+ "extends",
+ "implements",
+ "type_use",
+})
+
+
+def is_cpp_path(path: str) -> bool:
+ """Return True if *path* has a C or C++ source/header extension."""
+ return path.endswith(_CPP_ALL_EXTS)
+
+
+def _is_header(path: str) -> bool:
+ return path.endswith(_CPP_HEADER_EXTS)
+
+
+def _dir(node: str) -> str:
+ """Repo-relative POSIX directory of a C/C++ file ("" = repo root)."""
+ parent = PurePosixPath(node).parent.as_posix()
+ return "" if parent == "." else parent
+
+
+def build_cpp_package_files(graph: Any) -> dict[str, list[str]]:
+ """Group every C/C++ file node by directory.
+
+ Directory is the closest thing to a "compilation neighborhood" the
+ graph can derive without the workspace index — siblings in the same
+ directory typically share a CMake / Bazel target.
+ """
+ packages: dict[str, list[str]] = {}
+ for node in graph.nodes():
+ s = str(node)
+ if is_cpp_path(s):
+ packages.setdefault(_dir(s), []).append(s)
+ return packages
+
+
+def _file_defines_entry_function(graph: Any, file_node: str) -> bool:
+ """True if *file_node* defines an ``int main`` / ``WinMain`` / fuzzer entry."""
+ for succ in graph.successors(file_node):
+ succ_data = graph.nodes.get(succ, {})
+ if succ_data.get("node_type") != "symbol":
+ continue
+ edge = graph.get_edge_data(file_node, succ, {})
+ if edge.get("edge_type") != "defines":
+ continue
+ if (
+ succ_data.get("kind") in ("function", "method")
+ and succ_data.get("name") in _CPP_ENTRY_FUNCTION_NAMES
+ ):
+ return True
+ return False
+
+
+def _any_defined_symbol_is_used(graph: Any, file_node: str) -> bool:
+ """True iff any symbol defined in *file_node* carries an inbound use edge.
+
+ Drives the header-reached-by-symbol-reference rescue: a header that
+ no TU ``#include``d directly, but whose declared struct / class
+ appears as a parameter, field, return, or base type elsewhere in the
+ codebase, is live.
+ """
+ for succ in graph.successors(file_node):
+ succ_data = graph.nodes.get(succ, {})
+ if succ_data.get("node_type") != "symbol":
+ continue
+ edge = graph.get_edge_data(file_node, succ, {})
+ if edge.get("edge_type") != "defines":
+ continue
+ for pred in graph.predecessors(succ):
+ etype = graph[pred][succ].get("edge_type")
+ if etype in _SYMBOL_USE_EDGE_TYPES:
+ return True
+ return False
+
+
+def _stem_prefix(path: str) -> str | None:
+ """First ``_``-separated chunk of a filename's stem.
+
+ ``env_posix.cc`` → ``env``; ``crypto_openssl.cc`` → ``crypto``;
+ ``standalone.cc`` → None (no underscore — not a conditional alt).
+ """
+ name = PurePosixPath(path).name
+ dot = name.rfind(".")
+ stem = name[:dot] if dot > 0 else name
+ underscore = stem.find("_")
+ if underscore <= 0:
+ return None
+ return stem[:underscore]
+
+
+def is_cpp_file_reachable(
+ node: str,
+ graph: Any,
+ package_files: dict[str, list[str]],
+) -> bool:
+ """Return True if a C/C++ source file is reachable beyond ``in_degree``.
+
+ Called from the analyzer only for ``.c``/``.cc``/``.cpp``/``.cxx``/
+ ``.h``/``.hpp``/``.hxx`` nodes that have already survived the
+ generic skips (``is_entry_point``, ``is_test``, ``is_never_flag``,
+ fixture / barrel filters). Rules below short-circuit.
+ """
+ if graph.in_degree(node) > 0:
+ return True
+
+ # ``int main`` / ``WinMain`` / fuzzer entry — the file IS the binary
+ # entry point.
+ if _file_defines_entry_function(graph, node):
+ return True
+
+ is_header = _is_header(node)
+
+ # Header-reached-by-symbol-reference rescue. Public-API headers
+ # whose declared types are referenced anywhere (param / field /
+ # return / extends / implements / type alias RHS) are live even
+ # without a direct ``#include`` chain.
+ if is_header and _any_defined_symbol_is_used(graph, node):
+ return True
+
+ siblings = package_files.get(_dir(node), ())
+ stem_prefix = _stem_prefix(node)
+ has_sibling_with_importer = False
+ has_sibling_entry = False
+ has_conditional_pair = False
+ for sibling in siblings:
+ if sibling == node:
+ continue
+ sib_data = graph.nodes.get(sibling, {})
+ sib_has_importer = graph.in_degree(sibling) > 0
+ if sib_data.get("is_entry_point", False):
+ has_sibling_entry = True
+ break
+ if _file_defines_entry_function(graph, sibling):
+ has_sibling_entry = True
+ break
+ if sib_has_importer:
+ has_sibling_with_importer = True
+ # Conditional-alt pairing: same directory + shared stem
+ # prefix (``env_posix.cc`` ↔ ``env_windows.cc``,
+ # ``crypto_openssl.cc`` ↔ ``crypto_gnutls.cc``).
+ sib_prefix = _stem_prefix(sibling)
+ if stem_prefix and sib_prefix and sib_prefix == stem_prefix:
+ has_conditional_pair = True
+ break
+
+ if has_sibling_entry:
+ # Any sibling is an entry point — we are part of an apps / demo
+ # / cmd directory. Treat as live regardless of header/source
+ # status; helper files alongside ``main.cc`` are not dead.
+ return True
+
+ if is_header and has_sibling_with_importer:
+ # Internal header sitting next to its implementation .cc whose
+ # importer chain we observed — the header is implicitly part
+ # of the same TU.
+ return True
+
+ if has_conditional_pair:
+ return True
+
+ return False
diff --git a/packages/core/src/repowise/core/analysis/dead_code/dynamic_markers.py b/packages/core/src/repowise/core/analysis/dead_code/dynamic_markers.py
index 34cfa7b89..bcef04bdf 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/dynamic_markers.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/dynamic_markers.py
@@ -243,6 +243,180 @@ _DYNAMIC_IMPORT_MARKERS: dict[str, tuple[str, ...]] = {
# Deprecated items are intentionally present but winding down.
'#[deprecated',
),
+ # C — function-pointer / dynamic-loading idioms shared with C++.
+ ".c": (
+ "dlopen(",
+ "dlsym(",
+ "dlmopen(",
+ "LoadLibrary(",
+ "LoadLibraryA(",
+ "LoadLibraryW(",
+ "LoadLibraryEx",
+ "GetProcAddress(",
+ "__attribute__((constructor))",
+ "__attribute__((destructor))",
+ "__attribute__((used))",
+ "__attribute__((weak))",
+ "[[gnu::retain]]",
+ "[[gnu::used]]",
+ "LLVMFuzzerTestOneInput",
+ "JNI_OnLoad",
+ ),
+ # C++ — all of the C markers plus framework / registration / signal
+ # / slot idioms invoking symbols by macro expansion or runtime
+ # registration. Each token's presence in the file means at least one
+ # symbol is reached through a path the static graph cannot observe.
+ ".cc": (
+ "dlopen(",
+ "dlsym(",
+ "dlmopen(",
+ "LoadLibrary(",
+ "LoadLibraryA(",
+ "LoadLibraryW(",
+ "GetProcAddress(",
+ "Q_OBJECT",
+ "Q_GADGET",
+ "Q_NAMESPACE",
+ "QObject::connect(",
+ "QML_ELEMENT",
+ "SIGNAL(",
+ "SLOT(",
+ "TEST(",
+ "TEST_F(",
+ "TEST_P(",
+ "TYPED_TEST(",
+ "INSTANTIATE_TEST_SUITE_P(",
+ "FRIEND_TEST(",
+ "BOOST_AUTO_TEST_CASE",
+ "BOOST_FIXTURE_TEST_CASE",
+ "BOOST_AUTO_TEST_SUITE",
+ "CATCH_TEST_CASE",
+ "TEST_CASE(",
+ "SCENARIO(",
+ "DOCTEST_TEST_CASE",
+ "BENCHMARK(",
+ "BENCHMARK_F(",
+ "BENCHMARK_REGISTER_F(",
+ "BENCHMARK_MAIN(",
+ "LLVMFuzzerTestOneInput",
+ "LLVMFuzzerInitialize",
+ "REGISTER_OP(",
+ "REGISTER_KERNEL_BUILDER(",
+ "BOOST_CLASS_EXPORT",
+ "PLUGINLIB_EXPORT_CLASS(",
+ "RCLCPP_COMPONENTS_REGISTER_NODE(",
+ "PYBIND11_MODULE(",
+ "BOOST_PYTHON_MODULE(",
+ "NAPI_MODULE(",
+ "EM_JS(",
+ "EM_ASM",
+ "__attribute__((constructor))",
+ "__attribute__((destructor))",
+ "__attribute__((used))",
+ "__attribute__((weak))",
+ "[[gnu::retain]]",
+ "[[gnu::used]]",
+ "JNI_OnLoad",
+ 'extern "C"',
+ ),
+ ".cpp": (
+ "dlopen(",
+ "dlsym(",
+ "LoadLibrary(",
+ "GetProcAddress(",
+ "Q_OBJECT",
+ "Q_GADGET",
+ "Q_NAMESPACE",
+ "QObject::connect(",
+ "QML_ELEMENT",
+ "SIGNAL(",
+ "SLOT(",
+ "TEST(",
+ "TEST_F(",
+ "TEST_P(",
+ "TYPED_TEST(",
+ "INSTANTIATE_TEST_SUITE_P(",
+ "BOOST_AUTO_TEST_CASE",
+ "BOOST_FIXTURE_TEST_CASE",
+ "CATCH_TEST_CASE",
+ "TEST_CASE(",
+ "SCENARIO(",
+ "DOCTEST_TEST_CASE",
+ "BENCHMARK(",
+ "BENCHMARK_F(",
+ "BENCHMARK_MAIN(",
+ "LLVMFuzzerTestOneInput",
+ "REGISTER_OP(",
+ "REGISTER_KERNEL_BUILDER(",
+ "BOOST_CLASS_EXPORT",
+ "PLUGINLIB_EXPORT_CLASS(",
+ "RCLCPP_COMPONENTS_REGISTER_NODE(",
+ "PYBIND11_MODULE(",
+ "BOOST_PYTHON_MODULE(",
+ "NAPI_MODULE(",
+ "__attribute__((constructor))",
+ "__attribute__((used))",
+ "[[gnu::retain]]",
+ "[[gnu::used]]",
+ "JNI_OnLoad",
+ 'extern "C"',
+ ),
+ ".cxx": (
+ "Q_OBJECT",
+ "Q_GADGET",
+ "QObject::connect(",
+ "SIGNAL(",
+ "SLOT(",
+ "TEST(",
+ "TEST_F(",
+ "BOOST_AUTO_TEST_CASE",
+ "TEST_CASE(",
+ "BENCHMARK(",
+ "PYBIND11_MODULE(",
+ "__attribute__((constructor))",
+ "__attribute__((used))",
+ "[[gnu::retain]]",
+ 'extern "C"',
+ ),
+ # C++ headers — Q_OBJECT macro expands to a vtable + MOC entry, so a
+ # header with ``Q_OBJECT`` participates in the Qt meta-object
+ # protocol the static graph cannot trace.
+ ".h": (
+ "Q_OBJECT",
+ "Q_GADGET",
+ "Q_NAMESPACE",
+ "Q_DECLARE_METATYPE(",
+ "Q_PROPERTY(",
+ "QML_ELEMENT",
+ "BOOST_CLASS_EXPORT",
+ "PYBIND11_MODULE(",
+ "__attribute__((constructor))",
+ "__attribute__((used))",
+ "[[gnu::retain]]",
+ 'extern "C"',
+ ),
+ ".hpp": (
+ "Q_OBJECT",
+ "Q_GADGET",
+ "Q_NAMESPACE",
+ "Q_DECLARE_METATYPE(",
+ "Q_PROPERTY(",
+ "QML_ELEMENT",
+ "BOOST_CLASS_EXPORT",
+ "PYBIND11_MODULE(",
+ "__attribute__((constructor))",
+ "__attribute__((used))",
+ "[[gnu::retain]]",
+ 'extern "C"',
+ ),
+ ".hxx": (
+ "Q_OBJECT",
+ "Q_GADGET",
+ "BOOST_CLASS_EXPORT",
+ "__attribute__((constructor))",
+ "__attribute__((used))",
+ 'extern "C"',
+ ),
".cs": (
# Reflection-driven type loading
"Type.GetType(",
diff --git a/tests/unit/analysis/test_cpp_reachability.py b/tests/unit/analysis/test_cpp_reachability.py
new file mode 100644
index 000000000..5aa408019
--- /dev/null
+++ b/tests/unit/analysis/test_cpp_reachability.py
@@ -0,0 +1,524 @@
+"""Regression tests: C/C++ directory-aware reachability + never-flag rules.
+
+Asserts:
+
+- ``is_cpp_file_reachable`` rescues ``int main`` / ``WinMain`` / fuzzer
+ carriers, public-API headers whose symbols are referenced, internal
+ headers next to their implementation, and conditional-compile
+ alternates that share a stem prefix;
+- never-flag globs cover ``apps/``, ``demos/``, ``examples/``,
+ ``benchmarks/``, ``tools/``, ``tests/{perf,fuzz,unit,manual}`` trees,
+ generated source patterns (``moc_*.cpp``, ``*.pb.cc``,
+ ``*.grpc.pb.cc``, ``*.tab.c``, ``*_wrap.cxx``), conventional port
+ example headers, and the broader ``external/extern/contrib/submodules``
+ vendor roots;
+- C/C++ contract methods (constructors, destructors, operator
+ overloads, conversion operators, STL CPOs, coroutine machinery) are
+ protected from the unused-export / unused-internal passes;
+- ``LLVMFuzzerTestOneInput`` is recognised as an entry-point symbol
+ name.
+"""
+
+from __future__ import annotations
+
+import fnmatch
+
+import networkx as nx
+
+from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind
+from repowise.core.analysis.dead_code.analyzer import _ENTRY_POINT_SYMBOL_NAMES
+from repowise.core.analysis.dead_code.constants import _NEVER_FLAG_PATTERNS
+from repowise.core.analysis.dead_code.contract_methods import is_contract_method
+from repowise.core.analysis.dead_code.cpp_reachability import (
+ build_cpp_package_files,
+ is_cpp_file_reachable,
+)
+
+
+# ---------------------------------------------------------------------------
+# Graph helper
+# ---------------------------------------------------------------------------
+
+
+def _build_graph(nodes: dict[str, dict], edges: list | None = None) -> nx.DiGraph:
+ g = nx.DiGraph()
+ for name, attrs in nodes.items():
+ attrs = dict(attrs)
+ sym_list = attrs.pop("symbols", [])
+ g.add_node(name, **attrs)
+ for sym in sym_list:
+ sym_id = f"{name}::{sym['name']}"
+ g.add_node(sym_id, node_type="symbol", file_path=name, **sym)
+ g.add_edge(name, sym_id, edge_type="defines")
+ for edge in edges or []:
+ if len(edge) == 3:
+ g.add_edge(edge[0], edge[1], **(edge[2]))
+ else:
+ g.add_edge(edge[0], edge[1])
+ return g
+
+
+def _cpp_file(**overrides: object) -> dict:
+ base = {
+ "language": "cpp",
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 0,
+ "symbols": [],
+ }
+ base.update(overrides)
+ return base
+
+
+# ---------------------------------------------------------------------------
+# is_cpp_file_reachable
+# ---------------------------------------------------------------------------
+
+
+class TestCppFileReachable:
+ def test_in_degree_positive_is_reachable(self) -> None:
+ graph = _build_graph(
+ {
+ "a/foo.h": _cpp_file(),
+ "a/foo.cc": _cpp_file(),
+ },
+ edges=[("a/foo.cc", "a/foo.h", {"edge_type": "imports"})],
+ )
+ pkgs = build_cpp_package_files(graph)
+ assert is_cpp_file_reachable("a/foo.h", graph, pkgs) is True
+
+ def test_main_carrier_is_reachable(self) -> None:
+ graph = _build_graph(
+ {
+ "apps/runner/main.cc": _cpp_file(
+ symbols=[{
+ "name": "main",
+ "kind": "function",
+ "visibility": "public",
+ "language": "cpp",
+ }],
+ ),
+ },
+ )
+ pkgs = build_cpp_package_files(graph)
+ assert is_cpp_file_reachable("apps/runner/main.cc", graph, pkgs) is True
+
+ def test_winmain_carrier_is_reachable(self) -> None:
+ graph = _build_graph(
+ {
+ "src/gui/app.cpp": _cpp_file(
+ symbols=[{
+ "name": "WinMain",
+ "kind": "function",
+ "visibility": "public",
+ "language": "cpp",
+ }],
+ ),
+ },
+ )
+ pkgs = build_cpp_package_files(graph)
+ assert is_cpp_file_reachable("src/gui/app.cpp", graph, pkgs) is True
+
+ def test_libfuzzer_entry_carrier_is_reachable(self) -> None:
+ graph = _build_graph(
+ {
+ "fuzz/parse_fuzz.cc": _cpp_file(
+ symbols=[{
+ "name": "LLVMFuzzerTestOneInput",
+ "kind": "function",
+ "visibility": "public",
+ "language": "cpp",
+ }],
+ ),
+ },
+ )
+ pkgs = build_cpp_package_files(graph)
+ assert is_cpp_file_reachable("fuzz/parse_fuzz.cc", graph, pkgs) is True
+
+ def test_header_with_referenced_symbol_is_reachable(self) -> None:
+ graph = _build_graph(
+ {
+ "include/leveldb/cache.h": _cpp_file(
+ symbols=[{
+ "name": "Cache",
+ "kind": "class",
+ "visibility": "public",
+ "language": "cpp",
+ }],
+ ),
+ "src/consumer.cc": _cpp_file(
+ symbols=[{
+ "name": "use_it",
+ "kind": "function",
+ "visibility": "public",
+ "language": "cpp",
+ }],
+ ),
+ },
+ edges=[
+ ("src/consumer.cc::use_it", "include/leveldb/cache.h::Cache",
+ {"edge_type": "type_use"}),
+ ],
+ )
+ pkgs = build_cpp_package_files(graph)
+ assert is_cpp_file_reachable(
+ "include/leveldb/cache.h", graph, pkgs
+ ) is True
+
+ def test_header_with_implements_edge_is_reachable(self) -> None:
+ graph = _build_graph(
+ {
+ "include/iface.hpp": _cpp_file(
+ symbols=[{
+ "name": "IFace",
+ "kind": "interface",
+ "visibility": "public",
+ "language": "cpp",
+ }],
+ ),
+ "src/impl.cc": _cpp_file(
+ symbols=[{
+ "name": "Impl",
+ "kind": "class",
+ "visibility": "public",
+ "language": "cpp",
+ }],
+ ),
+ },
+ edges=[
+ ("src/impl.cc::Impl", "include/iface.hpp::IFace",
+ {"edge_type": "implements"}),
+ ],
+ )
+ pkgs = build_cpp_package_files(graph)
+ assert is_cpp_file_reachable("include/iface.hpp", graph, pkgs) is True
+
+ def test_internal_header_rescued_by_sibling_with_importer(self) -> None:
+ # builder.h has no direct importer, but builder.cc next to it does.
+ graph = _build_graph(
+ {
+ "db/builder.h": _cpp_file(),
+ "db/builder.cc": _cpp_file(),
+ "db/version_set.cc": _cpp_file(),
+ },
+ edges=[
+ ("db/version_set.cc", "db/builder.cc", {"edge_type": "imports"}),
+ ],
+ )
+ pkgs = build_cpp_package_files(graph)
+ assert is_cpp_file_reachable("db/builder.h", graph, pkgs) is True
+
+ def test_conditional_alt_pair_rescued(self) -> None:
+ # env_posix.cc has an importer; env_windows.cc does not but is the
+ # mutually-exclusive conditional alternative.
+ graph = _build_graph(
+ {
+ "util/env_posix.cc": _cpp_file(),
+ "util/env_windows.cc": _cpp_file(),
+ "util/consumer.cc": _cpp_file(),
+ },
+ edges=[
+ ("util/consumer.cc", "util/env_posix.cc", {"edge_type": "imports"}),
+ ],
+ )
+ pkgs = build_cpp_package_files(graph)
+ assert is_cpp_file_reachable("util/env_windows.cc", graph, pkgs) is True
+
+ def test_sibling_of_main_file_is_reachable(self) -> None:
+ # An apps directory: main.cc carries main(); helper.cc next to it
+ # has no importer but is part of the same binary.
+ graph = _build_graph(
+ {
+ "apps/runner/main.cc": _cpp_file(
+ symbols=[{
+ "name": "main",
+ "kind": "function",
+ "visibility": "public",
+ "language": "cpp",
+ }],
+ ),
+ "apps/runner/helper.cc": _cpp_file(),
+ },
+ )
+ pkgs = build_cpp_package_files(graph)
+ assert is_cpp_file_reachable(
+ "apps/runner/helper.cc", graph, pkgs
+ ) is True
+
+ def test_orphan_unrelated_header_is_unreachable(self) -> None:
+ # A pure orphan header with no symbol references and no live
+ # siblings should still surface as dead.
+ graph = _build_graph(
+ {
+ "lib/legacy.h": _cpp_file(
+ symbols=[{
+ "name": "Legacy",
+ "kind": "class",
+ "visibility": "public",
+ "language": "cpp",
+ }],
+ ),
+ },
+ )
+ pkgs = build_cpp_package_files(graph)
+ assert is_cpp_file_reachable("lib/legacy.h", graph, pkgs) is False
+
+ def test_orphan_source_with_no_sibling_signal_is_unreachable(self) -> None:
+ graph = _build_graph(
+ {
+ "lib/dead.cc": _cpp_file(),
+ },
+ )
+ pkgs = build_cpp_package_files(graph)
+ assert is_cpp_file_reachable("lib/dead.cc", graph, pkgs) is False
+
+
+# ---------------------------------------------------------------------------
+# Never-flag patterns
+# ---------------------------------------------------------------------------
+
+
+def _matches_any(path: str) -> bool:
+ return any(fnmatch.fnmatch(path, p) for p in _NEVER_FLAG_PATTERNS)
+
+
+class TestCppNeverFlag:
+ def test_apps_tree_never_flagged(self) -> None:
+ assert _matches_any("apps/io_tester/io_tester.cc")
+ assert _matches_any("seastar/apps/memcached/memcache.cc")
+ assert _matches_any("apps/runner/main.cpp")
+
+ def test_demos_tree_never_flagged(self) -> None:
+ assert _matches_any("demos/echo_demo.cc")
+ assert _matches_any("seastar/demos/hello_demo.cpp")
+
+ def test_examples_tree_never_flagged(self) -> None:
+ assert _matches_any("examples/hello.cc")
+ assert _matches_any("project/examples/snippet.cpp")
+ assert _matches_any("examples/dir/sub/nested.cc")
+
+ def test_benchmarks_tree_never_flagged(self) -> None:
+ assert _matches_any("benchmarks/db_bench.cc")
+ assert _matches_any("project/benchmarks/throughput.cpp")
+
+ def test_tools_tree_never_flagged(self) -> None:
+ assert _matches_any("tools/leveldbutil.cc")
+
+ def test_tests_perf_fuzz_unit_manual_never_flagged(self) -> None:
+ assert _matches_any("seastar/tests/perf/allocator_perf.cc")
+ assert _matches_any("seastar/tests/fuzz/sstring_fuzz.cc")
+ assert _matches_any("seastar/tests/unit/metrics_tester.cc")
+ assert _matches_any("seastar/tests/manual/io-trace-parse.py")
+
+ def test_test_suffix_files_never_flagged(self) -> None:
+ assert _matches_any("foo_test.cc")
+ assert _matches_any("nested/dir/bar_unittest.cpp")
+ assert _matches_any("baz_perf.cc")
+ assert _matches_any("qux_benchmark.cpp")
+ assert _matches_any("net_fuzz.cc")
+
+ def test_port_example_never_flagged(self) -> None:
+ assert _matches_any("port/port_example.h")
+ assert _matches_any("leveldb/port/port_example.h")
+
+ def test_generated_qt_protobuf_grpc_globs(self) -> None:
+ assert _matches_any("moc_widget.cpp")
+ assert _matches_any("ui_widget.h")
+ assert _matches_any("qrc_resources.cpp")
+ assert _matches_any("api.pb.cc")
+ assert _matches_any("api.pb.h")
+ assert _matches_any("api.grpc.pb.cc")
+ assert _matches_any("api.grpc.pb.h")
+
+ def test_generated_yacc_flex_swig_globs(self) -> None:
+ assert _matches_any("parser.tab.c")
+ assert _matches_any("parser.tab.h")
+ assert _matches_any("lexer.yy.c")
+ assert _matches_any("module_wrap.cxx")
+
+ def test_external_extern_contrib_submodules_globs(self) -> None:
+ assert _matches_any("external/spdlog/spdlog.cc")
+ assert _matches_any("project/external/fmt/format.h")
+ assert _matches_any("extern/zlib/zlib.h")
+ assert _matches_any("contrib/jemalloc/jemalloc.c")
+ assert _matches_any("submodules/anything/x")
+
+ def test_ordinary_source_not_flagged(self) -> None:
+ # Don't accidentally never-flag normal source.
+ assert not _matches_any("src/db/version_set.cc")
+ assert not _matches_any("lib/foo.cpp")
+ assert not _matches_any("include/proj/api.h")
+
+
+# ---------------------------------------------------------------------------
+# Contract methods
+# ---------------------------------------------------------------------------
+
+
+class TestCppContractMethods:
+ def test_operator_overloads_protected(self) -> None:
+ for op in ("operator==", "operator!=", "operator<", "operator<=>",
+ "operator+", "operator*", "operator()", "operator[]",
+ "operator->", "operator new", "operator delete"):
+ assert is_contract_method(op, "method", "cpp"), op
+
+ def test_stl_customization_points_protected(self) -> None:
+ for n in ("begin", "end", "cbegin", "cend", "swap", "size",
+ "empty", "data", "hash_value"):
+ assert is_contract_method(n, "method", "cpp"), n
+
+ def test_coroutine_machinery_protected(self) -> None:
+ for n in ("await_ready", "await_suspend", "await_resume",
+ "get_return_object", "initial_suspend", "final_suspend"):
+ assert is_contract_method(n, "method", "cpp"), n
+
+ def test_constructor_destructor_protected(self) -> None:
+ # Constructor: kind=constructor.
+ assert is_contract_method("MyClass", "constructor", "cpp")
+ # Destructor: kind=method with leading ``~``.
+ assert is_contract_method("~MyClass", "method", "cpp")
+ # Or kind=destructor.
+ assert is_contract_method("~MyClass", "destructor", "cpp")
+
+ def test_conversion_operator_protected(self) -> None:
+ assert is_contract_method("operator bool", "method", "cpp")
+ assert is_contract_method("operator MyType", "method", "cpp")
+
+ def test_unrelated_language_not_protected(self) -> None:
+ assert not is_contract_method("operator==", "method", "python")
+ assert not is_contract_method("begin", "method", "java")
+
+ def test_random_user_function_not_protected(self) -> None:
+ assert not is_contract_method("do_thing", "method", "cpp")
+
+
+# ---------------------------------------------------------------------------
+# Entry-point symbol names
+# ---------------------------------------------------------------------------
+
+
+class TestCppEntryPointSymbols:
+ def test_libfuzzer_entry_recognised(self) -> None:
+ assert "LLVMFuzzerTestOneInput" in _ENTRY_POINT_SYMBOL_NAMES
+ assert "LLVMFuzzerInitialize" in _ENTRY_POINT_SYMBOL_NAMES
+
+ def test_windows_main_variants_recognised(self) -> None:
+ # Already covered before Phase 3; spot-check they didn't regress.
+ for n in ("main", "WinMain", "wWinMain", "wmain", "DllMain"):
+ assert n in _ENTRY_POINT_SYMBOL_NAMES
+
+
+# ---------------------------------------------------------------------------
+# End-to-end via DeadCodeAnalyzer
+# ---------------------------------------------------------------------------
+
+
+class TestCppEndToEnd:
+ def test_main_carrier_not_flagged_unreachable(self) -> None:
+ graph = _build_graph(
+ {
+ "src/runner.cc": _cpp_file(
+ symbols=[{
+ "name": "main",
+ "kind": "function",
+ "visibility": "public",
+ "language": "cpp",
+ }],
+ ),
+ },
+ )
+ analyzer = DeadCodeAnalyzer(graph)
+ report = analyzer.analyze({
+ "detect_unused_exports": False,
+ "detect_unused_internals": False,
+ "detect_zombie_packages": False,
+ })
+ assert not any(
+ f.kind == DeadCodeKind.UNREACHABLE_FILE
+ and f.file_path == "src/runner.cc"
+ for f in report.findings
+ )
+
+ def test_public_header_with_type_use_not_flagged_unreachable(self) -> None:
+ graph = _build_graph(
+ {
+ "include/proj/api.h": _cpp_file(
+ symbols=[{
+ "name": "Api",
+ "kind": "class",
+ "visibility": "public",
+ "language": "cpp",
+ }],
+ ),
+ "src/use.cc": _cpp_file(
+ symbols=[{
+ "name": "client",
+ "kind": "function",
+ "visibility": "public",
+ "language": "cpp",
+ }],
+ ),
+ },
+ edges=[
+ ("src/use.cc::client", "include/proj/api.h::Api",
+ {"edge_type": "type_use"}),
+ ],
+ )
+ analyzer = DeadCodeAnalyzer(graph)
+ report = analyzer.analyze({
+ "detect_unused_exports": False,
+ "detect_unused_internals": False,
+ "detect_zombie_packages": False,
+ })
+ unreachable_paths = {
+ f.file_path for f in report.findings
+ if f.kind == DeadCodeKind.UNREACHABLE_FILE
+ }
+ assert "include/proj/api.h" not in unreachable_paths
+
+ def test_operator_overload_not_flagged_unused_export(self) -> None:
+ # A struct's ``operator==`` with no static caller — the compiler
+ # synthesizes ``std::equal_to`` / ``std::set`` lookups, no graph
+ # edge. Should not appear in unused-export findings.
+ graph = _build_graph(
+ {
+ "lib/widget.cc": _cpp_file(
+ symbols=[{
+ "name": "operator==",
+ "kind": "method",
+ "visibility": "public",
+ "language": "cpp",
+ }],
+ ),
+ },
+ edges=[("driver.cc", "lib/widget.cc", {"edge_type": "imports"})],
+ )
+ graph.add_node("driver.cc", language="cpp", symbol_count=0)
+ analyzer = DeadCodeAnalyzer(graph)
+ report = analyzer.analyze({"min_confidence": 0.0})
+ unused_export_safe = [
+ f for f in report.findings
+ if f.kind == DeadCodeKind.UNUSED_EXPORT
+ and f.symbol_name == "operator=="
+ and f.safe_to_delete
+ ]
+ assert not unused_export_safe
+
+ def test_apps_tree_never_flag_short_circuits(self) -> None:
+ graph = _build_graph(
+ {
+ "apps/io_tester/io_tester.cc": _cpp_file(
+ symbols=[{
+ "name": "context",
+ "kind": "class",
+ "visibility": "public",
+ "language": "cpp",
+ }],
+ ),
+ },
+ )
+ analyzer = DeadCodeAnalyzer(graph)
+ report = analyzer.analyze({"min_confidence": 0.0})
+ paths = {f.file_path for f in report.findings}
+ assert "apps/io_tester/io_tester.cc" not in paths