Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(ingestion): type C++ receivers from their declarations (#1919)

Raghav Chamadiya0c9faff85da6
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
index d3f8c5ebe..edccc1fcc 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -47,6 +47,7 @@ from .languages.receiver_types import (
scan_declarations,
types_by_class,
types_in_span,
+ unwrapped_names_in_span,
)
from .models import (
CallReceiver,
@@ -58,6 +59,7 @@ from .models import (
symbol_id_language,
)
from .return_types import declared_return_type, normalize_return_type, signature_parameter_count
+from .type_names import POINTER_LIKE_MEMBERS
log = structlog.get_logger(__name__)
@@ -138,8 +140,14 @@ _JVM_STRATEGIES = _LanguageCallStrategies(
member=("_resolve_jvm_receiver_same_package",),
)
+# C++ reaches the typed fallback and registers no `member` strategy, so an
+# `obj->m()` is looked for in the caller's own file, in what it includes, and
+# then in the global pair index. `c` shares this object and is excluded a layer
+# up instead: it is absent from `_LANGUAGE_PATTERNS`, and a struct declares no
+# method for the pair index to hold.
_CPP_STRATEGIES = _LanguageCallStrategies(
free=("_resolve_cpp_scoped_call", "_resolve_cpp_same_target"),
+ member_fallback=_TYPED_RECEIVER,
)
# Rust's crate-root strategy is deliberately absent: it runs for every language
@@ -1660,6 +1668,8 @@ class CallResolver:
return None
if type_name is None:
return None
+ if self._means_the_wrapper(file_path, caller_id, language, call, receiver_name):
+ return None
found = self._typed_receiver_target(file_path, call, caller_id, type_name)
if found is None:
@@ -1671,6 +1681,32 @@ class CallResolver:
return self._field_typed_call(caller_id, sym_id, tier, call.line)
return self._body_typed_call(caller_id, sym_id, tier, call.line)
+ def _means_the_wrapper(
+ self,
+ file_path: str,
+ caller_id: str,
+ language: str,
+ call: CallSite,
+ receiver_name: str,
+ ) -> bool:
+ """Is this call on the smart pointer itself rather than on what it holds?
+
+ ``shared_ptr<Foo> p`` gives ``p->m()`` a ``Foo`` and ``p.m()`` a
+ ``shared_ptr``, and the grammar query captures no operator to tell them
+ apart. The names a dot call can reach are closed by the language, so
+ refusing exactly those is what keeps ``p.get()`` off a repo's own
+ ``Foo::get`` -- at the cost of an arrow call that really did mean one.
+ Asked only of C++, and only of a type that was unwrapped.
+ """
+ if language != "cpp" or call.target_name not in POINTER_LIKE_MEMBERS:
+ return False
+ span = self._spans_for(file_path).get(caller_id)
+ if span is None:
+ return False
+ return receiver_name in unwrapped_names_in_span(
+ self._declarations_for(file_path, language), *span
+ )
+
def _body_typed_call(self, caller_id: str, sym_id: str, tier: str, line: int) -> ResolvedCall:
"""Stamp an edge whose receiver was typed from the calling body."""
if tier == "same_file":
diff --git a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
index 79820808f..51d257e8d 100644
--- a/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
+++ b/packages/core/src/repowise/core/ingestion/languages/receiver_types.py
@@ -34,7 +34,12 @@ from collections.abc import Iterable, Mapping
from typing import NamedTuple
from ..language_data import get_builtin_types
-from ..type_names import bare_type_name, is_resolvable_type_name, strip_type_arguments
+from ..type_names import (
+ bare_type_name,
+ is_resolvable_type_name,
+ strip_type_arguments,
+ unwrap_pointer_like,
+)
# A type as written before a declared name: optionally qualified, optionally
# generic to two levels of nesting, optionally an array. A third level yields
@@ -264,6 +269,46 @@ _SWIFT_CONSTRUCTED = re.compile(
r"(?<![\w.])(?:let|var)\s+(?P<name>[a-z_]\w*)\s*=\s*(?P<type>[A-Z]\w*)\s*\((?![^()]*\)\s*\.)"
)
+# C++ writes the C family's ``T name``, with three differences ``_TYPE`` cannot
+# read: ``::`` qualifies rather than ``.``, a pointer or reference star binds
+# between the type and the name, and a lowercase head is ordinary rather than a
+# Go-style unexported one, because every STL type is written that way.
+#
+# A keyword head is refused outright. Without it ``struct foo {`` and
+# ``namespace foo {`` present as ``struct``/``namespace`` naming a ``foo``, and
+# ``auto`` would be read as a type rather than as the absence of one.
+_CPP_KEYWORDS = (
+ r"(?:const|constexpr|consteval|constinit|static|mutable|volatile|extern|"
+ r"inline|virtual|explicit|friend|typedef|using|namespace|template|typename|"
+ r"class|struct|union|enum|public|private|protected|return|delete|new|throw|"
+ r"case|else|do|if|for|while|switch|goto|break|continue|auto|register|"
+ r"operator|sizeof|decltype|noexcept|co_await|co_return|co_yield)"
+)
+
+# Two levels of nesting, the same ceiling ``_TYPE`` states and for the same
+# reason: a third needs a real bracket matcher, and failing to type a name
+# costs an edge rather than inventing one.
+_CPP_TYPE = r"(?:[A-Za-z_]\w*\s*::\s*)*[A-Za-z_]\w*(?:\s*<(?:[^<>]|<[^<>]*>)*>)?"
+
+# ``T name``, ``T* name``, ``T& name``, ``ns::T name``, ``W<T> name``, closed by
+# the same punctuation the C family requires plus ``{`` for brace init.
+#
+# ``(`` is deliberately NOT a closer, and it is load-bearing twice. ``Status
+# doIt(int x);`` is a method declaration and not a variable of type ``Status``,
+# and it is the commonest line in a C++ header. Excluding it also drops ``Foo
+# bar(args);``, a real construction -- that costs an edge, which is the safe
+# direction, and it additionally keeps a constructed local from being read at a
+# scope where a same-named field would answer instead.
+#
+# ``>`` and ``:`` sit in the lookbehind so the scan cannot restart inside a
+# type it has already read: without them ``std::shared_ptr<Foo>& p`` matches a
+# second time at ``shared_ptr``.
+_CPP_DECLARATION = re.compile(
+ rf"(?<![\w.>:])(?!{_CPP_KEYWORDS}\b)(?P<type>{_CPP_TYPE})"
+ rf"(?:\s*[*&]{{1,2}}\s*|\s+)(?P<name>[a-z_]\w*)\s*(?=(?P<closer>[=;,){{]))"
+)
+
+
_C_FAMILY = (_TYPED_DECLARATION, _INFERRED_FROM_NEW)
# No Go shape captures a closer, so every Go declaration carries ``""`` and
# class scope would drop all of them. That is the intended reading: Go is not
@@ -273,6 +318,7 @@ _KT_FAMILY = (_KT_ANNOTATED, _KT_CONSTRUCTED)
_SWIFT_FAMILY = (_SWIFT_ANNOTATED, _SWIFT_CONSTRUCTED)
_LANGUAGE_PATTERNS: dict[str, tuple[re.Pattern[str], ...]] = {
+ "cpp": (_CPP_DECLARATION,),
"csharp": _C_FAMILY,
"go": _GO_FAMILY,
"java": _C_FAMILY,
@@ -400,10 +446,14 @@ def framework_decorated_type(decorators: Iterable[str], language: str) -> str |
return None
_LANGUAGE_BLOCK_COMMENTS: dict[str, re.Pattern[str]] = {
+ # C++ needs the block strip for the reason Kotlin does: doxygen writes
+ # `@param Type name`, which is exactly the shape the scan reads.
+ "cpp": _BLOCK_COMMENT,
"kotlin": _BLOCK_COMMENT,
}
_LANGUAGE_COMMENTS: dict[str, re.Pattern[str]] = {
+ "cpp": _LINE_COMMENT,
"csharp": _LINE_COMMENT,
"go": _LINE_COMMENT,
"java": _LINE_COMMENT,
@@ -418,12 +468,18 @@ class Declaration(NamedTuple):
``closer`` is the punctuation that ended the declaration, or empty where
the shape has none. Only class scope reads it.
+
+ ``unwrapped`` marks a type taken from inside a pointer-like wrapper rather
+ than written outright. The two spellings answer differently depending on
+ which operator the call used, and the caller that cannot see the operator
+ reads this to refuse the ambiguous names.
"""
line: int
name: str
type_name: str
closer: str = ""
+ unwrapped: bool = False
# What can end a field. `var` has no place here at all: it is a local-only
@@ -445,12 +501,22 @@ def _nests_in_a_builtin(raw: str, language: str) -> bool:
return bool(separator) and head in get_builtin_types(language)
-def _usable_type_name(raw: str, language: str) -> str | None:
- """The bare name *raw* denotes, or None if it can name no repo symbol."""
+def _usable_type_name(raw: str, language: str) -> tuple[str | None, bool]:
+ """``(bare name, unwrapped)`` for *raw*, or ``(None, False)``.
+
+ C++ is the one language that looks inside the spelling: ``shared_ptr<Foo>``
+ denotes a ``Foo`` at every call the arrow can reach, and taking the head
+ would answer ``shared_ptr``, which names no repo symbol and resolves
+ nothing. Every other language keeps the head, where a generic really is
+ the type the value has.
+ """
if _nests_in_a_builtin(raw, language):
- return None
- name = raw if raw.isidentifier() else bare_type_name(raw)
- return name if is_resolvable_type_name(name, language) else None
+ return None, False
+ inner = unwrap_pointer_like(raw) if language == "cpp" else None
+ name = inner or (raw if raw.isidentifier() else bare_type_name(raw))
+ if not is_resolvable_type_name(name, language):
+ return None, False
+ return name, inner is not None
def scan_declarations(text: str, language: str) -> tuple[Declaration, ...]:
@@ -474,14 +540,14 @@ def scan_declarations(text: str, language: str) -> tuple[Declaration, ...]:
# One file writes the same type name hundreds of times, and normalising it
# walks the string character by character. Resolve each spelling once.
- resolved: dict[str, str | None] = {}
+ resolved: dict[str, tuple[str | None, bool]] = {}
found: list[Declaration] = []
for pattern in patterns:
for match in pattern.finditer(cleaned):
raw = match.group("type")
if raw not in resolved:
resolved[raw] = _usable_type_name(raw, language)
- type_name = resolved[raw]
+ type_name, unwrapped = resolved[raw]
if type_name is None:
continue
groups = match.groupdict()
@@ -497,6 +563,7 @@ def scan_declarations(text: str, language: str) -> tuple[Declaration, ...]:
match.group("name"),
type_name,
closer,
+ unwrapped,
)
)
@@ -538,6 +605,24 @@ def types_in_span(
return types
+def unwrapped_names_in_span(
+ declarations: tuple[Declaration, ...],
+ start_line: int,
+ end_line: int,
+) -> frozenset[str]:
+ """The names in one body whose type was taken from inside a wrapper.
+
+ Separate from ``types_in_span`` rather than folded into its return: only
+ C++ can produce one of these, and only one caller asks.
+ """
+ first = bisect_left(declarations, start_line, key=lambda d: d.line)
+ return frozenset(
+ declaration.name
+ for declaration in declarations[first:]
+ if declaration.line <= end_line and declaration.unwrapped
+ )
+
+
def _merged(spans: Iterable[tuple[int, int]]) -> tuple[tuple[int, int], ...]:
"""The spans as non-overlapping, ascending intervals."""
merged: list[list[int]] = []
diff --git a/packages/core/src/repowise/core/ingestion/type_names.py b/packages/core/src/repowise/core/ingestion/type_names.py
index 6e853fa2f..4ce3f52e2 100644
--- a/packages/core/src/repowise/core/ingestion/type_names.py
+++ b/packages/core/src/repowise/core/ingestion/type_names.py
@@ -92,6 +92,67 @@ def bare_type_name(raw: str) -> str:
return text.strip()
+# C++ template heads whose ``operator->`` forwards to their argument, so
+# ``shared_ptr<Foo> p`` makes ``p->m()`` a call on ``Foo``. Only these: a
+# container holds a ``T`` without being one, and unwrapping ``vector<Foo>``
+# would answer ``Foo`` for ``v.size()``.
+#
+# ``weak_ptr`` is deliberately absent. It declares no ``operator->`` at all and
+# reaches its argument only through ``lock()``.
+_POINTER_LIKE_HEADS = frozenset({"shared_ptr", "unique_ptr", "auto_ptr", "optional"})
+
+# Every member the heads above declare, which is the whole of what a ``.`` call
+# on one can name -- the arrow yields the argument, the dot yields the wrapper.
+# A caller that cannot see which operator was written refuses these names
+# instead, which costs an arrow call that really did mean ``Foo::get`` and
+# never lets a ``p.get()`` bind to one. Measured over aria2's 2,242 wrapper
+# receivers: it covers every one of the 355 real dot calls and gives up 57
+# arrows.
+POINTER_LIKE_MEMBERS = frozenset({
+ "get", "reset", "release", "swap", "use_count", "unique", "owner_before",
+ "get_deleter", "value", "has_value", "value_or", "emplace",
+ "and_then", "transform", "or_else",
+})
+
+
+def unwrap_pointer_like(raw: str) -> str | None:
+ """The type ``raw``'s ``operator->`` yields, or None if it forwards nowhere.
+
+ ``std::shared_ptr<Foo>`` -> ``Foo``; ``unique_ptr<Foo, D>`` -> ``Foo``,
+ since the deleter is not what the arrow reaches. Every other head answers
+ None, a repo's own wrapper included: whether *its* arrow forwards is not
+ written at the declaration, and guessing would bind ``h->m()`` to a class
+ the handle merely holds.
+
+ ``normalize_return_type`` deliberately does not use this. There the head is
+ the receiver -- ``future<T>.get()`` is a method on ``future`` -- so the two
+ call sites want opposite answers from the same spelling.
+ """
+ head, opener, rest = raw.strip().partition("<")
+ rest = rest.rstrip()
+ if not opener or not rest.endswith(">"):
+ return None
+ for separator in _QUALIFIER_SEPARATORS:
+ head = head.rsplit(separator, 1)[-1]
+ if head.strip() not in _POINTER_LIKE_HEADS:
+ return None
+
+ # The first top-level argument, tracked by depth so a ``map<K, V>`` nested
+ # inside one cannot be split at its own comma.
+ depth = 0
+ first: list[str] = []
+ for char in rest[:-1]:
+ if char in "<([":
+ depth += 1
+ elif char in ">)]":
+ depth -= 1
+ elif char == "," and depth == 0:
+ break
+ first.append(char)
+ name = bare_type_name("".join(first))
+ return name or None
+
+
def is_resolvable_type_name(name: str, language: str) -> bool:
"""True if *name* could name a symbol declared in this repo.
diff --git a/tests/unit/ingestion/test_cpp_typed_receivers.py b/tests/unit/ingestion/test_cpp_typed_receivers.py
new file mode 100644
index 000000000..9c2943a86
--- /dev/null
+++ b/tests/unit/ingestion/test_cpp_typed_receivers.py
@@ -0,0 +1,111 @@
+"""A C++ ``obj->method()`` must resolve against the receiver's declared type.
+
+``_CPP_STRATEGIES`` carried an empty ``member`` and ``member_fallback``, so a
+call with a receiver reached no strategy at all: measured over leveldb and
+aria2, C++ resolved 13 of 22,112 receiver-carrying sites. Six languages already
+resolve exactly that shape by reading the receiver's declaration, and the shape
+C++ writes it in is the C family's ``T name`` plus ``::``, a pointer star, and
+lowercase heads.
+
+The wrapper case is where the two spellings disagree. ``shared_ptr<Foo> p``
+makes ``p->m()`` a call on ``Foo`` and ``p.m()`` a call on the pointer, and the
+grammar query captures no operator to tell them apart. The names a dot call can
+reach are closed by the language, so those are refused instead.
+"""
+
+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 _call_targets(graph, caller_file: str) -> set[str]:
+ return {
+ t
+ for s, t, d in graph.edges(data=True)
+ if d.get("edge_type") == "calls" and str(s).startswith(caller_file + "::")
+ }
+
+
+def _repo(root: Path, caller_body: str, *, extra: str = "") -> None:
+ """One class with a method, one decoy class declaring the same name."""
+ (root / "lib").mkdir(parents=True, exist_ok=True)
+ (root / "lib" / "peer.h").write_text(
+ "#pragma once\n"
+ "class Peer {\n public:\n int sendMessage(int n);\n int get(int n);\n};\n"
+ "class Stranger {\n public:\n int sendMessage(int n);\n};\n"
+ )
+ (root / "lib" / "peer.cc").write_text(
+ '#include "lib/peer.h"\n'
+ "int Peer::sendMessage(int n) { return n; }\n"
+ "int Peer::get(int n) { return n; }\n"
+ "int Stranger::sendMessage(int n) { return n + 1; }\n"
+ )
+ (root / "lib" / "caller.cc").write_text(
+ '#include "lib/peer.h"\n' + extra + "int Run() {\n" + caller_body + "\n}\n"
+ )
+
+
+class TestTypedReceiverResolves:
+ def test_a_pointer_receiver_binds_to_its_declared_type(self, tmp_path: Path) -> None:
+ _repo(tmp_path, " Peer* peer;\n return peer->sendMessage(1);")
+ assert any(t.endswith("Peer::sendMessage") for t in _call_targets(_build(tmp_path), "lib/caller.cc"))
+
+ def test_a_value_receiver_binds_too(self, tmp_path: Path) -> None:
+ _repo(tmp_path, " Peer peer;\n return peer.sendMessage(1);")
+ assert any(t.endswith("Peer::sendMessage") for t in _call_targets(_build(tmp_path), "lib/caller.cc"))
+
+ def test_it_does_not_answer_with_another_class_declaring_the_name(
+ self, tmp_path: Path
+ ) -> None:
+ """The decoy control: ``Stranger`` declares ``sendMessage`` as well."""
+ _repo(tmp_path, " Peer* peer;\n return peer->sendMessage(1);")
+ assert not any("Stranger" in t for t in _call_targets(_build(tmp_path), "lib/caller.cc"))
+
+ def test_an_undeclared_receiver_resolves_nothing(self, tmp_path: Path) -> None:
+ """The control the mechanism has to fail: nothing types ``peer`` here."""
+ _repo(tmp_path, " return peer->sendMessage(1);")
+ assert not any(t.endswith("Peer::sendMessage") for t in _call_targets(_build(tmp_path), "lib/caller.cc"))
+
+
+class TestSmartPointerReceivers:
+ def test_a_shared_ptr_binds_to_what_it_holds(self, tmp_path: Path) -> None:
+ """The peer's normaliser strips the whole ``<...>`` and loses ``Peer``."""
+ _repo(tmp_path, " std::shared_ptr<Peer> peer;\n return peer->sendMessage(1);")
+ assert any(t.endswith("Peer::sendMessage") for t in _call_targets(_build(tmp_path), "lib/caller.cc"))
+
+ def test_a_unique_ptr_binds_past_its_deleter(self, tmp_path: Path) -> None:
+ _repo(tmp_path, " std::unique_ptr<Peer, D> peer;\n return peer->sendMessage(1);")
+ assert any(t.endswith("Peer::sendMessage") for t in _call_targets(_build(tmp_path), "lib/caller.cc"))
+
+ def test_a_name_the_pointer_itself_declares_is_refused(self, tmp_path: Path) -> None:
+ """``peer.get()`` is ``shared_ptr::get``, and ``Peer`` declares a ``get`` too.
+
+ The operator is not captured, so the dot call and the arrow call arrive
+ identical. Refusing the closed member set is what keeps this off
+ ``Peer::get``; it costs the arrow calls that really did mean one.
+ """
+ _repo(tmp_path, " std::shared_ptr<Peer> peer;\n return peer->get(1);")
+ assert not any(t.endswith("Peer::get") for t in _call_targets(_build(tmp_path), "lib/caller.cc"))
+
+ def test_the_refusal_does_not_reach_a_plainly_declared_receiver(
+ self, tmp_path: Path
+ ) -> None:
+ """The control the refusal has to fail: ``Peer* peer`` unwraps nothing."""
+ _repo(tmp_path, " Peer* peer;\n return peer->get(1);")
+ assert any(t.endswith("Peer::get") for t in _call_targets(_build(tmp_path), "lib/caller.cc"))
+
+ def test_a_container_receiver_is_not_read_as_its_element(self, tmp_path: Path) -> None:
+ """``items.sendMessage()`` is not ``Peer::sendMessage`` on a vector."""
+ _repo(tmp_path, " std::vector<Peer> items;\n return items.sendMessage(1);")
+ assert not any(t.endswith("Peer::sendMessage") for t in _call_targets(_build(tmp_path), "lib/caller.cc"))
diff --git a/tests/unit/ingestion/test_pointer_like_unwrap.py b/tests/unit/ingestion/test_pointer_like_unwrap.py
new file mode 100644
index 000000000..cc44741dd
--- /dev/null
+++ b/tests/unit/ingestion/test_pointer_like_unwrap.py
@@ -0,0 +1,63 @@
+"""What a C++ pointer-like wrapper's ``operator->`` yields.
+
+``shared_ptr<Foo> p`` denotes a ``Foo`` at every call the arrow reaches, so
+taking the head answers ``shared_ptr`` and resolves nothing. Only the heads
+that really do forward may be unwrapped: a container holds a ``T`` without
+being one, and a repo's own handle does not say either way at the declaration.
+
+``normalize_return_type`` deliberately does not use this, and the last test
+holds that apart: there the head IS the receiver, so the same spelling wants
+the opposite answer.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.ingestion.return_types import normalize_return_type
+from repowise.core.ingestion.type_names import POINTER_LIKE_MEMBERS, unwrap_pointer_like
+
+
+ ("written", "expected"),
+ [
+ ("std::shared_ptr<Foo>", "Foo"),
+ ("shared_ptr<Foo>", "Foo"),
+ ("std::unique_ptr<Foo>", "Foo"),
+ ("unique_ptr<Foo, Deleter>", "Foo"),
+ ("std::optional<Baz>", "Baz"),
+ ("ns::unique_ptr<A::B>", "B"),
+ ("std::shared_ptr<std::map<int, Bar>>", "map"),
+ ],
+)
+def test_a_forwarding_head_yields_its_argument(written: str, expected: str) -> None:
+ assert unwrap_pointer_like(written) == expected
+
+
+ "written",
+ [
+ "std::vector<Foo>",
+ "std::map<K, V>",
+ "SharedHandle<Foo>",
+ "std::weak_ptr<Foo>",
+ "Foo",
+ "shared_ptr",
+ "shared_ptr<>",
+ "",
+ ],
+)
+def test_everything_else_forwards_nowhere(written: str) -> None:
+ """The controls. ``weak_ptr`` declares no ``operator->`` at all."""
+ assert unwrap_pointer_like(written) is None
+
+
+def test_the_dot_reachable_members_are_named() -> None:
+ """A caller blind to the operator refuses these, so the set is the contract."""
+ assert {"get", "reset", "release", "use_count"} <= POINTER_LIKE_MEMBERS
+ assert "sendMessage" not in POINTER_LIKE_MEMBERS
+
+
+def test_a_return_type_keeps_its_wrapper() -> None:
+ """``future<T>.get()`` is a method on ``future``, which is the other reading."""
+ assert normalize_return_type("std::shared_ptr<Foo>", "cpp") == "shared_ptr"
diff --git a/tests/unit/ingestion/test_receiver_types.py b/tests/unit/ingestion/test_receiver_types.py
index 9ac56ac5b..1d8ea570e 100644
--- a/tests/unit/ingestion/test_receiver_types.py
+++ b/tests/unit/ingestion/test_receiver_types.py
@@ -14,6 +14,7 @@ from repowise.core.ingestion.languages.receiver_types import (
scan_declarations,
types_by_class,
types_in_span,
+ unwrapped_names_in_span,
)
@@ -625,7 +626,15 @@ class TestClassScope:
def test_the_language_set_is_what_the_patterns_declare() -> None:
"""Excluding a language means removing its shapes, not gating a caller."""
- assert set(RECEIVER_TYPE_LANGUAGES) == {"csharp", "go", "java", "kotlin", "python", "swift"}
+ assert set(RECEIVER_TYPE_LANGUAGES) == {
+ "cpp",
+ "csharp",
+ "go",
+ "java",
+ "kotlin",
+ "python",
+ "swift",
+ }
def test_go_is_not_a_field_language() -> None:
@@ -641,3 +650,102 @@ def test_go_is_not_a_field_language() -> None:
@pytest.mark.parametrize("language", ["java", "csharp", "python", "go"])
def test_an_empty_body_is_not_an_error(language: str) -> None:
assert declared_types("", language) == {}
+
+
+def unwrapped(body: str) -> frozenset[str]:
+ """The names in *body* whose type came from inside a wrapper."""
+ return unwrapped_names_in_span(scan_declarations(body, "cpp"), 1, 10_000)
+
+
+class TestCppDeclarations:
+ """The C family's shape with ``::``, a pointer star, and lowercase heads."""
+
+ @pytest.mark.parametrize(
+ ("body", "expected"),
+ [
+ ("Slice key = x;", {"key": "Slice"}),
+ ("Status s;", {"s": "Status"}),
+ ("DB* db;", {"db": "DB"}),
+ ("DB *db;", {"db": "DB"}),
+ ("Options& opt = o;", {"opt": "Options"}),
+ ("const Options& opt = o;", {"opt": "Options"}),
+ ("leveldb::Slice key;", {"key": "Slice"}),
+ ("void f(Slice key, DB* db);", {"key": "Slice", "db": "DB"}),
+ ("Row scratch{1};", {"scratch": "Row"}),
+ ],
+ )
+ def test_the_shapes_it_reads(self, body: str, expected: dict[str, str]) -> None:
+ assert declared_types(body, "cpp") == expected
+
+ def test_a_method_declaration_is_not_a_variable(self) -> None:
+ """The commonest line in a C++ header, and the reason ``(`` cannot close.
+
+ ``Status doIt(int x);`` reads as a ``doIt`` of type ``Status`` under any
+ closer set that admits the bracket, and a header is mostly these.
+ """
+ assert declared_types("Status doIt(int x);", "cpp") == {}
+
+ def test_a_constructed_local_is_given_up_rather_than_guessed(self) -> None:
+ """Same exclusion seen from the other side: a real declaration, dropped."""
+ assert declared_types("BtRequestMessage msg(0, 16);", "cpp") == {}
+
+ def test_auto_names_no_type(self) -> None:
+ assert declared_types("auto it = m.begin();", "cpp") == {}
+
+ @pytest.mark.parametrize("keyword", ["struct", "class", "namespace", "union", "enum"])
+ def test_a_keyword_head_is_not_a_type(self, keyword: str) -> None:
+ assert declared_types(f"{keyword} foo {{", "cpp") == {}
+
+ def test_a_builtin_is_refused(self) -> None:
+ assert declared_types("int count = 0;", "cpp") == {}
+
+ def test_a_comment_declares_nothing(self) -> None:
+ source = "// Slice key is the thing;\n/* Status s; */\nDB* db;"
+ assert declared_types(source, "cpp") == {"db": "DB"}
+
+
+class TestCppWrapperUnwrapping:
+ """``shared_ptr<Foo> p`` is a ``Foo`` at every call its arrow can reach."""
+
+ def test_a_smart_pointer_yields_what_it_holds(self) -> None:
+ assert declared_types("std::shared_ptr<Request> req;", "cpp") == {"req": "Request"}
+ assert unwrapped("std::shared_ptr<Request> req;") == {"req"}
+
+ def test_a_deleter_is_not_what_the_arrow_reaches(self) -> None:
+ assert declared_types("std::unique_ptr<Peer, D> peer;", "cpp") == {"peer": "Peer"}
+
+ def test_a_container_keeps_its_head(self) -> None:
+ """The control the unwrap has to fail: ``v.size()`` is not ``Entry::size``."""
+ assert declared_types("std::vector<Entry> items;", "cpp") == {"items": "vector"}
+ assert unwrapped("std::vector<Entry> items;") == frozenset()
+
+ def test_a_repo_wrapper_is_not_assumed_to_forward(self) -> None:
+ """Whether ``SharedHandle``'s arrow forwards is not written here."""
+ assert declared_types("SharedHandle<Thing> h;", "cpp") == {"h": "SharedHandle"}
+ assert unwrapped("SharedHandle<Thing> h;") == frozenset()
+
+ def test_weak_ptr_forwards_nowhere(self) -> None:
+ assert unwrapped("std::weak_ptr<Thing> w;") == frozenset()
+
+ def test_another_language_keeps_the_generic_head(self) -> None:
+ """The unwrap is C++ only: a Kotlin ``Column<T>`` really is a ``Column``."""
+ assert declared_types("val c: Column<Thing> = x", "kotlin") == {"c": "Column"}
+
+
+def test_cpp_is_not_a_field_language() -> None:
+ """C++ declares its fields in a header, away from the call that reads them.
+
+ Registering it would promise a scope the scan cannot answer from, which is
+ the condition that disqualified python on the same constant.
+ """
+ assert "cpp" not in IMPLICIT_FIELD_LANGUAGES
+
+
+def test_c_has_no_shapes_of_its_own() -> None:
+ """``c`` shares the C++ call strategies and is excluded here instead.
+
+ A struct declares no method, so the pair index the fallback ends in can
+ hold nothing for it.
+ """
+ assert "c" not in RECEIVER_TYPE_LANGUAGES
+ assert scan_declarations("Widget* w;", "c") == ()