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(dead-code): count a C/C++ name written outside its declaration as a use (#2909)

Raghav Chamadiya00883e0ccb40
diff --git a/docs/layers/DEAD_CODE.md b/docs/layers/DEAD_CODE.md
index 9ebce47a3..845af1458 100644
--- a/docs/layers/DEAD_CODE.md
+++ b/docs/layers/DEAD_CODE.md
@@ -84,6 +84,21 @@ Rust helper is never flagged here. And the `lines` count on file and package fin
estimate (symbol count times ten), not a real line count, so treat the
"reclaimable lines" roll-up as an order of magnitude rather than a figure.
+### A C or C++ name written anywhere else is a use
+
+C, C++ and Objective-C symbols are used in ways that carry no edge: a callback
+passed to `SetTimer`, a function reached through a `#define` alias, a P/Invoke
+export named in a C# `[LibraryImport]`, an icall registered in a table header,
+a `.def` EXPORTS line, an assembly label. So an `unused_export` or
+`unused_internal` in these languages is dropped when any of the names its
+declaration introduces is written outside a declaration of it, in any code
+file or in a `.def`, `.asm` or `.s` file. A typedef contributes its tag and
+every alias (`typedef struct _X {...} X, *PX;`), and an enum its enumerators.
+Declarations do not count (the header prototype of a `.cpp` function), and
+neither do comments, prose strings and documentation. A COM method declared
+with `IFACEMETHODIMP` or `STDMETHODIMP` fills an interface slot and is never
+reported.
+
### How unreachable-file confidence is scored
An orphaned file that nobody has touched in a year is a much stronger signal than
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 9fda15be0..f6f408eb3 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -25,6 +25,11 @@ import structlog
from ...entry_candidacy import is_reachability_root
from ...ingestion.models import REACHABILITY_USE_EDGE_TYPES
from ...ingestion.symbol_identity import base_symbol_id, overload_sets
+from .c_name_uses import (
+ DEFINITION_HEADER_LINES,
+ DeclarationSites,
+ drop_preprocessed_named_elsewhere,
+)
from .constants import (
_CONTAINER_USE_LANGUAGES,
_DEAD_CODE_EXEMPT_LANGUAGES,
@@ -39,7 +44,7 @@ from .constants import (
_is_fixture_path,
never_flag_path,
)
-from .contract_methods import is_contract_method
+from .contract_methods import is_com_method_implementation, is_contract_method
from .dynamic_markers import (
find_dynamic_edge_files,
find_dynamic_import_files,
@@ -464,6 +469,10 @@ _ENTRY_POINT_SYMBOL_NAMES: frozenset[str] = frozenset(
"WinMain", # ANSI WinMain
"wmain", # Unicode console main
"ServiceMain", # Win32 service entry
+ # Screen savers: scrnsave.lib calls these three by name.
+ "ScreenSaverProc",
+ "ScreenSaverConfigureDialog",
+ "RegisterDialogClasses",
# ---- libFuzzer / Honggfuzz / AFL fuzz harness entries ------------
# The fuzzer driver invokes these by name via dlsym; no static
# caller will ever exist.
@@ -901,6 +910,14 @@ class DeadCodeAnalyzer:
if on_step:
on_step("zombie_packages")
+ # First: a C/C++ name written outside its declaration is a use, which
+ # settles the finding before any clamp re-scores it.
+ findings = drop_preprocessed_named_elsewhere(
+ findings,
+ self._source_map,
+ self._preprocessed_declaration_sites(),
+ self._unindexed_identifier_tokens(),
+ )
# Before the confidence filter, not after: a finding an unread importer
# could explain must be able to fall *below* min_confidence and drop
# out entirely, rather than being reported at a number it no longer
@@ -968,6 +985,19 @@ class DeadCodeAnalyzer:
return findings
+ def _preprocessed_declaration_sites(self) -> DeclarationSites:
+ """Where each C/C++ symbol name is declared: a prototype's whole span, a
+ definition's header lines. An occurrence there is not a use of it."""
+ sites: dict[str, list[tuple[str, int, int]]] = {}
+ for _, data in self.graph.nodes(data=True):
+ if data.get("node_type") != "symbol" or data.get("language") not in _PREPROCESSED_LANGUAGES:
+ continue
+ start, end = data.get("start_line") or 0, data.get("end_line") or 0
+ if not data.get("is_declaration"):
+ end = min(end, start + DEFINITION_HEADER_LINES - 1)
+ sites.setdefault(data.get("name", ""), []).append((data.get("file_path", ""), start, end))
+ return sites
+
def _unindexed_identifier_tokens(self) -> frozenset[str]:
"""Identifiers appearing in the source files ingestion never read.
@@ -1362,6 +1392,9 @@ class DeadCodeAnalyzer:
return False
if _is_compiler_invoked(sym, sym_name):
return False
+ # A COM interface method the runtime calls through the vtable.
+ if is_com_method_implementation(sym.get("signature"), sym.get("language")):
+ return False
if _is_declaration_only(sym):
return False
# Dotted names are namespace path fragments, not exports.
diff --git a/packages/core/src/repowise/core/analysis/dead_code/c_name_uses.py b/packages/core/src/repowise/core/analysis/dead_code/c_name_uses.py
new file mode 100644
index 000000000..ed27d6dd6
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/dead_code/c_name_uses.py
@@ -0,0 +1,242 @@
+"""A C/C++ symbol whose name is written outside its own declaration is used.
+
+A C or C++ symbol needs no import to be used, and most of its uses carry no
+graph edge either: a callback passed to ``SetTimer``, a function reached
+through a ``#define`` alias, a P/Invoke export named in a C# attribute, an
+icall registered in a table header, a ``.def`` EXPORTS line, a member defined
+in the ``.cpp`` beside its header. So for these languages a name written
+anywhere outside a declaration of it, in any indexed file or in a file ingestion
+could not read, is a use, and the finding is dropped. It is the C/C++
+counterpart of Python's ``local_refs``, widened to every file because a C/C++
+name is global to the program.
+
+One declaration can introduce several names.
+``typedef struct _ARM64_VFP_STATE {...} ARM64_VFP_STATE, *PARM64_VFP_STATE;``
+declares four for one struct, and code uses whichever it likes; an enum is used
+through its enumerators. Those names come from the declaration's own text,
+because the grammar emits one symbol per declaration and pointer declarators
+never become symbols at all.
+
+What does not count: the declaration itself, any other declaration of the same
+name (the header prototype of a ``.cpp`` function, an overload's header line),
+comments and prose strings in C-family code (a ``// FunctionName`` banner is
+not a call) and documentation files. Everything else counts, so an unrelated symbol sharing the name costs a
+true finding. That is the direction precision asks for.
+"""
+
+from __future__ import annotations
+
+import re
+from collections.abc import Iterator, Mapping
+from pathlib import PurePosixPath
+
+from ...ingestion.languages.registry import REGISTRY
+from .constants import _NON_CODE_LANGUAGES, _PREPROCESSED_LANGUAGES
+from .models import DeadCodeFindingData, DeadCodeKind
+from .name_occurrences import IDENTIFIER_RE, occurrence_files
+
+#: Kinds a C/C++ type declaration's finding can carry.
+TYPE_KINDS: frozenset[str] = frozenset({"struct", "class", "enum", "union", "type_alias"})
+
+#: Lines read past a declaration's recorded end for the ``} Alias, *PAlias;``
+#: tail, which a struct specifier's span stops short of when the closing brace
+#: and the declarators sit on separate lines.
+_TAIL_LINES = 3
+
+#: Lines of a definition, from its first, that may still be its header: the
+#: name sits one line below a return type written on its own line.
+DEFINITION_HEADER_LINES = 3
+
+_IDENT = re.compile(r"[A-Za-z_]\w*")
+_COMMENT = re.compile(r"/\*.*?\*/|//[^\n]*", re.DOTALL)
+#: Comments, skipping string literals so ``"http://x"`` is not read as one.
+_COMMENT_OR_STRING = re.compile(
+ rb'"(?:\\.|[^"\\\n])*"|\'(?:\\.|[^\'\\\n])*\'|/\*.*?\*/|//[^\n]*', re.DOTALL
+)
+_NOT_NEWLINE = re.compile(rb"[^\n]")
+_WHITESPACE = re.compile(rb"\s")
+_TAG = re.compile(r"\b(?:struct|union|enum|class)\s+([A-Za-z_]\w*)")
+_ENUMERATOR = re.compile(r"^\s*([A-Za-z_]\w*)\s*(?:=|$)")
+
+#: ``{name: [(path, first line, last line), ...]}``: where a symbol of that name
+#: is declared, so an occurrence there is not a use.
+DeclarationSites = Mapping[str, list[tuple[str, int, int]]]
+
+
+def is_preprocessed(path: str) -> bool:
+ """Whether *path* is in a language the preprocessor reaches into."""
+ return REGISTRY.from_extension(PurePosixPath(path).suffix) in _PREPROCESSED_LANGUAGES
+
+
+def declared_names(finding: DeadCodeFindingData, blob: bytes) -> list[str]:
+ """The finding's name plus the tag, typedef aliases and enumerators it adds."""
+ names = [finding.symbol_name or ""]
+ if finding.symbol_kind not in TYPE_KINDS or finding.start_line is None:
+ return names
+ lines = blob.split(b"\n")[finding.start_line - 1 : (finding.end_line or 0) + _TAIL_LINES]
+ text = _COMMENT.sub(" ", b"\n".join(lines).decode("utf-8", "ignore"))
+ text = "\n".join(line for line in text.split("\n") if not line.lstrip().startswith("#"))
+ open_at = text.find("{")
+ close_at = _matching_brace(text, open_at)
+ if close_at >= 0:
+ names.extend(_typedef_names(text, open_at, close_at))
+ if finding.symbol_kind == "enum":
+ names.extend(_enumerators(text[open_at + 1 : close_at]))
+ return list(dict.fromkeys(names))
+
+
+def _typedef_names(text: str, open_at: int, close_at: int) -> list[str]:
+ """The tag and declarator names of a ``typedef struct _X {...} X, *PX;``."""
+ head = text[:open_at]
+ if "typedef" not in head:
+ return []
+ semicolon = text.find(";", close_at)
+ tail = text[close_at + 1 : semicolon if semicolon >= 0 else None]
+ # A declarator's name is its last identifier: ``*PX``, ``ALIGNED(8) X``.
+ declarators = (_IDENT.findall(piece) for piece in tail.split(","))
+ return [*_TAG.findall(head), *(ids[-1] for ids in declarators if ids)]
+
+
+def _enumerators(body: str) -> list[str]:
+ """The enumerator names of an enum body."""
+ return [m.group(1) for m in (_ENUMERATOR.match(piece) for piece in body.split(",")) if m]
+
+
+def _matching_brace(text: str, open_at: int) -> int:
+ """Index of the ``}`` closing the ``{`` at *open_at*, or -1."""
+ if open_at < 0:
+ return -1
+ depth = 0
+ for index in range(open_at, len(text)):
+ char = text[index]
+ if char == "{":
+ depth += 1
+ elif char == "}":
+ depth -= 1
+ if depth == 0:
+ return index
+ return -1
+
+
+def _blank_prose(match: re.Match[bytes]) -> bytes:
+ """Blank a comment, or a string holding a space; keep a one-word string.
+
+ ``dlsym(h, "SymbolName")`` names a symbol; ``"505 Version Not Supported"``
+ is prose that happens to contain one.
+ """
+ text = match.group()
+ if text[:1] in (b'"', b"'") and not _WHITESPACE.search(text):
+ return text
+ return _NOT_NEWLINE.sub(b" ", text)
+
+
+class _CodeOnly(Mapping[str, bytes]):
+ """The code files of *source_map*, with C-family comments and prose blanked.
+
+ Documentation is left out: a README naming a function does not call it.
+ Line breaks are kept so line numbers still hold.
+ """
+
+ def __init__(self, source_map: Mapping[str, bytes]) -> None:
+ self._source = source_map
+ self._paths = [
+ path
+ for path in source_map
+ if REGISTRY.from_extension(PurePosixPath(path).suffix) not in _NON_CODE_LANGUAGES
+ ]
+
+ def __getitem__(self, path: str) -> bytes:
+ blob = self._source[path]
+ return _COMMENT_OR_STRING.sub(_blank_prose, blob) if is_preprocessed(path) else blob
+
+ def __iter__(self) -> Iterator[str]:
+ return iter(self._paths)
+
+ def __len__(self) -> int:
+ return len(self._paths)
+
+
+def _name_lines(blob: bytes, wanted: set[bytes]) -> dict[bytes, list[int]]:
+ """Line numbers of each wanted name in *blob*."""
+ found: dict[bytes, list[int]] = {}
+ for lineno, line in enumerate(blob.split(b"\n"), start=1):
+ for token in IDENTIFIER_RE.findall(line):
+ if token in wanted:
+ found.setdefault(token, []).append(lineno)
+ return found
+
+
+class _UseIndex:
+ """Where the candidate names are written, and where they are declared.
+
+ The repository is scanned once for which files write a name; a file is
+ read line by line only when it also declares that name, to tell its
+ declaration lines apart from its uses.
+ """
+
+ def __init__(
+ self, source_map: Mapping[str, bytes], wanted: set[bytes], declarations: DeclarationSites
+ ) -> None:
+ self._source = _CodeOnly(source_map)
+ self._wanted = wanted
+ self._declarations = declarations
+ self._writers = occurrence_files(self._source, wanted)
+ self._lines: dict[str, dict[bytes, list[int]]] = {}
+
+ def written_outside_declarations(self, finding: DeadCodeFindingData, name: str) -> bool:
+ """Whether *name* is written somewhere that is not a declaration of it."""
+ token = name.encode()
+ sites = [
+ *self._declarations.get(name, ()),
+ (finding.file_path, finding.start_line or 0, finding.end_line or 0),
+ ]
+ for path in self._writers.get(token, ()):
+ spans = [(start, end) for site, start, end in sites if site == path]
+ if not spans or any(
+ not any(start <= line <= end for start, end in spans)
+ for line in self._lines_of(path).get(token, ())
+ ):
+ return True
+ return False
+
+ def _lines_of(self, path: str) -> dict[bytes, list[int]]:
+ if path not in self._lines:
+ self._lines[path] = _name_lines(self._source.get(path, b""), self._wanted)
+ return self._lines[path]
+
+
+def _is_candidate(finding: DeadCodeFindingData) -> bool:
+ """A spanned C/C++ symbol finding."""
+ return (
+ finding.kind in (DeadCodeKind.UNUSED_EXPORT, DeadCodeKind.UNUSED_INTERNAL)
+ and bool(finding.symbol_name)
+ and finding.end_line is not None
+ and is_preprocessed(finding.file_path)
+ )
+
+
+def drop_preprocessed_named_elsewhere(
+ findings: list[DeadCodeFindingData],
+ source_map: Mapping[str, bytes],
+ declarations: DeclarationSites,
+ unread_tokens: frozenset[str] = frozenset(),
+) -> list[DeadCodeFindingData]:
+ """Drop C/C++ symbol findings whose names are written outside a declaration.
+
+ *declarations* lists the declaration sites of the candidate names;
+ *unread_tokens* are the identifiers of files ingestion could not read (a
+ ``.def`` EXPORTS list), any of which is a use. Returns a new list.
+ """
+ candidates = [f for f in findings if _is_candidate(f)]
+ if not candidates or not source_map:
+ return findings
+ names = {id(f): declared_names(f, source_map.get(f.file_path, b"")) for f in candidates}
+ wanted = {n.encode() for group in names.values() for n in group if n.isascii()}
+ uses = _UseIndex(source_map, wanted, declarations)
+ dropped = {
+ id(f)
+ for f in candidates
+ if not unread_tokens.isdisjoint(names[id(f)])
+ or any(uses.written_outside_declarations(f, n) for n in names[id(f)])
+ }
+ return [f for f in findings if id(f) not in dropped]
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 e67312169..678760c04 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
@@ -29,6 +29,8 @@ overrides without static callers, etc.
from __future__ import annotations
+import re
+
# Method names reserved by COM / IUnknown / IDispatch. Case-sensitive —
# Windows COM uses PascalCase universally.
_COM_CONTRACT_METHOD_NAMES: frozenset[str] = frozenset({
@@ -59,6 +61,17 @@ _COM_CONTRACT_METHOD_NAMES: frozenset[str] = frozenset({
# these names in user code via the ``#[implement]`` macro.
_COM_LANGUAGES: frozenset[str] = frozenset({"cpp", "c", "csharp", "rust"})
+#: The macros a C/C++ COM interface method implementation is declared with
+#: (``IFACEMETHODIMP GetTitle(...)``, ``STDMETHODIMP_(ULONG) AddRef()``). The
+#: method fills an interface slot the COM runtime calls through the vtable,
+#: whatever its name.
+_COM_METHOD_MACRO_RE = re.compile(r"\b(?:IFACE|STD)METHOD(?:IMP)?_?\b")
+
+
+def is_com_method_implementation(signature: str | None, language: str | None) -> bool:
+ """Whether a C/C++ signature declares a COM interface method implementation."""
+ return language in _CPP_LANGUAGES and bool(_COM_METHOD_MACRO_RE.search(signature or ""))
+
# Method names reserved by JVM ``Object`` / ``Serializable`` / ``Comparable`` /
# ``Cloneable`` contracts and by language-emitted synthesis (Kotlin data
diff --git a/packages/core/src/repowise/core/ingestion/traverser.py b/packages/core/src/repowise/core/ingestion/traverser.py
index c996eef1e..08a72e4a9 100644
--- a/packages/core/src/repowise/core/ingestion/traverser.py
+++ b/packages/core/src/repowise/core/ingestion/traverser.py
@@ -179,6 +179,9 @@ _MAX_UNKNOWN_LANGUAGE_PATHS = 500
_REFERENCE_BEARING_EXTENSIONS: frozenset[str] = frozenset(
{
".api", # also matches Kotlin's .klib.api
+ ".asm", # assembly that calls or defines C/C++ symbols by name
+ ".def", # a Windows module-definition file's EXPORTS list
+ ".s", # .s and .S, matched lowercased
".properties",
".rst",
".topic",
diff --git a/tests/unit/dead_code/test_cpp_name_uses.py b/tests/unit/dead_code/test_cpp_name_uses.py
new file mode 100644
index 000000000..04ca4c310
--- /dev/null
+++ b/tests/unit/dead_code/test_cpp_name_uses.py
@@ -0,0 +1,243 @@
+"""A C/C++ symbol written outside its own declaration is used.
+
+Shapes taken from dotnet/runtime and PowerToys, where every one of them was
+reported as dead: a typedef tag used through its alias, an enum used through
+its enumerators, a timer callback passed by name, a P/Invoke export named from
+C#, an MSI custom action listed in a ``.def`` file, a private member defined
+in the ``.cpp`` beside its header.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from repowise.core.analysis.dead_code import DeadCodeAnalyzer
+from repowise.core.analysis.dead_code.c_name_uses import (
+ declared_names,
+ drop_preprocessed_named_elsewhere,
+)
+from repowise.core.analysis.dead_code.models import DeadCodeFindingData, DeadCodeKind
+from tests.unit.dead_code._helpers import _build_graph
+
+_UNWINDER = b"""#include "unwinder.h"
+
+typedef struct _ARM64_VFP_STATE
+{
+ struct _ARM64_VFP_STATE *Link; // link to next state entry
+ ULONG Fpcr;
+} ARM64_VFP_STATE, *PARM64_VFP_STATE, KARM64_VFP_STATE, *PKARM64_VFP_STATE;
+
+ULONG64 Offset()
+{
+ return offsetof(KARM64_VFP_STATE, Fpcr);
+}
+"""
+
+_FLAGS = b"""#pragma once
+enum GenerateDumpFlags
+{
+ GenerateDumpFlagsNone = 0x00, // none
+ GenerateDumpFlagsLoggingEnabled = 0x01,
+#if defined(HOST_UNIX)
+ GenerateDumpFlagsCrashReportEnabled = 0x04
+#endif
+};
+"""
+
+
+def _finding(path, name, kind, start, end, finding_kind=DeadCodeKind.UNUSED_EXPORT):
+ return DeadCodeFindingData(
+ kind=finding_kind,
+ file_path=path,
+ symbol_name=name,
+ symbol_kind=kind,
+ confidence=0.6,
+ reason="test",
+ last_commit_at=None,
+ commit_count_90d=0,
+ lines=end - start + 1,
+ evidence=[],
+ safe_to_delete=False,
+ primary_owner=None,
+ age_days=None,
+ start_line=start,
+ end_line=end,
+ )
+
+
+def _kept(findings, source_map, unread=frozenset(), declarations=None):
+ kept = drop_preprocessed_named_elsewhere(findings, source_map, declarations or {}, unread)
+ return {f.symbol_name for f in kept}
+
+
+def test_typedef_declares_tag_and_every_alias():
+ names = declared_names(_finding("unwinder.cpp", "_ARM64_VFP_STATE", "struct", 3, 7), _UNWINDER)
+ assert names == [
+ "_ARM64_VFP_STATE",
+ "ARM64_VFP_STATE",
+ "PARM64_VFP_STATE",
+ "KARM64_VFP_STATE",
+ "PKARM64_VFP_STATE",
+ ]
+
+
+def test_enum_declares_its_enumerators_past_comments_and_directives():
+ names = declared_names(_finding("flags.h", "GenerateDumpFlags", "enum", 2, 9), _FLAGS)
+ assert names == [
+ "GenerateDumpFlags",
+ "GenerateDumpFlagsNone",
+ "GenerateDumpFlagsLoggingEnabled",
+ "GenerateDumpFlagsCrashReportEnabled",
+ ]
+
+
+def test_typedef_tag_used_through_an_alias_is_dropped():
+ findings = [
+ _finding("unwinder.cpp", "_ARM64_VFP_STATE", "struct", 3, 7),
+ _finding("unwinder.cpp", "ARM64_VFP_STATE", "struct", 3, 7),
+ ]
+ assert _kept(findings, {"unwinder.cpp": _UNWINDER}) == set()
+
+
+def test_enum_used_through_an_enumerator_elsewhere_is_dropped():
+ source = {
+ "inc/flags.h": _FLAGS,
+ "dump.cpp": b"int f() { return GenerateDumpFlagsNone; }\n",
+ }
+ assert _kept([_finding("inc/flags.h", "GenerateDumpFlags", "enum", 2, 9)], source) == set()
+
+
+def test_callback_passed_by_name_in_its_own_file_is_dropped():
+ source = {
+ "hook.cpp": (
+ b"void CALLBACK PressedKeyTimerProc(HWND, UINT, UINT_PTR, DWORD)\n{\n}\n"
+ b"void Arm()\n{\n SetTimer(nullptr, 0, 10, PressedKeyTimerProc);\n}\n"
+ )
+ }
+ assert _kept([_finding("hook.cpp", "PressedKeyTimerProc", "function", 1, 3)], source) == set()
+
+
+def test_export_named_by_a_csharp_pinvoke_is_dropped():
+ source = {
+ "native/pal_io.c": b"int32_t SystemNative_FcntlGetIsNonBlocking(intptr_t fd)\n{\n return 0;\n}\n",
+ "Interop.Fcntl.cs": (
+ b'[LibraryImport(Libraries.SystemNative, EntryPoint = '
+ b'"SystemNative_FcntlGetIsNonBlocking")]\n'
+ ),
+ }
+ finding = _finding("native/pal_io.c", "SystemNative_FcntlGetIsNonBlocking", "function", 1, 4)
+ assert _kept([finding], source) == set()
+
+
+def test_name_listed_only_in_an_unread_file_is_dropped():
+ source = {"CustomAction.cpp": b"UINT __stdcall SetBundleInstallLocationCA(MSIHANDLE h)\n{\n}\n"}
+ finding = _finding("CustomAction.cpp", "SetBundleInstallLocationCA", "function", 1, 3)
+ assert _kept([finding], source, frozenset({"SetBundleInstallLocationCA"})) == set()
+
+
+def test_private_member_defined_beside_its_header_is_dropped():
+ source = {
+ "debugger.h": b"class Debugger {\nprivate:\n static DWORD ThreadProcStatic(LPVOID p);\n};\n",
+ "debugger.cpp": b"DWORD Debugger::ThreadProcStatic(LPVOID p) { return 0; }\n",
+ }
+ finding = _finding(
+ "debugger.h", "ThreadProcStatic", "function", 3, 3, DeadCodeKind.UNUSED_INTERNAL
+ )
+ assert _kept([finding], source) == set()
+
+
+def test_name_written_nowhere_else_is_kept():
+ source = {
+ "util.c": b"int unused_helper(void)\n{\n return unused_helper_impl;\n}\n",
+ "main.c": b"int main(void) { return 0; }\n",
+ }
+ assert _kept([_finding("util.c", "unused_helper", "function", 1, 4)], source) == {
+ "unused_helper"
+ }
+
+
+def test_other_languages_are_untouched():
+ source = {"a.py": b"def helper():\n pass\n", "b.py": b"helper()\n"}
+ assert _kept([_finding("a.py", "helper", "function", 1, 2)], source) == {"helper"}
+
+
+def test_analyzer_drops_the_typedef_tag_end_to_end(tmp_path: Path):
+ symbols = [
+ {
+ "name": "_ARM64_VFP_STATE",
+ "kind": "struct",
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 3,
+ "end_line": 7,
+ "language": "cpp",
+ },
+ {
+ "name": "Offset",
+ "kind": "function",
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 9,
+ "end_line": 12,
+ "language": "cpp",
+ },
+ ]
+ graph = _build_graph({"unwinder.cpp": {"language": "cpp", "symbols": symbols}})
+ report = DeadCodeAnalyzer(graph, source_map={"unwinder.cpp": _UNWINDER}).analyze(
+ {"detect_unreachable_files": False, "detect_zombie_packages": False, "min_confidence": 0.0}
+ )
+ assert {f.symbol_name for f in report.findings} == {"Offset"}
+
+
+def test_header_prototype_and_comment_banner_are_not_uses():
+ # ZoomIt's ``ConvertToUnicode`` and powerrename's ``SetRegBoolean``: the
+ # only other mentions are a banner comment and the header prototype.
+ source = {
+ "Helpers.cpp": b"// SetRegBoolean\nvoid SetRegBoolean(bool v)\n{\n}\n",
+ "Helpers.h": b"#pragma once\nvoid SetRegBoolean(bool v);\n",
+ "Other.cpp": b'const char* s = "http://x"; // SetRegBoolean is unused\n',
+ }
+ declarations = {"SetRegBoolean": [("Helpers.h", 2, 2), ("Helpers.cpp", 2, 4)]}
+ finding = _finding("Helpers.cpp", "SetRegBoolean", "function", 2, 4)
+ assert _kept([finding], source, declarations=declarations) == {"SetRegBoolean"}
+
+
+def test_com_interface_method_is_not_reported():
+ symbols = [
+ {
+ "name": "GetTitle",
+ "kind": "function",
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 1,
+ "end_line": 4,
+ "language": "cpp",
+ "signature": "GetTitle(_In_opt_ IShellItemArray* items, PWSTR* name) -> IFACEMETHODIMP",
+ }
+ ]
+ graph = _build_graph({"dllmain.cpp": {"language": "cpp", "symbols": symbols}})
+ report = DeadCodeAnalyzer(graph).analyze(
+ {"detect_unreachable_files": False, "detect_zombie_packages": False, "min_confidence": 0.0}
+ )
+ assert report.findings == []
+
+
+def test_documentation_and_prose_strings_are_not_uses():
+ # aria2's unused ``Supported`` functor: the name is otherwise written only in
+ # an HTTP status string and a changelog.
+ source = {
+ "src/MetalinkEntry.cc": b"namespace {\nclass Supported {\n};\n}\n",
+ "src/HttpServer.cc": b'const char* s = "505 HTTP Version Not Supported";\n',
+ "README.md": b"Supported protocols: HTTP, FTP\n",
+ }
+ finding = _finding("src/MetalinkEntry.cc", "Supported", "class", 2, 3)
+ assert _kept([finding], source) == {"Supported"}
+
+
+def test_one_word_string_is_a_use():
+ # ``GetProcAddress(h, "FreeString")`` names the export it loads.
+ source = {
+ "Wrapper.cpp": b"void FreeString(wchar_t* s)\n{\n}\n",
+ "Loader.cpp": b'auto f = GetProcAddress(h, "FreeString");\n',
+ }
+ assert _kept([_finding("Wrapper.cpp", "FreeString", "function", 1, 3)], source) == set()
diff --git a/tests/unit/ingestion/test_traverser.py b/tests/unit/ingestion/test_traverser.py
index 006392ab0..40b77483b 100644
--- a/tests/unit/ingestion/test_traverser.py
+++ b/tests/unit/ingestion/test_traverser.py
@@ -1185,6 +1185,17 @@ class TestUnknownLanguageFileRecording:
assert [s.path for s in traverser.stats.unknown_language_files] == ["guide.rst"]
assert traverser.stats.unknown_language_files[0].reason == "unknown_language"
+ def test_records_files_that_name_native_symbols(self, tmp_path: Path) -> None:
+ # A .def EXPORTS list and assembly name C/C++ symbols no parsed file does.
+ (tmp_path / "CustomAction.def").write_text("EXPORTS\n SetInstallLocationCA\n")
+ (tmp_path / "barrier.S").write_text("PATCH_LABEL JIT_WriteBarrier_Patch_Label\n")
+ (tmp_path / "helpers.asm").write_text("extern JIT_Helper:proc\n")
+ traverser = FileTraverser(tmp_path)
+ list(traverser.traverse())
+
+ recorded = sorted(s.path for s in traverser.stats.unknown_language_files)
+ assert recorded == ["CustomAction.def", "barrier.S", "helpers.asm"]
+
def test_ignores_formats_that_name_no_code(self, tmp_path: Path) -> None:
# The tail is dominated by these, and a name-matching clamp fed prose
# suppresses findings on coincidence rather than on evidence.