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(graph): pair a C/C++ prototype with its definition member by member (#4827)

Swati Ahujaebbfea12dd19
diff --git a/packages/core/src/repowise/core/ingestion/call_overload_selection.py b/packages/core/src/repowise/core/ingestion/call_overload_selection.py
index 7fc396095..2f63d13ef 100644
--- a/packages/core/src/repowise/core/ingestion/call_overload_selection.py
+++ b/packages/core/src/repowise/core/ingestion/call_overload_selection.py
@@ -27,6 +27,10 @@ from .symbol_identity import (
split_symbol_id,
)
+# Languages whose prototypes and bodies pair member by member, and whose
+# ``static`` (or anonymous-namespace) symbols no other translation unit sees.
+C_LINKAGE_LANGUAGES = ("c", "cpp", "objectivec")
+
def _overload_phase(admitted: tuple[int, int | None], argument_count: int) -> int | None:
"""The first phase in which a member with *admitted* arguments takes the call.
@@ -524,18 +528,19 @@ class OverloadSelectionMixin:
def _pair_overload_members(self) -> None:
"""Pair each member of a declared overload set with its definition.
- ``_link_declarations`` pairs a declared set with a defined one by their
- representatives; the members pair here by parameter count and types
- (``pair_overloads``), so each declaration records its definition, even
- when the source defines one plain-id member. The definition also admits
- the defaults its declaration writes: C++ writes them on the header
- declaration only, so ``f(int, int)`` alone would refuse the one-argument
- call ``f(int, int = 0)`` admits.
+ Outside C, C++ and Objective-C, ``_link_declarations`` pairs a declared
+ set with a defined one by their representatives; the members pair here
+ by parameter count and types (``pair_overloads``), so each declaration
+ records its definition, even when the source defines one plain-id
+ member. The C family pairs member by member there already. Either way
+ the definition also admits the defaults its declaration writes: C++
+ writes them on the header declaration only, so ``f(int, int)`` alone
+ would refuse the one-argument call ``f(int, int = 0)`` admits.
"""
symbols = self._symbols_by_id
for declared, defined in list(self._decl_to_def.items()):
declared_members = self._overload_members.get(declared, ())
- if not declared_members:
+ if not declared_members or symbols[declared].language in C_LINKAGE_LANGUAGES:
continue
defined_members = self._overload_members.get(defined, ())
pairs = pair_overloads(
@@ -550,6 +555,39 @@ class OverloadSelectionMixin:
del self._decl_to_def[declared]
if defined_members:
self._carry_declared_floors(defined, declared_members, pairs)
+ self._carry_member_floors()
+
+ def _carry_member_floors(self) -> None:
+ """Carry each C-family declared set's defaults onto the sets it pairs with.
+
+ Walked by set rather than by link, so a set whose first member has no
+ definition still lends its other members' defaults.
+ """
+ for rep, declared_members in list(self._overload_members.items()):
+ if self._symbols_by_id[rep].language not in C_LINKAGE_LANGUAGES:
+ continue
+ by_defined: dict[str, dict[str, str]] = defaultdict(dict)
+ for member, _ in declared_members:
+ target = self._decl_to_def.get(member)
+ if target is not None:
+ by_defined[self._overload_rep.get(target, target)][member] = target
+ for defined, pairs in by_defined.items():
+ if defined in self._overload_members:
+ self._carry_declared_floors(defined, declared_members, pairs)
+
+ def _paired_member(self, decl: Symbol, decl_index: str, members: list[Symbol]) -> str | None:
+ """The member of one definition set that C-family prototype *decl* declares.
+
+ A lone definition of a lone prototype pairs by name, as it always has.
+ Otherwise the parameter lists pair the way a declared set pairs with a
+ defined one (``pair_overloads``).
+ """
+ if len(members) == 1 and decl.id not in self._overload_rep:
+ return members[0].id
+ declared = [self._symbols_by_id[m] for m, _ in self._overload_members.get(decl_index, ())]
+ if all(sym.id != decl.id for sym in declared):
+ declared.append(decl)
+ return pair_overloads(declared, members).get(decl.id)
def _carry_declared_floors(
self,
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
index 1e8343b8d..fde40f6aa 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -60,6 +60,7 @@ from .call_overload_selection import ( # noqa: F401
_JAVA_UNBOXED,
_JAVA_WIDENING,
_UNJUDGED_LEVEL,
+ C_LINKAGE_LANGUAGES,
OverloadSelectionMixin,
_argument_fit,
_ArgumentTypes,
@@ -109,7 +110,7 @@ from .return_types import (
normalize_return_type,
signature_parameter_count,
)
-from .symbol_identity import id_segment_name, outer_scope
+from .symbol_identity import id_segment_name, outer_scope, same_parameters
from .type_names import (
bare_type_name,
csharp_extension_receiver,
@@ -267,13 +268,18 @@ def _has_internal_linkage(path: str, sym: Symbol) -> bool:
so only a source file keeps the symbol to itself.
"""
return (
- sym.language in ("c", "cpp", "objectivec")
+ sym.language in C_LINKAGE_LANGUAGES
and sym.parent_name is None
and sym.visibility == "private"
and path.lower().endswith(_SOURCE_TU_EXTS)
)
+# (parent, name) -> [(file, index id, symbol)], and [(file, symbol, index id)].
+_Definitions = dict[tuple[str | None, str], list[tuple[str, str, Symbol]]]
+_Declarations = list[tuple[str, Symbol, str]]
+
+
def _same_translation_unit(decl_file: str, def_file: str) -> bool:
"""Are these two paths the same C++ translation unit?
@@ -423,9 +429,11 @@ class CallResolver(
self._property_accessor_ids: set[str] = set()
# C/C++ forward declaration → the definition it declares. Populated by
- # ``_build_indices``; applied to every resolved call so the edge lands
- # on the body rather than the header line that announced it.
+ # ``_build_indices``; ``_settle_callee`` applies it to every resolved
+ # call so the edge lands on the body rather than the header line.
self._decl_to_def: dict[str, str] = {}
+ # {file: every file it includes, transitively}, filled on demand.
+ self._include_closure: dict[str, set[str]] = {}
# Plain-name alias → the real symbol it stands for (``s`` in
# ``s = widget``), same-file only. Populated by ``_index_file``,
@@ -496,11 +504,11 @@ class CallResolver(
(Import-name maps are shared — see ``import_index.build_import_name_maps``.)
"""
- # (parent, name) → [(file, symbol_id)] over symbols that carry a body,
- # and the bodiless declarations waiting to be paired against them.
+ # (parent, name) → [(file, symbol_id, symbol)] over symbols that carry a
+ # body, and the bodiless declarations waiting to be paired against them.
# Both feed ``_link_declarations`` once every file has been indexed.
- definitions: dict[tuple[str | None, str], list[tuple[str, str]]] = defaultdict(list)
- declarations: list[tuple[str, str, tuple[str | None, str]]] = []
+ definitions: _Definitions = defaultdict(list)
+ declarations: _Declarations = []
# (extended type, method) -> the symbols claiming it. Settled after the
# loop, because ambiguity is judged repo-wide.
extensions: dict[tuple[str, str], set[tuple[str, str]]] = defaultdict(set)
@@ -516,8 +524,8 @@ class CallResolver(
self,
path: str,
parsed: ParsedFile,
- definitions: dict[tuple[str | None, str], list[tuple[str, str]]],
- declarations: list[tuple[str, str, tuple[str | None, str]]],
+ definitions: _Definitions,
+ declarations: _Declarations,
extensions: dict[tuple[str, str], set[tuple[str, str]]],
) -> None:
"""Index one file's symbols, collecting what is settled repo-wide later."""
@@ -544,9 +552,9 @@ class CallResolver(
# ``(parent, name)`` would redirect the spec onto an unrelated
# type's method, so it stays unlinked.
if sym.language != "go":
- declarations.append((path, index_id, decl_key))
+ declarations.append((path, sym, index_id))
else:
- definitions[decl_key].append((path, index_id))
+ definitions[decl_key].append((path, index_id, sym))
_index_bare_name(sym, index_id, file_syms, top_level)
if sym.alias_of is not None and (
@@ -677,9 +685,7 @@ class CallResolver(
self._file_extension_methods.setdefault(path, {})[key] = sym_id
def _link_declarations(
- self,
- declarations: list[tuple[str, str, tuple[str | None, str]]],
- definitions: dict[tuple[str | None, str], list[tuple[str, str]]],
+ self, declarations: _Declarations, definitions: _Definitions
) -> dict[str, str]:
"""Pair each C/C++ forward declaration with the definition it declares.
@@ -701,30 +707,109 @@ class CallResolver(
proves the method name unique and says nothing about the class, and two
unrelated classes of one name would pair across. A free function has no
class identity to get wrong and is unchanged.
+
+ C-family prototypes pair member by member (``_c_definition_of``).
"""
redirects: dict[str, str] = {}
- for decl_file, decl_id, key in declarations:
- candidates = definitions.get(key, ())
+ for decl_file, decl, decl_index in declarations:
+ rows = definitions.get((decl.parent_name, decl.name), ())
+ if decl.language in C_LINKAGE_LANGUAGES:
+ target = self._c_definition_of(decl_file, decl, decl_index, rows)
+ if target is not None:
+ redirects[decl.id] = target
+ continue
+ candidates = [(def_file, sym_id) for def_file, sym_id, _sym in rows]
# An overload stub's implementation shares its id: already defined.
- if not candidates or any(sym_id == decl_id for _f, sym_id in candidates):
+ if any(sym_id == decl_index for _f, sym_id in candidates):
continue
- # Deduped by symbol id, not by row: an overload set defined in one
- # file is several definitions sharing one id, and counting rows
- # reads that as an ambiguity that does not exist.
- including = {
- sym_id
- for def_file, sym_id in candidates
- if decl_file in self._import_targets.get(def_file, ())
- }
- distinct = {sym_id for _def_file, sym_id in candidates}
- if len(including) == 1:
- redirects[decl_id] = next(iter(including))
- elif len(distinct) == 1:
- def_file = candidates[0][0]
- if key[0] is None or _same_translation_unit(decl_file, def_file):
- redirects[decl_id] = next(iter(distinct))
+ defined = self._defining_set(decl_file, decl.parent_name, candidates)
+ if defined is not None:
+ redirects[decl_index] = defined
return redirects
+ def _defining_set(
+ self, decl_file: str, parent: str | None, candidates: list[tuple[str, str]]
+ ) -> str | None:
+ """The one definition a declaration in *decl_file* can mean, or None."""
+ # Deduped by symbol id, not by row: an overload set defined in one
+ # file is several definitions sharing one id, and counting rows
+ # reads that as an ambiguity that does not exist.
+ including = {
+ sym_id
+ for def_file, sym_id in candidates
+ if decl_file in self._import_targets.get(def_file, ())
+ }
+ if len(including) == 1:
+ return next(iter(including))
+ distinct = {sym_id for _def_file, sym_id in candidates}
+ if len(distinct) == 1 and (
+ parent is None or _same_translation_unit(decl_file, candidates[0][0])
+ ):
+ return next(iter(distinct))
+ return None
+
+ def _c_definition_of(
+ self, decl_file: str, decl: Symbol, decl_index: str, rows: list[tuple[str, str, Symbol]]
+ ) -> str | None:
+ """The definition C-family prototype *decl* declares, member by member.
+
+ Another member of *decl*'s own overload set is a different function,
+ and a ``static`` body in another translation unit is invisible to the
+ header, so neither is a candidate. Definitions with *decl*'s parameter
+ list in its own source file or in a file including it, directly or
+ not, come first when there are any: a file including the header
+ directly may define a same-named function of another namespace.
+ Platform variants defining one signature in two files stay unlinked.
+ """
+ # A same-file definition shares the prototype's id: already defined.
+ if any(sym.id == decl.id for _f, _i, sym in rows):
+ return None
+ rows = [
+ (def_file, index_id, sym)
+ for def_file, index_id, sym in rows
+ if index_id != decl_index
+ and (def_file == decl_file or index_id not in self._tu_local_ids)
+ ]
+ candidates = self._signature_candidates(decl_file, decl, rows)
+ defined = self._defining_set(decl_file, decl.parent_name, candidates)
+ if defined is None:
+ return None
+ return self._paired_member(decl, decl_index, [r[2] for r in rows if r[1] == defined])
+
+ def _signature_candidates(
+ self, decl_file: str, decl: Symbol, rows: list[tuple[str, str, Symbol]]
+ ) -> list[tuple[str, str]]:
+ """*rows* narrowed to bodies with *decl*'s parameters that see it, when any.
+
+ Only asked when several definitions compete, which keeps the include
+ walk and the signature reads off the common one-definition path.
+ """
+ everything = [(def_file, index_id) for def_file, index_id, _sym in rows]
+ if len({index_id for _f, index_id in everything}) < 2:
+ return everything
+ matching = [
+ (def_file, index_id)
+ for def_file, index_id, sym in rows
+ if same_parameters(decl, sym)
+ and (
+ _same_translation_unit(decl_file, def_file)
+ or self._includes(def_file, decl_file)
+ )
+ ]
+ return matching or everything
+
+ def _includes(self, path: str, header: str) -> bool:
+ """Does *path* include *header*, directly or through other headers?"""
+ reached = self._include_closure.get(path)
+ if reached is None:
+ reached = self._include_closure[path] = set()
+ stack = [path]
+ while stack:
+ fresh = set(self._import_targets.get(stack.pop(), ())) - reached
+ reached |= fresh
+ stack.extend(fresh)
+ return header in reached
+
@property
def declaration_definitions(self) -> dict[str, str]:
"""``{declaration symbol id: definition symbol id}`` for paired decls.
@@ -735,8 +820,12 @@ class CallResolver(
"""
return self._decl_to_def
- def _redirect_to_definition(self, resolved: ResolvedCall) -> ResolvedCall:
- """Redirect calls through aliases and declarations to the final target."""
+ def _redirect_to_definition(self, resolved: ResolvedCall) -> ResolvedCall | None:
+ """Redirect calls through aliases and declarations to the final target.
+
+ None when the target is the caller itself: recursion through its own
+ prototype draws no edge, as recursion on an overload does not.
+ """
original = resolved.callee_id
target = original
visited: set[str] = set()
@@ -757,8 +846,10 @@ class CallResolver(
):
return resolved
- if target == original or target == resolved.caller_id:
+ if target == original:
return resolved
+ if target == resolved.caller_id:
+ return None if original in self._decl_to_def else resolved
return ResolvedCall(
resolved.caller_id,
@@ -877,7 +968,7 @@ class CallResolver(
resolved = self._overload_sibling_call(call) or self._resolve_one(file_path, call)
if resolved:
- resolved = self._narrow_overload(self._redirect_to_definition(resolved), call)
+ resolved = self._settle_callee(resolved, call)
if resolved:
# The edge type is a property of the call syntax, not of the
# tier that answered, so it is stamped once here.
@@ -894,6 +985,26 @@ class CallResolver(
return results
+ def _settle_callee(self, resolved: ResolvedCall, call: CallSite) -> ResolvedCall | None:
+ """Carry *resolved* through prototypes, aliases and overload sets to its body.
+
+ A C-family prototype pairs member by member, so its overload set is
+ narrowed before the redirect; any other set is redirected first and
+ narrowed among its definition's members. The final redirect covers a
+ chosen member whose body lives in another file.
+ """
+ callee = self._symbols_by_id.get(resolved.callee_id)
+ member_paired = (
+ callee is not None
+ and callee.language in C_LINKAGE_LANGUAGES
+ and resolved.callee_id in self._overload_rep
+ )
+ if not member_paired:
+ resolved = self._redirect_to_definition(resolved)
+ if resolved:
+ resolved = self._narrow_overload(resolved, call)
+ return self._redirect_to_definition(resolved) if resolved else None
+
def _resolve_one(self, file_path: str, call: CallSite) -> ResolvedCall | None:
"""Resolve a single CallSite through the three-tier fallback."""
caller_id = call.caller_symbol_id
diff --git a/packages/core/src/repowise/core/ingestion/symbol_identity.py b/packages/core/src/repowise/core/ingestion/symbol_identity.py
index 360ab698c..f98189154 100644
--- a/packages/core/src/repowise/core/ingestion/symbol_identity.py
+++ b/packages/core/src/repowise/core/ingestion/symbol_identity.py
@@ -412,6 +412,16 @@ def parameter_type_arity(parameter: str) -> int:
return type_argument_count(" ".join(written[:-1]) or parameter)
+def same_parameters(declared: Symbol, defined: Symbol) -> bool:
+ """Do both declare one parameter list, by count and erased types?"""
+ count = _parameter_count(declared)
+ return (
+ count is not None
+ and count == _parameter_count(defined)
+ and _parameter_types(declared) == _parameter_types(defined)
+ )
+
+
def pair_overloads(declared: list[Symbol], defined: list[Symbol]) -> dict[str, str]:
"""``{declared id: defined id}``: by count and erased types, then by count.
diff --git a/tests/unit/ingestion/test_cpp_decl_def.py b/tests/unit/ingestion/test_cpp_decl_def.py
index afa395367..e542dab70 100644
--- a/tests/unit/ingestion/test_cpp_decl_def.py
+++ b/tests/unit/ingestion/test_cpp_decl_def.py
@@ -111,6 +111,98 @@ class TestCallAttachesToDefinition:
assert _callers_of(graph, "circle.cpp::Area") == set()
assert _callers_of(graph, "square.cpp::Area") == set()
+ def test_definition_with_the_declared_parameters_is_chosen(self, tmp_path: Path) -> None:
+ # The body sits in an ``-inl.h`` that reaches the header through
+ # another, while a file including it directly defines an ``emit`` of
+ # other parameters, as a sibling namespace may.
+ (tmp_path / "base.h").write_text("void emit(const char* s);\n")
+ (tmp_path / "format.h").write_text('#include "base.h"\n')
+ (tmp_path / "format-inl.h").write_text(
+ '#include "format.h"\nvoid emit(const char* s) { }\n'
+ )
+ (tmp_path / "color.h").write_text('#include "base.h"\nvoid emit(int style) { }\n')
+ (tmp_path / "use.cpp").write_text('#include "base.h"\nvoid run() { emit("x"); }\n')
+ graph = _build(tmp_path)
+ assert _callers_of(graph, "format-inl.h::emit") == {"use.cpp::run"}
+ assert _callers_of(graph, "color.h::emit") == set()
+
+ def test_prototype_beside_an_inline_overload_reaches_its_body(self, tmp_path: Path) -> None:
+ (tmp_path / "api.h").write_text(
+ "void emit(const char* s);\ninline void emit(int n) { emit(\"n\"); }\n"
+ )
+ (tmp_path / "api.cc").write_text('#include "api.h"\nvoid emit(const char* s) { }\n')
+ (tmp_path / "use.cpp").write_text('#include "api.h"\nvoid run() { emit("x"); }\n')
+ graph = _build(tmp_path)
+ assert _callers_of(graph, "api.cc::emit") == {"use.cpp::run", _id_at(graph, "api.h", 2)}
+
+ def test_static_namesake_in_another_file_does_not_block_pairing(
+ self, tmp_path: Path
+ ) -> None:
+ (tmp_path / "util.h").write_text("void canon(char* p);\n")
+ (tmp_path / "util.cc").write_text('#include "util.h"\nvoid canon(char* p) { }\n')
+ (tmp_path / "util_test.cc").write_text(
+ '#include "util.h"\nnamespace {\nvoid canon(char* p) { ::canon(p); }\n}\n'
+ )
+ (tmp_path / "app.cc").write_text('#include "util.h"\nvoid run(char* p) { canon(p); }\n')
+ graph = _build(tmp_path)
+ assert "app.cc::run" in _callers_of(graph, "util.cc::canon")
+
+ def test_platform_variants_of_a_method_stay_unlinked(self, tmp_path: Path) -> None:
+ (tmp_path / "sub.h").write_text("struct Sub { int Finish(); };\n")
+ for name in ("sub-posix.cc", "sub-win32.cc"):
+ (tmp_path / name).write_text('#include "sub.h"\nint Sub::Finish() { return 0; }\n')
+ (tmp_path / "run.cc").write_text(
+ '#include "sub.h"\nint run(Sub* s) { return s->Finish(); }\n'
+ )
+ graph = _build(tmp_path)
+ assert _callers_of(graph, "sub-posix.cc::Sub::Finish") == set()
+ assert _callers_of(graph, "sub-win32.cc::Sub::Finish") == set()
+
+ def test_recursion_through_the_prototype_draws_no_edge(self, tmp_path: Path) -> None:
+ (tmp_path / "walk.h").write_text("int walk(int n);\n")
+ (tmp_path / "walk.c").write_text(
+ '#include "walk.h"\nint walk(int n) { return n ? walk(n - 1) : 0; }\n'
+ )
+ graph = _build(tmp_path)
+ assert _callers_of(graph, "walk.h::walk") == set()
+ assert _callers_of(graph, "walk.c::walk") == set()
+
+
+class TestHeaderDefaultsReachTheDefinition:
+ def test_a_header_default_is_admitted_by_the_definition(self, tmp_path: Path) -> None:
+ (tmp_path / "f.h").write_text("void f(int a, int b = 0);\n")
+ (tmp_path / "f.cc").write_text('#include "f.h"\nvoid f(int a, int b) { }\n')
+ (tmp_path / "use.cc").write_text('#include "f.h"\nvoid run() { f(1); }\n')
+ graph = _build(tmp_path)
+ assert _callers_of(graph, "f.cc::f") == {"use.cc::run"}
+
+ # A same-file call resolves on the definitions' set, whose default-bearing member is not
+ # the representative: only a carried floor reaches it.
+ def test_a_set_whose_first_member_is_undefined_still_lends_its_defaults(
+ self, tmp_path: Path
+ ) -> None:
+ (tmp_path / "f.h").write_text(
+ "void f(double d, int b);\n"
+ "void f(int a, int b = 0);\n"
+ "void f(const char* s, int b);\n"
+ )
+ (tmp_path / "f.cc").write_text(
+ '#include "f.h"\nvoid f(const char* s, int b) { }\n'
+ "void f(int a, int b) { }\n"
+ "void run() { f(1); }\n"
+ )
+ graph = _build(tmp_path)
+ assert _callers_of(graph, _id_at(graph, "f.cc", 3)) == {"f.cc::run"}
+ assert _callers_of(graph, _id_at(graph, "f.cc", 2)) == set()
+
+
+def _id_at(graph, path: str, line: int) -> str:
+ return next(
+ node
+ for node, data in graph.nodes(data=True)
+ if data.get("file_path") == path and data.get("start_line") == line
+ )
+
class TestTypeDeclarationFlag:
"""``class Env;`` is a declaration too, and only the ``body`` field says so.
@@ -193,3 +285,148 @@ class TestTypeDeclarationFlag:
assert graph.nodes["t.hh::Multi"]["is_declaration"] is True
assert graph.nodes["t.hh::Bar"]["is_declaration"] is False
assert graph.nodes["t.hh::fn"]["is_declaration"] is False
+
+
+def _resolver(tmp_path: Path, files: dict[str, str], includes: dict[str, set[str]]):
+ """A resolver over *files*, with the include map spelled out by hand."""
+ from repowise.core.ingestion.call_resolver import CallResolver
+
+ for name, text in files.items():
+ (tmp_path / name).write_text(text)
+ parser = ASTParser()
+ parsed = {
+ fi.path: parser.parse_file(fi, Path(fi.abs_path).read_bytes())
+ for fi in FileTraverser(tmp_path).traverse()
+ }
+ targets = {**{path: set() for path in parsed}, **includes}
+ return CallResolver(parsed, targets, repo_path=str(tmp_path)), parsed
+
+
+def _symbol(parsed, path: str, name: str, *, declaration: bool):
+ return next(
+ s for s in parsed[path].symbols if s.name == name and s.is_declaration is declaration
+ )
+
+
+def _rows(parsed, name: str, paths: tuple[str, ...]):
+ """Definition rows ``(file, index id, symbol)`` as ``_link_declarations`` builds them."""
+ rows = []
+ for path in paths:
+ sym = _symbol(parsed, path, name, declaration=False)
+ rows.append((path, sym.id, sym))
+ return rows
+
+
+class TestDefiningSet:
+ """``_defining_set``: the one definition a declaration can mean, or None."""
+
+ def test_the_one_definition_including_the_header_wins(self, tmp_path: Path) -> None:
+ resolver, _ = _resolver(tmp_path, {}, {"a.cc": {"f.h"}})
+ candidates = [("a.cc", "a.cc::f"), ("b.cc", "b.cc::f")]
+ assert resolver._defining_set("f.h", None, candidates) == "a.cc::f"
+
+ def test_two_including_definitions_refuse(self, tmp_path: Path) -> None:
+ resolver, _ = _resolver(tmp_path, {}, {"a.cc": {"f.h"}, "b.cc": {"f.h"}})
+ candidates = [("a.cc", "a.cc::f"), ("b.cc", "b.cc::f")]
+ assert resolver._defining_set("f.h", None, candidates) is None
+
+ def test_a_lone_free_function_pairs_without_an_include(self, tmp_path: Path) -> None:
+ resolver, _ = _resolver(tmp_path, {}, {})
+ assert resolver._defining_set("f.h", None, [("x.cc", "x.cc::f")]) == "x.cc::f"
+
+ def test_a_lone_method_pairs_only_in_its_own_translation_unit(self, tmp_path: Path) -> None:
+ resolver, _ = _resolver(tmp_path, {}, {})
+ assert resolver._defining_set("f.h", "P", [("x.cc", "x.cc::P::f")]) is None
+ assert resolver._defining_set("f.h", "P", [("f.cc", "f.cc::P::f")]) == "f.cc::P::f"
+
+ def test_one_overload_set_is_one_definition(self, tmp_path: Path) -> None:
+ """Two rows sharing one id are one set, not an ambiguity."""
+ resolver, _ = _resolver(tmp_path, {}, {})
+ assert resolver._defining_set("f.h", None, [("x.cc", "x.cc::f")] * 2) == "x.cc::f"
+
+ def test_platform_variants_refuse(self, tmp_path: Path) -> None:
+ resolver, _ = _resolver(tmp_path, {}, {})
+ candidates = [("f-posix.cc", "f-posix.cc::f"), ("f-win32.cc", "f-win32.cc::f")]
+ assert resolver._defining_set("f.h", None, candidates) is None
+
+
+class TestCDefinitionOf:
+ """``_c_definition_of``: a C-family prototype's definition, member by member."""
+
+ def test_a_prototype_nothing_defines_pairs_with_nothing(self, tmp_path: Path) -> None:
+ resolver, parsed = _resolver(tmp_path, {"f.h": "void f(int n);\n"}, {})
+ decl = _symbol(parsed, "f.h", "f", declaration=True)
+ assert resolver._c_definition_of("f.h", decl, decl.id, []) is None
+ assert decl.id not in resolver.declaration_definitions
+
+ def test_the_lone_definition_is_paired(self, tmp_path: Path) -> None:
+ files = {"f.h": "void f(int n);\n", "f.cc": '#include "f.h"\nvoid f(int n) { }\n'}
+ resolver, parsed = _resolver(tmp_path, files, {"f.cc": {"f.h"}})
+ decl = _symbol(parsed, "f.h", "f", declaration=True)
+ rows = _rows(parsed, "f", ("f.cc",))
+ assert resolver._c_definition_of("f.h", decl, decl.id, rows) == "f.cc::f"
+
+ def test_a_static_body_in_another_file_is_no_candidate(self, tmp_path: Path) -> None:
+ files = {
+ "f.h": "void f(int n);\n",
+ "f.cc": '#include "f.h"\nvoid f(int n) { }\n',
+ "t.cc": '#include "f.h"\nstatic void f(int n) { }\n',
+ }
+ resolver, parsed = _resolver(tmp_path, files, {"f.cc": {"f.h"}, "t.cc": {"f.h"}})
+ decl = _symbol(parsed, "f.h", "f", declaration=True)
+ both = _rows(parsed, "f", ("f.cc", "t.cc"))
+ assert resolver._c_definition_of("f.h", decl, decl.id, both) == "f.cc::f"
+ alone = _rows(parsed, "f", ("t.cc",))
+ assert resolver._c_definition_of("f.h", decl, decl.id, alone) is None
+
+ def test_an_anonymous_namespace_body_is_no_candidate(self, tmp_path: Path) -> None:
+ files = {
+ "f.h": "void f(int n);\n",
+ "f.cc": '#include "f.h"\nvoid f(int n) { }\n',
+ "t.cc": '#include "f.h"\nnamespace {\nvoid f(int n) { }\n}\n',
+ }
+ resolver, parsed = _resolver(tmp_path, files, {"f.cc": {"f.h"}, "t.cc": {"f.h"}})
+ decl = _symbol(parsed, "f.h", "f", declaration=True)
+ rows = _rows(parsed, "f", ("f.cc", "t.cc"))
+ assert resolver._c_definition_of("f.h", decl, decl.id, rows) == "f.cc::f"
+
+ def test_a_member_of_its_own_overload_set_is_no_candidate(self, tmp_path: Path) -> None:
+ """A row under the prototype's own index id is another member of its set."""
+ files = {"f.h": "void f(int n);\n", "x.cc": "void f(int n) { }\n"}
+ resolver, parsed = _resolver(tmp_path, files, {})
+ decl = _symbol(parsed, "f.h", "f", declaration=True)
+ body = _symbol(parsed, "x.cc", "f", declaration=False)
+ assert resolver._c_definition_of("f.h", decl, decl.id, [("x.cc", decl.id, body)]) is None
+
+ def test_a_same_file_definition_is_already_the_prototype(self, tmp_path: Path) -> None:
+ resolver, parsed = _resolver(tmp_path, {"f.c": "void f(int n);\nvoid f(int n) { }\n"}, {})
+ decl = _symbol(parsed, "f.c", "f", declaration=True)
+ body = _symbol(parsed, "f.c", "f", declaration=False)
+ assert decl.id == body.id
+ assert resolver._c_definition_of("f.c", decl, decl.id, [("f.c", body.id, body)]) is None
+
+ def test_the_body_with_the_declared_parameters_that_sees_the_header_wins(
+ self, tmp_path: Path
+ ) -> None:
+ """Both bodies include the header; only one has its parameter list."""
+ files = {
+ "f.h": "void f(const char* s);\n",
+ "a.cc": '#include "f.h"\nvoid f(const char* s) { }\n',
+ "b.cc": '#include "f.h"\nvoid f(int style) { }\n',
+ }
+ resolver, parsed = _resolver(tmp_path, files, {"a.cc": {"f.h"}, "b.cc": {"f.h"}})
+ decl = _symbol(parsed, "f.h", "f", declaration=True)
+ rows = _rows(parsed, "f", ("a.cc", "b.cc"))
+ assert resolver._c_definition_of("f.h", decl, decl.id, rows) == "a.cc::f"
+
+ def test_platform_variants_of_one_signature_stay_unpaired(self, tmp_path: Path) -> None:
+ files = {
+ "f.h": "void f(int n);\n",
+ "f-posix.cc": '#include "f.h"\nvoid f(int n) { }\n',
+ "f-win32.cc": '#include "f.h"\nvoid f(int n) { }\n',
+ }
+ includes = {"f-posix.cc": {"f.h"}, "f-win32.cc": {"f.h"}}
+ resolver, parsed = _resolver(tmp_path, files, includes)
+ decl = _symbol(parsed, "f.h", "f", declaration=True)
+ rows = _rows(parsed, "f", ("f-posix.cc", "f-win32.cc"))
+ assert resolver._c_definition_of("f.h", decl, decl.id, rows) is None