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): a static function in another translation unit is not a call target (#2770)

Raghav Chamadiyabb90e6b5b3b4
diff --git a/packages/core/src/repowise/core/ingestion/call_language_strategies.py b/packages/core/src/repowise/core/ingestion/call_language_strategies.py
index 3c0001c04..8abbaa04a 100644
--- a/packages/core/src/repowise/core/ingestion/call_language_strategies.py
+++ b/packages/core/src/repowise/core/ingestion/call_language_strategies.py
@@ -241,7 +241,11 @@ class LanguageStrategiesMixin:
for sibling in siblings:
syms = self._file_symbols.get(sibling, {})
sym_id = syms.get(call.target_name)
- if sym_id is not None and sym_id != caller_id:
+ if (
+ sym_id is not None
+ and sym_id != caller_id
+ and self._reachable_by_name(file_path, sym_id)
+ ):
return ResolvedCall(caller_id, sym_id, 0.85, call.line, "same_target")
return None
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
index 1b7c99541..5a430f737 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -55,6 +55,7 @@ from .models import (
symbol_id_language,
)
from .resolved_call import ResolvedCall
+from .resolvers.cpp import _SOURCE_TU_EXTS
from .return_types import declared_return_type, normalize_return_type, signature_parameter_count
from .type_names import (
csharp_extension_receiver,
@@ -177,6 +178,21 @@ def _renames_on_the_way(binding: NamedBinding | None, name: str) -> bool:
return binding is not None and (binding.exported_name or name) != name
+def _has_internal_linkage(path: str, sym: Symbol) -> bool:
+ """Is *sym* a C/C++ free symbol only its own translation unit can name?
+
+ The parser records ``static`` and anonymous-namespace linkage as
+ ``private``. A header's copy is compiled into every file that includes it,
+ so only a source file keeps the symbol to itself.
+ """
+ return (
+ sym.language in ("c", "cpp")
+ and sym.parent_name is None
+ and sym.visibility == "private"
+ and path.lower().endswith(_SOURCE_TU_EXTS)
+ )
+
+
def _same_translation_unit(decl_file: str, def_file: str) -> bool:
"""Are these two paths the same C++ translation unit?
@@ -272,6 +288,8 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
# Held as an id set rather than a full id->kind map: it is the only
# kind question asked of it and the set is small.
self._non_callable_ids: set[str] = set()
+ # C/C++ symbols with internal linkage; see ``_reachable_by_name``.
+ self._tu_local_ids: set[str] = set()
self._property_accessor_ids: set[str] = set()
# C/C++ forward declaration → the definition it declares. Populated by
@@ -498,7 +516,7 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
if extended is not None:
extensions[(extended, sym.name)].add((path, sym.id))
- self._index_globally(sym)
+ self._index_globally(path, sym)
self._file_symbols[path] = file_syms
self._file_methods[path] = file_methods
@@ -512,7 +530,9 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
return None
return extended if extended in self._csharp_type_names else None
- def _index_globally(self, sym: Symbol) -> None:
+ def _index_globally(self, path: str, sym: Symbol) -> None:
+ if _has_internal_linkage(path, sym):
+ self._tu_local_ids.add(sym.id)
if sym.kind in _NON_CALLABLE_KINDS:
self._non_callable_ids.add(sym.id)
if _is_property_accessor(sym):
@@ -1094,9 +1114,14 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
"""Tier 3 and what follows it: answers not grounded in this file or its imports."""
target_name = call.target_name
# Tier 3: global unique match, only within the same language.
- # Uniqueness is judged on the unfiltered list on purpose: filtering data
- # members out first would re-uniquify a name a field and a method share.
- candidates = self._global_symbols.get(target_name, [])
+ # Uniqueness is judged before filtering data members, on purpose: filtering
+ # them out first would re-uniquify a name a field and a method share. A
+ # symbol the caller cannot name at all is no rival, so that one is dropped.
+ candidates = [
+ sym_id
+ for sym_id in self._global_symbols.get(target_name, ())
+ if self._reachable_by_name(file_path, sym_id)
+ ]
if len(candidates) == 1 and candidates[0] != caller_id:
return self._global_unique_match(
file_path, call, caller_id, target_name, candidates[0]
@@ -1117,6 +1142,16 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):
return None
return self._global_unique_match(file_path, call, caller_id, target_name, only)
+ def _reachable_by_name(self, file_path: str, sym_id: str) -> bool:
+ """Can a bare name in *file_path* reach *sym_id* with no include in between?
+
+ Not when *sym_id* has internal linkage in another translation unit: a
+ ``static`` function in one .c file cannot be linked from any other. The
+ include-grounded tiers need no check, since an included file is part of
+ the includer's translation unit.
+ """
+ return sym_id not in self._tu_local_ids or self._symbol_paths_by_id.get(sym_id) == file_path
+
def _implicit_inherited_call(
self,
file_path: str,
diff --git a/packages/core/src/repowise/core/ingestion/extractors/visibility.py b/packages/core/src/repowise/core/ingestion/extractors/visibility.py
index 4d769f8f2..d5bf2fd1d 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/visibility.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/visibility.py
@@ -566,6 +566,16 @@ def _has_export_marker(def_node: Node, src: str) -> bool:
return False
+def _in_anonymous_namespace(def_node: Node) -> bool:
+ """Return True if an unnamed ``namespace { ... }`` encloses the def."""
+ ancestor = def_node.parent
+ while ancestor is not None:
+ if ancestor.type == "namespace_definition" and ancestor.child_by_field_name("name") is None:
+ return True
+ ancestor = ancestor.parent
+ return False
+
+
def _has_file_scope_static(def_node: Node, src: str) -> bool:
"""Return True if a ``static`` storage-class specifier appears in the leading declarators."""
for child in def_node.children[:4]:
@@ -591,7 +601,8 @@ def refine_cpp_visibility(def_node: Node, current_visibility: str, src: str) ->
``private`` (the C++ class default) — ``struct`` defaults to
``public``.
* Free function at namespace / file scope with ``static`` storage
- class → ``private`` (translation-unit local; not importable).
+ class, or anything in an anonymous namespace → ``private``
+ (translation-unit local; not importable).
* ``__declspec(dllexport)`` or ``__attribute__((visibility("default")))``
→ forces ``public`` and sets ``is_exported = True`` so a future
"exported entry point" check can whitelist it.
@@ -610,8 +621,9 @@ def refine_cpp_visibility(def_node: Node, current_visibility: str, src: str) ->
# No access specifier — use the enclosing aggregate's default.
return _enclosing_class_default_access(def_node), False
- # 3. File-scope ``static`` is translation-unit local.
- if _has_file_scope_static(def_node, src):
+ # 3. File-scope ``static`` and an anonymous namespace are both internal
+ # linkage: translation-unit local.
+ if _has_file_scope_static(def_node, src) or _in_anonymous_namespace(def_node):
return "private", False
return current_visibility, False
diff --git a/tests/unit/ingestion/test_cpp_extractors.py b/tests/unit/ingestion/test_cpp_extractors.py
index 8ce2e5ee1..7ba64de58 100644
--- a/tests/unit/ingestion/test_cpp_extractors.py
+++ b/tests/unit/ingestion/test_cpp_extractors.py
@@ -72,6 +72,15 @@ namespace ns {
def test_file_scope_static_function_is_private(self, parser: ASTParser) -> None:
src = b"""\
static int Helper(int x) { return x; }
+"""
+ result = parser.parse_file(_file(), src)
+ sym = next(s for s in result.symbols if s.name == "Helper")
+ assert sym.visibility == "private"
+
+ def test_anonymous_namespace_function_is_private(self, parser: ASTParser) -> None:
+ src = b"""namespace {
+ int Helper(int x) { return x; }
+}
"""
result = parser.parse_file(_file(), src)
sym = next(s for s in result.symbols if s.name == "Helper")
diff --git a/tests/unit/ingestion/test_cpp_internal_linkage.py b/tests/unit/ingestion/test_cpp_internal_linkage.py
new file mode 100644
index 000000000..d10bd03f4
--- /dev/null
+++ b/tests/unit/ingestion/test_cpp_internal_linkage.py
@@ -0,0 +1,74 @@
+"""A C/C++ symbol with internal linkage is only callable from its own file.
+
+A ``static`` function, or one in an anonymous namespace, cannot be linked from
+another translation unit, so a bare call elsewhere must not bind to it even
+when its name is unique in the repository.
+"""
+
+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 _callees_of(graph, symbol_id: str) -> set[str]:
+ return {
+ succ
+ for succ in graph.successors(symbol_id)
+ if graph[symbol_id][succ].get("edge_type") == "calls"
+ }
+
+
+def test_static_function_in_another_c_file_is_not_bound(tmp_path: Path) -> None:
+ (tmp_path / "bench.c").write_text("static int make_client(void) { return 1; }\n")
+ (tmp_path / "server.c").write_text("int start(void) { return make_client(); }\n")
+ graph = _build(tmp_path)
+ assert _callees_of(graph, "server.c::start") == set()
+
+
+def test_static_function_does_not_hide_the_linkable_one(tmp_path: Path) -> None:
+ (tmp_path / "bench.c").write_text("static int make_client(void) { return 1; }\n")
+ (tmp_path / "net.c").write_text("int make_client(void) { return 2; }\n")
+ (tmp_path / "server.c").write_text("int start(void) { return make_client(); }\n")
+ graph = _build(tmp_path)
+ assert _callees_of(graph, "server.c::start") == {"net.c::make_client"}
+
+
+def test_anonymous_namespace_function_in_another_file_is_not_bound(tmp_path: Path) -> None:
+ (tmp_path / "a.cpp").write_text("namespace { int Helper() { return 1; } }\n")
+ (tmp_path / "b.cpp").write_text("int Run() { return Helper(); }\n")
+ graph = _build(tmp_path)
+ assert _callees_of(graph, "b.cpp::Run") == set()
+
+
+def test_static_function_in_the_same_file_still_binds(tmp_path: Path) -> None:
+ (tmp_path / "util.c").write_text(
+ "static int helper(void) { return 1; }\nint run(void) { return helper(); }\n"
+ )
+ graph = _build(tmp_path)
+ assert _callees_of(graph, "util.c::run") == {"util.c::helper"}
+
+
+def test_non_static_function_in_another_file_still_binds(tmp_path: Path) -> None:
+ (tmp_path / "util.c").write_text("int helper(void) { return 1; }\n")
+ (tmp_path / "app.c").write_text("int run(void) { return helper(); }\n")
+ graph = _build(tmp_path)
+ assert _callees_of(graph, "app.c::run") == {"util.c::helper"}
+
+
+def test_static_inline_in_a_header_still_binds(tmp_path: Path) -> None:
+ # A header's static copy is compiled into every includer.
+ (tmp_path / "atomic.hpp").write_text("static inline int load(int *p) { return *p; }\n")
+ (tmp_path / "app.cpp").write_text("int run(int *p) { return load(p); }\n")
+ graph = _build(tmp_path)
+ assert _callees_of(graph, "app.cpp::run") == {"atomic.hpp::load"}