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(cpp): count a function named but never called as a use (#1627)

Raghav Chamadiya547cba26e5f2
diff --git a/packages/core/src/repowise/core/analysis/knowledge_graph.py b/packages/core/src/repowise/core/analysis/knowledge_graph.py
index f3cafb880..0397bd833 100644
--- a/packages/core/src/repowise/core/analysis/knowledge_graph.py
+++ b/packages/core/src/repowise/core/analysis/knowledge_graph.py
@@ -213,7 +213,9 @@ def _slugify(text: str) -> str:
#
# "2": `_EDGE_TYPE_MAP` gained six types and `_curate_entry_points` changed its
# ranking, neither of which moves a node or edge count.
-KG_BUILDER_VERSION = "2"
+# "3": `references` joined the map, so C/C++ dispatch tables and registration
+# macros reach the export instead of being dropped.
+KG_BUILDER_VERSION = "3"
# An unmapped type is dropped from the export entirely (see the
# `if not kg_type: continue` below), which is silent. Six real types used to be
@@ -240,6 +242,7 @@ _EDGE_TYPE_MAP: dict[str, str] = {
"implements": "depends_on",
"method_implements": "depends_on",
"reads": "depends_on",
+ "references": "depends_on",
}
diff --git a/packages/core/src/repowise/core/generation/onboarding/subkinds/key_concepts.py b/packages/core/src/repowise/core/generation/onboarding/subkinds/key_concepts.py
index c9dcf198f..c8b21800c 100644
--- a/packages/core/src/repowise/core/generation/onboarding/subkinds/key_concepts.py
+++ b/packages/core/src/repowise/core/generation/onboarding/subkinds/key_concepts.py
@@ -109,6 +109,10 @@ _RELATION_VERB: dict[str, str] = {
"implements": "implements",
"method_implements": "implements",
"reads": "reads from",
+ # Named rather than called: a dispatch-table entry, a callback field, an
+ # argument to a registration macro. "references" is the honest verb, since
+ # "calls" would claim an invocation this edge never observed.
+ "references": "references",
}
diff --git a/packages/core/src/repowise/core/ingestion/graph/_resolvers.py b/packages/core/src/repowise/core/ingestion/graph/_resolvers.py
index 9d3e442a6..8db2e35d0 100644
--- a/packages/core/src/repowise/core/ingestion/graph/_resolvers.py
+++ b/packages/core/src/repowise/core/ingestion/graph/_resolvers.py
@@ -14,6 +14,13 @@ from ..languages.specs.cpp import INCLUDE_FRAGMENT_EXTENSIONS
log = structlog.get_logger(__name__)
+#: Lowest call-resolution confidence a ``references`` edge may be built from.
+#: Set above the resolver's global-unique tier (0.50), which binds a name to
+#: the only symbol that carries it anywhere in the repo. That tier is a guess
+#: even for a call; for a bare identifier it bound ordinary words to unrelated
+#: files. See ``_add_reference_edges``.
+_MIN_REFERENCE_CONFIDENCE = 0.85
+
class ResolveMixin:
"""Symbol-level edge resolution passes run during ``build()``."""
@@ -535,3 +542,55 @@ class ResolveMixin:
if _phase_done is not None:
_phase_done("graph.calls")
log.info("Call edges resolved", total=total_resolved)
+
+ self._add_reference_edges(resolver)
+
+ def _add_reference_edges(self, resolver: Any) -> None:
+ """Emit ``references`` edges for functions named but never called.
+
+ Shares the ``CallResolver`` built for calls: resolving "which symbol
+ does this name mean" is the same problem and the same three tiers, and
+ building a second index over every parsed file would double that cost
+ for nothing.
+
+ Only free functions produce an edge, never methods. A bare identifier
+ cannot name a member function in C++ — that needs ``&Class::method`` —
+ so a plain name resolving to a method is always a collision rather
+ than a reference, and C++ names its getters exactly like the locals
+ that feed them. Measured on leveldb, admitting methods turned
+ ``value``, ``status``, ``level``, ``key`` and ``offset`` into fifteen
+ edges, every one of them wrong. Every shape the issue reports is a
+ free function, so nothing real is lost.
+
+ A ``calls`` edge already covering the same pair wins and is left alone:
+ it is the stronger claim, and downgrading it here would lose the fact
+ that the function is genuinely invoked.
+
+ The confidence floor drops the resolver's last tier, which fires when a
+ name happens to be globally unique. That is already a guess for a call;
+ for a bare identifier it reached across the repo to bind common words
+ like ``output`` to an unrelated file's function. A real dispatch table
+ names something in its own file or in a header it includes, which the
+ earlier tiers cover.
+ """
+ total = 0
+ for path, parsed in self._parsed_files.items():
+ if not parsed.references:
+ continue
+ for rc in resolver.resolve_file(path, parsed.references):
+ if rc.confidence < _MIN_REFERENCE_CONFIDENCE:
+ continue
+ if rc.caller_id not in self._graph or rc.callee_id not in self._graph:
+ continue
+ if self._graph.nodes[rc.callee_id].get("kind") != "function":
+ continue
+ if self._graph.has_edge(rc.caller_id, rc.callee_id):
+ continue
+ self._graph.add_edge(
+ rc.caller_id,
+ rc.callee_id,
+ edge_type="references",
+ confidence=rc.confidence,
+ )
+ total += 1
+ log.info("Reference edges resolved", total=total)
diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.py
index 01f24e38f..361de9381 100644
--- a/packages/core/src/repowise/core/ingestion/models.py
+++ b/packages/core/src/repowise/core/ingestion/models.py
@@ -301,6 +301,13 @@ EdgeType = Literal[
# from ``imports`` so analyses can weight it lower and so the
# persistence layer can surface provenance for these edges.
"type_use",
+ # A function named without being called: a dispatch-table entry, a
+ # callback field, an argument to a registration macro (currently C/C++;
+ # see the ``@reference.name`` captures). Symbol → symbol, and deliberately
+ # not ``calls`` — nothing here proves the function is ever invoked, only
+ # that something holds a handle to it, which is enough to make deleting it
+ # unsafe.
+ "references",
]
# Runtime mirror of the Literal, for the places that must test membership
@@ -390,6 +397,10 @@ SYMBOL_USE_EDGE_TYPES: frozenset[str] = frozenset(
"implements",
"method_implements",
"reads",
+ # Naming a function is using it. A handler sitting in a dispatch table
+ # is never called anywhere a parser can see, and treating that as "no
+ # use" reported entire registration layers as safe to delete (#1602).
+ "references",
}
)
@@ -461,6 +472,12 @@ class ParsedFile:
# Python only; lets the dead-code unused-export pass rescue symbols whose
# only use is intra-module. See ``python_local_refs``.
local_refs: frozenset[str] = field(default_factory=frozenset)
+ # C/C++ sites that name a function without calling it: a dispatch table
+ # entry, a callback field, an argument to a registration macro. Reuses
+ # ``CallSite`` because resolving one is the identical problem — a name, the
+ # symbol enclosing it, and a line — and it lets these ride the same
+ # resolution tiers. They become ``references`` edges, not ``calls``.
+ references: list[CallSite] = field(default_factory=list)
def compute_content_hash(source: bytes) -> str:
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index 0c5e52219..886a21d9b 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -106,6 +106,11 @@ _MODULE_ANCHORED_NODE_TYPES = frozenset({"assignment", "variable_declarator"})
# a TS buffer at identical offsets, so every TS/JS code path applies verbatim.
_TS_JS_LANGUAGES = ("typescript", "javascript", "svelte", "vue")
+# Languages whose query defines the ``@reference.*`` captures. Every other
+# language would only scan the whole match list to find nothing, so the check
+# is here rather than inside ``_extract_references``.
+_REFERENCE_LANGUAGES = ("cpp", "c")
+
@cache
def _load_compiled_query(lang: str, grammar_tag: str | None = None) -> object | None:
@@ -422,6 +427,11 @@ class ASTParser:
# tsx.scm turns ``<Component />`` into a call for React. Returns [] for
# every non-SFC language.
calls.extend(component_call_sites(lang, original_source, symbols))
+ references = (
+ self._extract_references(matches, file_info, src, symbols)
+ if lang in _REFERENCE_LANGUAGES
+ else []
+ )
heritage = extract_heritage(matches, config, file_info, src)
exports = self._derive_exports(symbols, config, src)
docstring = extract_module_docstring(root, src, lang)
@@ -458,6 +468,7 @@ class ASTParser:
content_hash=content_hash,
type_refs=type_refs,
local_refs=local_refs,
+ references=references,
)
# ------------------------------------------------------------------
@@ -1121,6 +1132,94 @@ class ASTParser:
return calls
+ def _extract_references(
+ self,
+ matches: list[dict],
+ file_info: FileInfo,
+ src: str,
+ symbols: list[Symbol],
+ ) -> list[CallSite]:
+ """Extract sites that name a function without calling it.
+
+ Three C/C++ shapes carry a function by name and never call it where a
+ parser can see: a dispatch-table entry, a callback field, and an
+ argument to a registration macro. Each leaves the named function with
+ no inbound edge, which read as a ``safe_to_delete`` unused export and
+ took out whole handler and interop layers (#1602).
+
+ Self-gating on the reference captures, so a language whose query
+ defines none produces nothing and pays two dict lookups. Two guards
+ keep these broad syntactic positions from claiming ordinary code:
+
+ * A macro argument requires a SCREAMING_CASE callee and must be that
+ macro's only argument. Uppercase alone is not enough: assertion
+ macros are spelled the same way and take values, so ``EXPECT_EQ(
+ capacity, 100)`` bound a local to whatever free function shared its
+ name. Registering something registers one thing, which separates
+ ``BENCHMARK(BM_Foo)`` from ``TEST(SuiteName, TestName)``.
+ * A table entry must sit outside any function body. A dispatch table is
+ a file-, namespace- or class-scope aggregate; the same braces inside
+ a function are a constructor member-init or a local aggregate, where
+ ``{data, size}`` names parameters. Measured on fmt, admitting those
+ turned ``data``, ``size``, ``begin``, ``end``, ``capacity`` and
+ ``buffer`` into edges, every one of them wrong.
+
+ Whether the name denotes a function at all is settled later, at
+ resolution, where the symbol kind is known.
+ """
+ from .language_data import get_builtin_calls
+
+ builtins = get_builtin_calls(file_info.language)
+
+ symbol_ranges = sorted(
+ [(s.start_line, s.end_line, s.id) for s in symbols],
+ key=lambda t: (t[0], -t[1]),
+ )
+ callable_ids = {s.id for s in symbols if s.kind in ("function", "method")}
+
+ references: list[CallSite] = []
+ seen: set[tuple[int, str]] = set()
+
+ for capture_dict in matches:
+ plain_nodes = capture_dict.get("reference.name", [])
+ table_nodes = capture_dict.get("reference.table", [])
+ if not plain_nodes and not table_nodes:
+ continue
+
+ via_nodes = capture_dict.get("reference.via", [])
+ if via_nodes:
+ via = _node_text(via_nodes[0], src).strip()
+ if not via or not via.isupper():
+ continue
+ arg_list = plain_nodes[0].parent if plain_nodes else None
+ if arg_list is None or len(arg_list.named_children) != 1:
+ continue
+
+ candidates = [(node, False) for node in plain_nodes]
+ candidates += [(node, True) for node in table_nodes]
+ for name_node, is_table in candidates:
+ name = _node_text(name_node, src).strip()
+ if not name or name in builtins:
+ continue
+ line = name_node.start_point[0] + 1
+ enclosing = _find_enclosing_symbol(line, symbol_ranges)
+ if is_table and enclosing in callable_ids:
+ continue
+ if (line, name) in seen:
+ continue
+ seen.add((line, name))
+ references.append(
+ CallSite(
+ target_name=name,
+ receiver_name=None,
+ caller_symbol_id=enclosing,
+ line=line,
+ argument_count=None,
+ )
+ )
+
+ return references
+
# ------------------------------------------------------------------
# Export derivation
# ------------------------------------------------------------------
diff --git a/packages/core/src/repowise/core/ingestion/queries/c.scm b/packages/core/src/repowise/core/ingestion/queries/c.scm
index f598f2099..f0e857606 100644
--- a/packages/core/src/repowise/core/ingestion/queries/c.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/c.scm
@@ -120,3 +120,41 @@
; Function return type: JSON_Value * json_parse(...)
(function_definition
type: (_) @param.type)
+
+; ---------------------------------------------------------------------------
+; Bare references — drive symbol-level ``references`` edges
+; ---------------------------------------------------------------------------
+; The C half of #1602. Naming a function without calling it is a use that no
+; call pattern above can see, and C reaches for it constantly: a dispatch
+; table of handlers, a ``.callback =`` designated initialiser, a registration
+; macro. The referenced function otherwise carries no inbound edge and reads
+; as a ``safe_to_delete`` unused export. The parser drops any name that does
+; not resolve to a function, so a same-named local cannot mint an edge.
+
+; Dispatch table: struct cmd cmds[] = { {"add", do_add} };
+; Captured under its own name because the parser additionally requires a table
+; to sit at file scope: inside a function body the same shape is a local
+; aggregate whose elements are parameters, not functions.
+(initializer_list
+ (identifier) @reference.table)
+
+; Designated initialiser: static struct ops o = { .write = my_write };
+(initializer_pair
+ value: (identifier) @reference.name)
+
+; Callback field assignment: handle->on_close = on_close_cb;
+; Restricted to a member on the left: a plain ``x = y`` is overwhelmingly
+; local bookkeeping, and matching it manufactured an edge wherever a local
+; happened to share a function's name.
+(assignment_expression
+ left: (field_expression)
+ right: (identifier) @reference.name)
+
+; Registration macro: REGISTER_CMD(do_add);
+; ``@reference.via`` carries the macro name so the parser can require the
+; SCREAMING_CASE convention, without which this captures every identifier
+; argument of every ordinary call.
+(call_expression
+ function: (identifier) @reference.via
+ arguments: (argument_list
+ (identifier) @reference.name))
diff --git a/packages/core/src/repowise/core/ingestion/queries/cpp.scm b/packages/core/src/repowise/core/ingestion/queries/cpp.scm
index 74a1bd733..a7cf0fcf1 100644
--- a/packages/core/src/repowise/core/ingestion/queries/cpp.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/cpp.scm
@@ -240,3 +240,49 @@
(template_argument_list
(type_descriptor
type: (_) @param.type))
+
+; ---------------------------------------------------------------------------
+; Bare references — drive symbol-level ``references`` edges
+; ---------------------------------------------------------------------------
+; Naming a function without calling it is a use, and none of the call
+; patterns above can see it: a dispatch table, a callback field and a
+; registration macro all mention the function as a plain identifier. The
+; referenced function then carries no inbound edge and reads as a
+; ``safe_to_delete`` unused export, which took out whole subsystems of
+; handlers and interop shims (#1602).
+;
+; Only the identifier forms are captured, so ``NodeType::Add`` in a table
+; (a ``qualified_identifier``) filters itself out. The parser drops any name
+; that does not resolve to a function or method, which is what keeps a
+; same-named local variable from minting an edge.
+
+; Dispatch table: Entry g_table[] = { {"a", HandleAlpha} };
+; The query is recursive, so nested initialiser rows match too. Captured under
+; its own name because the parser additionally requires a table to sit at file
+; / namespace / class scope: inside a function body the same shape is a
+; constructor member-init or a local aggregate, where ``{data, size}`` names
+; parameters rather than functions.
+(initializer_list
+ (identifier) @reference.table)
+
+; Designated initialiser: static Ops o = { .write = MyWrite };
+(initializer_pair
+ value: (identifier) @reference.name)
+
+; Callback field assignment: tool.Handler = Handle_SceneSummary;
+; Restricted to a member on the left. A plain ``x = y`` is overwhelmingly
+; local bookkeeping, and C++ getters are named exactly like the locals that
+; feed them (``offset_ = offset`` beside an ``offset()`` accessor), so the
+; unrestricted form manufactured a reference edge for half of leveldb.
+(assignment_expression
+ left: (field_expression)
+ right: (identifier) @reference.name)
+
+; Registration macro: REGISTER_HOOK(OnFrameStart);
+; ``@reference.via`` carries the macro name so the parser can require the
+; SCREAMING_CASE convention. Without that guard this would capture every
+; identifier argument of every ordinary call in the codebase.
+(call_expression
+ function: (identifier) @reference.via
+ arguments: (argument_list
+ (identifier) @reference.name))
diff --git a/packages/server/src/repowise/server/services/c4_builder/labels.py b/packages/server/src/repowise/server/services/c4_builder/labels.py
index 0121c385b..8cf2e839d 100644
--- a/packages/server/src/repowise/server/services/c4_builder/labels.py
+++ b/packages/server/src/repowise/server/services/c4_builder/labels.py
@@ -43,6 +43,10 @@ _EDGE_VERB: dict[str, str] = {
"reads": "uses",
# A type reference without an import: named, but not imported.
"type_use": "references",
+ # A function named without being called: a dispatch-table entry, a callback
+ # field, an argument to a registration macro. Same verb as ``type_use`` for
+ # the same reason — something holds a handle to it, nothing invokes it.
+ "references": "references",
# Containment. Only reachable when the view includes symbol nodes.
"defines": "contains",
"has_method": "contains",
diff --git a/tests/unit/analysis/test_kg_skip_logic.py b/tests/unit/analysis/test_kg_skip_logic.py
index 42d4affb9..29135d28e 100644
--- a/tests/unit/analysis/test_kg_skip_logic.py
+++ b/tests/unit/analysis/test_kg_skip_logic.py
@@ -210,7 +210,7 @@ class TestFingerprintDeterminism:
one: whoever bumps the constant updates this line and sees, in the
diff, that they are asking every existing store to re-curate.
"""
- assert knowledge_graph.KG_BUILDER_VERSION == "2"
+ assert knowledge_graph.KG_BUILDER_VERSION == "3"
# ---------------------------------------------------------------------------
diff --git a/tests/unit/ingestion/test_cpp_reference_edges.py b/tests/unit/ingestion/test_cpp_reference_edges.py
new file mode 100644
index 000000000..2a20f9e45
--- /dev/null
+++ b/tests/unit/ingestion/test_cpp_reference_edges.py
@@ -0,0 +1,172 @@
+"""C/C++ functions named without being called (#1602).
+
+A dispatch table, a callback field and a registration macro all mention a
+function as a plain identifier. None of them is a call expression, so the
+named function carried no inbound edge and read as a ``safe_to_delete``
+unused export, which swept up whole handler and interop layers.
+
+The precision half matters as much as the recall half: the captures are broad
+syntactic positions, and C++ names its getters exactly like the locals that
+feed them, so the tests below pin what must *not* produce an edge.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder
+
+
+def _build(repo: Path):
+ traverser = FileTraverser(repo)
+ parser = ASTParser()
+ builder = GraphBuilder(repo_path=repo)
+ for fi in traverser.traverse():
+ builder.add_file(parser.parse_file(fi, Path(fi.abs_path).read_bytes()))
+ return builder.build()
+
+
+def _referrers_of(graph, symbol_id: str) -> set[str]:
+ if not graph.has_node(symbol_id):
+ return set()
+ return {
+ pred
+ for pred in graph.predecessors(symbol_id)
+ if graph[pred][symbol_id].get("edge_type") == "references"
+ }
+
+
+def _reference_edges(graph) -> list[tuple[str, str]]:
+ return [(u, v) for u, v, d in graph.edges(data=True) if d.get("edge_type") == "references"]
+
+
+class TestDispatchTable:
+ def test_function_pointer_in_table_is_a_reference(self, tmp_path: Path) -> None:
+ (tmp_path / "registry.cpp").write_text(
+ "struct Entry { const char* name; void (*fn)(); };\n"
+ "void HandleAlpha() {}\n"
+ "void HandleBeta() {}\n"
+ 'Entry g_table[] = { {"a", HandleAlpha}, {"b", HandleBeta} };\n'
+ )
+ graph = _build(tmp_path)
+ assert _referrers_of(graph, "registry.cpp::HandleAlpha")
+ assert _referrers_of(graph, "registry.cpp::HandleBeta")
+
+ def test_nested_initialiser_row(self, tmp_path: Path) -> None:
+ (tmp_path / "nodes.cpp").write_text(
+ "void InitAddNode() {}\n"
+ 'struct Init { int type; struct { void (*fn)(); const char* cat; } v; };\n'
+ 'Init g_inits[] = { { 1, { InitAddNode, "math" } } };\n'
+ )
+ graph = _build(tmp_path)
+ assert _referrers_of(graph, "nodes.cpp::InitAddNode")
+
+ def test_designated_initialiser(self, tmp_path: Path) -> None:
+ (tmp_path / "ops.c").write_text(
+ "int my_write(void) { return 0; }\n"
+ "struct ops { int (*write)(void); };\n"
+ "static struct ops g_ops = { .write = my_write };\n"
+ )
+ graph = _build(tmp_path)
+ assert _referrers_of(graph, "ops.c::my_write")
+
+
+class TestRegistrationMacro:
+ def test_screaming_case_macro_argument_is_a_reference(self, tmp_path: Path) -> None:
+ (tmp_path / "hooks.cpp").write_text(
+ "#define REGISTER_HOOK(fn) RegisterHook(#fn, fn)\n"
+ "void RegisterHook(const char* n, void (*f)());\n"
+ "void OnFrameStart() {}\n"
+ "void InstallHooks() { REGISTER_HOOK(OnFrameStart); }\n"
+ )
+ graph = _build(tmp_path)
+ assert _referrers_of(graph, "hooks.cpp::OnFrameStart") == {"hooks.cpp::InstallHooks"}
+
+ def test_multi_argument_macro_is_not_a_registration(self, tmp_path: Path) -> None:
+ # gtest spells its assertions in SCREAMING_CASE too, and they take
+ # values. Registering something registers one thing.
+ (tmp_path / "t.cpp").write_text(
+ "int capacity() { return 1; }\n"
+ "void body() { int capacity = 2; EXPECT_EQ(capacity, 2); }\n"
+ )
+ graph = _build(tmp_path)
+ assert _referrers_of(graph, "t.cpp::capacity") == set()
+
+ def test_lowercase_callee_argument_is_not_a_reference(self, tmp_path: Path) -> None:
+ # Without the SCREAMING_CASE guard this would claim every identifier
+ # argument of every ordinary call in the codebase.
+ (tmp_path / "plain.cpp").write_text(
+ "void helper() {}\n"
+ "void compute(int v);\n"
+ "void run() { int helper = 1; compute(helper); }\n"
+ )
+ graph = _build(tmp_path)
+ assert _referrers_of(graph, "plain.cpp::helper") == set()
+
+
+class TestPrecision:
+ def test_plain_local_assignment_is_not_a_reference(self, tmp_path: Path) -> None:
+ # ``offset_ = offset`` beside an ``offset()`` accessor is the shape
+ # that made half of leveldb look cross-referenced.
+ (tmp_path / "handle.cpp").write_text(
+ "void offset() {}\n"
+ "void store(int v) { int offset_ = 0; int offset = v; offset_ = offset; }\n"
+ )
+ graph = _build(tmp_path)
+ assert _referrers_of(graph, "handle.cpp::offset") == set()
+
+ def test_local_aggregate_colliding_with_a_free_function(self, tmp_path: Path) -> None:
+ # ``count`` and ``size`` are both ordinary locals and plausible free
+ # function names. Inside a function body the braces are a local
+ # aggregate, never a dispatch table.
+ (tmp_path / "agg.cpp").write_text(
+ "int count() { return 1; }\n"
+ "int size() { return 2; }\n"
+ "void body() { int count = 1, size = 2; int arr[] = {count, size}; (void)arr; }\n"
+ )
+ graph = _build(tmp_path)
+ assert _referrers_of(graph, "agg.cpp::count") == set()
+ assert _referrers_of(graph, "agg.cpp::size") == set()
+
+ def test_method_target_is_never_referenced_by_bare_name(self, tmp_path: Path) -> None:
+ # A bare identifier cannot name a member function in C++; it needs
+ # ``&Class::method``. A plain name matching a method is a collision.
+ (tmp_path / "m.cpp").write_text(
+ "struct Iter { int value() { return 1; } };\n"
+ "struct Cfg { int value; };\n"
+ "void use(Cfg& c, int value) { c.value = value; }\n"
+ )
+ graph = _build(tmp_path)
+ assert _referrers_of(graph, "m.cpp::Iter::value") == set()
+
+ def test_enum_value_in_a_table_is_not_a_reference(self, tmp_path: Path) -> None:
+ # ``NodeType::Add`` parses as a qualified_identifier, so the bare
+ # identifier capture never sees it.
+ (tmp_path / "e.cpp").write_text(
+ "namespace NodeType { enum E { Add }; }\n"
+ "int g_t[] = { NodeType::Add };\n"
+ )
+ graph = _build(tmp_path)
+ assert not [e for e in _reference_edges(graph) if e[1].endswith("::Add")]
+
+ def test_other_languages_emit_no_reference_edges(self, tmp_path: Path) -> None:
+ # Only the C/C++ queries define ``@reference.name``; everything else
+ # pays a dict lookup and produces nothing.
+ (tmp_path / "mod.py").write_text("def handler():\n pass\n\nTABLE = [handler]\n")
+ graph = _build(tmp_path)
+ assert _reference_edges(graph) == []
+
+
+class TestDeadCodeEffect:
+ def test_referenced_handler_is_not_an_unused_export(self, tmp_path: Path) -> None:
+ from repowise.core.analysis.dead_code import DeadCodeAnalyzer
+
+ (tmp_path / "registry.cpp").write_text(
+ "struct Entry { const char* name; void (*fn)(); };\n"
+ "void HandleAlpha() {}\n"
+ 'Entry g_table[] = { {"a", HandleAlpha} };\n'
+ )
+ graph = _build(tmp_path)
+ report = DeadCodeAnalyzer(graph).analyze()
+ flagged = {f.symbol_name for f in report.findings if f.kind == "unused_export"}
+ assert "HandleAlpha" not in flagged