Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(cpp): symbol-graph hardening — captures, type-refs, synthesis, entry markers (#283)
Raghav Chamadiyac984f94f7a66
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/cpp.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/cpp.pyindex 4bdefce05..8d399ad5c 100644--- a/packages/core/src/repowise/core/ingestion/extractors/heritage/cpp.py+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/cpp.py@@ -46,6 +46,14 @@ def _extract_cpp_heritage(text = node_text(base, src).strip()for prefix in ("public", "protected", "private", "virtual"):text = text.removeprefix(prefix).strip()+ # ``class Combined : public Bases...`` — variadic pack+ # expansion. Strip the trailing ``...`` so the bare base+ # name still emits a (one-to-many, low-confidence)+ # heritage edge instead of being dropped.+ text = text.removesuffix("...").strip()+ # ``: boost::noncopyable`` and similar mixins — keep the+ # bare name; downstream callers don't currently distinguish+ # mixin bases from real ones.bare = text.split("::")[-1].strip()if not bare:continuediff --git a/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/__init__.py b/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/__init__.pyindex 1df820b3f..c4baf6723 100644--- a/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/__init__.py+++ b/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/__init__.py@@ -25,6 +25,7 @@ from collections.abc import Callablefrom typing import TYPE_CHECKINGfrom ...models import FileInfo, Symbol+from .cpp_macros import cpp_macro_synthetic_symbolsfrom .csharp_mvvm import csharp_synthetic_symbolsfrom .java_records import java_record_synthetic_symbolsfrom .jvm_codegen import jvm_codegen_synthetic_symbols@@ -48,6 +49,8 @@ _SYNTHETIC_PROVIDERS: dict[str, list[_Provider]] = {jvm_codegen_synthetic_symbols,],"kotlin": [kotlin_synthetic_symbols],+ "cpp": [cpp_macro_synthetic_symbols],+ "c": [cpp_macro_synthetic_symbols],}diff --git a/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/cpp_macros.py b/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/cpp_macros.pynew file mode 100644index 000000000..c17c2eda6--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/cpp_macros.py@@ -0,0 +1,165 @@+"""C/C++ registration-macro symbol synthesis.++A swathe of C++ idioms wire functions and types into a runtime registry+at static-initialisation time. The compiler emits no call edge, so the+referenced symbols look orphaned to a static analyzer that only sees+the tree-sitter AST:++ - ``PYBIND11_MODULE(name, m) { m.def("foo", &foo); }`` — Python+ binding entry point.+ - ``BOOST_PYTHON_MODULE(name) { ... }`` — Boost.Python equivalent.+ - ``DEFINE_string(NAME, DEFAULT, HELP)`` / ``ABSL_FLAG(T, NAME, ...)``+ — gflags / Abseil flag definitions which materialise a+ ``FLAGS_NAME`` global at static-init time.++This module emits the *symbols* those macros materialise so the rest of+the graph treats them like the parser had seen them in source. File-+level reachability (e.g. marking the whole TU as an entry point because+``PYBIND11_MODULE`` is present) lives in :mod:`graph_warmups` — it can+mutate graph node attributes; the synthesis pass can only add Symbol+records the parser appends to its symbol list.+"""++from __future__ import annotations++import re+from typing import TYPE_CHECKING++from ...models import FileInfo, Symbol+from ._helpers import build_synthetic_symbol++if TYPE_CHECKING:+ from tree_sitter import Node+++# Regex catalog — every match emits one synthetic symbol.+#+# Each entry: (pattern, kind, name_group, parent, signature_template).+# We use plain regex instead of walking the AST: most of these macros+# look like function calls to tree-sitter (``call_expression`` whose+# function is an ``identifier``), and traversing the AST adds nothing+# over a precompiled regex on the source text.++_PYBIND11_MODULE_RE = re.compile(+ r"\bPYBIND11_MODULE\s*\(\s*([A-Za-z_]\w*)\s*,",+)+_BOOST_PY_MODULE_RE = re.compile(+ r"\bBOOST_PYTHON_MODULE(?:_INIT)?\s*\(\s*([A-Za-z_]\w*)\s*\)",+)+_NAPI_MODULE_RE = re.compile(+ r"\bNAPI_MODULE\s*\(\s*([A-Za-z_]\w*)\s*,",+)++# gflags: DEFINE_bool / DEFINE_string / DEFINE_int32 / DEFINE_double / …+_GFLAGS_DEFINE_RE = re.compile(+ r"\bDEFINE_(?:bool|string|int32|int64|uint32|uint64|double|float)\s*"+ r"\(\s*([A-Za-z_]\w*)\s*,",+)+# Abseil: ABSL_FLAG(type, name, default, help)+_ABSL_FLAG_RE = re.compile(+ r"\bABSL_FLAG\s*\(\s*[^,]+,\s*([A-Za-z_]\w*)\s*,",+)+++# Tokens that, if absent from the source, mean none of the patterns+# above can match — cheap reject path before running every regex.+_FAST_REJECT_TOKENS = (+ "PYBIND11_MODULE",+ "BOOST_PYTHON_MODULE",+ "NAPI_MODULE",+ "DEFINE_",+ "ABSL_FLAG",+)+++def _line_of(src: str, offset: int) -> int:+ """Return 1-based line number for a byte offset within ``src``."""+ return src.count("\n", 0, offset) + 1+++def cpp_macro_synthetic_symbols(+ root: "Node", src: str, file_info: FileInfo+) -> list[Symbol]:+ """Emit synthetic symbols for static-init registration macros."""+ # Cheap reject — vast majority of C/C++ TUs don't use any of these.+ if not any(tok in src for tok in _FAST_REJECT_TOKENS):+ return []++ out: list[Symbol] = []++ for m in _PYBIND11_MODULE_RE.finditer(src):+ name = m.group(1)+ line = _line_of(src, m.start())+ out.append(+ build_synthetic_symbol(+ name=name,+ kind="module",+ signature=f"PYBIND11_MODULE({name}, ...)",+ start_line=line,+ end_line=line,+ file_info=file_info,+ parent_name=None,+ )+ )++ for m in _BOOST_PY_MODULE_RE.finditer(src):+ name = m.group(1)+ line = _line_of(src, m.start())+ out.append(+ build_synthetic_symbol(+ name=name,+ kind="module",+ signature=f"BOOST_PYTHON_MODULE({name})",+ start_line=line,+ end_line=line,+ file_info=file_info,+ parent_name=None,+ )+ )++ for m in _NAPI_MODULE_RE.finditer(src):+ name = m.group(1)+ line = _line_of(src, m.start())+ out.append(+ build_synthetic_symbol(+ name=name,+ kind="module",+ signature=f"NAPI_MODULE({name}, ...)",+ start_line=line,+ end_line=line,+ file_info=file_info,+ parent_name=None,+ )+ )++ for m in _GFLAGS_DEFINE_RE.finditer(src):+ flag_name = m.group(1)+ line = _line_of(src, m.start())+ out.append(+ build_synthetic_symbol(+ name=f"FLAGS_{flag_name}",+ kind="variable",+ signature=f"DEFINE_*({flag_name}, …)",+ start_line=line,+ end_line=line,+ file_info=file_info,+ parent_name=None,+ )+ )++ for m in _ABSL_FLAG_RE.finditer(src):+ flag_name = m.group(1)+ line = _line_of(src, m.start())+ out.append(+ build_synthetic_symbol(+ name=f"FLAGS_{flag_name}",+ kind="variable",+ signature=f"ABSL_FLAG(…, {flag_name}, …)",+ start_line=line,+ end_line=line,+ file_info=file_info,+ parent_name=None,+ )+ )++ return outdiff --git a/packages/core/src/repowise/core/ingestion/graph_warmups.py b/packages/core/src/repowise/core/ingestion/graph_warmups.pyindex c60cbfe20..75ce458b8 100644--- a/packages/core/src/repowise/core/ingestion/graph_warmups.py+++ b/packages/core/src/repowise/core/ingestion/graph_warmups.py@@ -110,41 +110,107 @@ def _warmup_cpp(ctx: "ResolverContext") -> None:against the workspace's discovered macro set. This keeps the parserstateless w.r.t. the workspace while still surfacing the rightvisibility on the graph nodes the dead-code analyzer reads.++ A second pass scans each translation unit for *registration-macro*+ markers — ``PYBIND11_MODULE``, ``REGISTER_OP``,+ ``RCLCPP_COMPONENTS_REGISTER_NODE``, ``BOOST_CLASS_EXPORT``,+ ``LLVMFuzzerTestOneInput``, ``Q_OBJECT``, ``__attribute__((constructor))``,+ ``[[gnu::retain]]`` / ``[[gnu::used]]`` and the like — and stamps+ ``is_entry_point=True`` on the file node. These macros wire the file+ into a runtime registry at static-init time, so a static call edge+ will never exist; without this rescue, every such TU reads as+ ``unreachable_file``."""from .resolvers.cpp_workspace import get_or_build_cpp_indexindex = get_or_build_cpp_index(ctx)graph = getattr(ctx, "graph", None)- if graph is None or not index.project_export_macros:+ if graph is None:returnmacros = index.project_export_macrosparsed_files = getattr(ctx, "parsed_files", None) or {}++ if macros:+ for path, parsed in parsed_files.items():+ if not path.endswith((".h", ".hpp", ".hxx", ".hh", ".h++", ".inc",+ ".c", ".cc", ".cpp", ".cxx", ".c++")):+ continue+ for sym in parsed.symbols:+ sig = sym.signature or ""+ if not sig:+ continue+ # Check macro presence as a token — cheap substring with a+ # word-boundary check to avoid false matches inside other+ # identifiers.+ for macro in macros:+ idx = sig.find(macro)+ if idx == -1:+ continue+ before_ok = idx == 0 or not (sig[idx - 1].isalnum() or sig[idx - 1] == "_")+ end = idx + len(macro)+ after_ok = end >= len(sig) or not (sig[end].isalnum() or sig[end] == "_")+ if before_ok and after_ok:+ node = graph.nodes.get(sym.id)+ if node is not None:+ node["is_exported_symbol"] = True+ if node.get("visibility") == "private":+ node["visibility"] = "public"+ break++ _mark_cpp_entry_point_files(parsed_files, graph)+++# Tokens whose presence means the surrounding TU wires itself into a+# runtime registry at static-init time. Every match marks the file node+# as an entry point so the dead-code analyzer treats it as live.+_CPP_ENTRY_MARKERS = (+ "PYBIND11_MODULE",+ "BOOST_PYTHON_MODULE",+ "NAPI_MODULE",+ "REGISTER_OP",+ "REGISTER_KERNEL_BUILDER",+ "BOOST_CLASS_EXPORT",+ "PLUGINLIB_EXPORT_CLASS",+ "RCLCPP_COMPONENTS_REGISTER_NODE",+ "LLVMFuzzerTestOneInput",+ "Q_OBJECT",+ "Q_GADGET",+ "Q_NAMESPACE",+ "QML_ELEMENT",+ "QML_NAMED_ELEMENT",+ "__attribute__((constructor))",+ "__attribute__((used))",+ "[[gnu::retain]]",+ "[[gnu::used]]",+ "JNI_OnLoad",+)+++def _mark_cpp_entry_point_files(parsed_files: dict, graph: Any) -> None:+ """Stamp ``is_entry_point=True`` on TU file nodes matching an entry marker."""for path, parsed in parsed_files.items():- if not path.endswith((".h", ".hpp", ".hxx", ".hh", ".h++", ".inc",- ".c", ".cc", ".cpp", ".cxx", ".c++")):+ lang = parsed.file_info.language+ if lang not in ("cpp", "c"):continue- for sym in parsed.symbols:- sig = sym.signature or ""- if not sig:+ # The parser already loaded the source; reuse it via the+ # ParsedFile (avoids a second filesystem read).+ src = getattr(parsed, "source", None) or getattr(parsed.file_info, "source", None)+ if src is None:+ # ParsedFile doesn't always carry the source — fall back to disk.+ abs_path = getattr(parsed.file_info, "abs_path", None)+ if not abs_path:continue- # Check macro presence as a token — cheap substring with a- # word-boundary check to avoid false matches inside other- # identifiers.- for macro in macros:- idx = sig.find(macro)- if idx == -1:- continue- before_ok = idx == 0 or not (sig[idx - 1].isalnum() or sig[idx - 1] == "_")- end = idx + len(macro)- after_ok = end >= len(sig) or not (sig[end].isalnum() or sig[end] == "_")- if before_ok and after_ok:- node = graph.nodes.get(sym.id)- if node is not None:- node["is_exported_symbol"] = True- if node.get("visibility") == "private":- node["visibility"] = "public"- break+ try:+ with open(abs_path, "r", encoding="utf-8", errors="replace") as f:+ src = f.read()+ except OSError:+ continue+ if not any(tok in src for tok in _CPP_ENTRY_MARKERS):+ continue+ node = graph.nodes.get(path)+ if node is not None:+ node["is_entry_point"] = Truedef _warmup_dotnet(ctx: "ResolverContext") -> None:diff --git a/packages/core/src/repowise/core/ingestion/language_configs.py b/packages/core/src/repowise/core/ingestion/language_configs.pyindex 22b8b6a9c..87da837e1 100644--- a/packages/core/src/repowise/core/ingestion/language_configs.py+++ b/packages/core/src/repowise/core/ingestion/language_configs.py@@ -177,7 +177,8 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {"type_definition": "struct", # typedef struct { ... } Name;"preproc_def": "variable", # #define MACRO value"preproc_function_def": "function", # #define MACRO(x) ...- "declaration": "function", # forward declarations+ "declaration": "function", # forward declarations + dtor decls+ "alias_declaration": "type_alias", # using X = Y;},import_node_types=["preproc_include"],export_node_types=[],diff --git a/packages/core/src/repowise/core/ingestion/queries/cpp.scm b/packages/core/src/repowise/core/ingestion/queries/cpp.scmindex 5cae658cd..74a1bd733 100644--- a/packages/core/src/repowise/core/ingestion/queries/cpp.scm+++ b/packages/core/src/repowise/core/ingestion/queries/cpp.scm@@ -127,6 +127,39 @@)) @symbol.def+; Destructor declaration inside a class body: ~Foo();+(declaration+ declarator: (function_declarator+ declarator: (destructor_name) @symbol.name+ parameters: (parameter_list) @symbol.params+ )+) @symbol.def++; Destructor definition out-of-class: Foo::~Foo() { ... }+(function_definition+ declarator: (function_declarator+ declarator: (qualified_identifier+ name: (destructor_name) @symbol.name+ )+ parameters: (parameter_list) @symbol.params+ )+) @symbol.def++; Operator-overload definition outside class: bool Foo::operator==(const Foo&) { }+(function_definition+ declarator: (function_declarator+ declarator: (qualified_identifier+ name: (operator_name) @symbol.name+ )+ parameters: (parameter_list) @symbol.params+ )+) @symbol.def++; using StringMap = std::map<std::string, int>;+(alias_declaration+ name: (type_identifier) @symbol.name+) @symbol.def+; ---------------------------------------------------------------------------; Imports (#include directives); ---------------------------------------------------------------------------@@ -199,3 +232,11 @@; Function return type: Widget * make(...)(function_definitiontype: (_) @param.type)++; Template type argument: std::vector<Widget> — captures ``Widget``+; (the head extractor strips ``std::*`` container wrappers before+; resolving). Without this, every header type used only as a template+; parameter reads as an unused export.+(template_argument_list+ (type_descriptor+ type: (_) @param.type))diff --git a/packages/core/src/repowise/core/ingestion/type_ref_resolution.py b/packages/core/src/repowise/core/ingestion/type_ref_resolution.pyindex efe95d974..b729577a1 100644--- a/packages/core/src/repowise/core/ingestion/type_ref_resolution.py+++ b/packages/core/src/repowise/core/ingestion/type_ref_resolution.py@@ -280,6 +280,33 @@ def _find_go_type_file(# Strategy: C / C++# ---------------------------------------------------------------------------+# ``std::vector`` / ``std::optional`` / ``std::shared_ptr`` — when the+# parser captures these as type-ref heads (no unwrap path through the+# grammar caught the inner T), the lookup is guaranteed to find nothing+# useful. Filter them so we don't waste a per-ref graph walk. Same idea+# as the TS/Rust builtin filters above.+_CPP_STL_HEAD_NAMES: frozenset[str] = frozenset({+ "vector", "array", "deque", "list", "forward_list",+ "set", "multiset", "map", "multimap",+ "unordered_set", "unordered_multiset",+ "unordered_map", "unordered_multimap",+ "stack", "queue", "priority_queue", "span",+ "string", "string_view", "wstring", "u16string", "u32string",+ "pair", "tuple",+ "optional", "variant", "any", "bitset",+ "shared_ptr", "unique_ptr", "weak_ptr",+ "function", "reference_wrapper", "atomic", "atomic_ref",+ "future", "promise", "shared_future",+ "thread", "mutex", "lock_guard", "unique_lock", "shared_lock",+ "condition_variable", "condition_variable_any",+ "chrono", "duration", "time_point",+ "initializer_list", "common_type", "decay", "remove_reference",+ "enable_if", "is_same", "conditional",+ # Smart casts / trait helpers+ "make_shared", "make_unique", "make_pair", "make_tuple",+})++def _resolve_c_type_refs(parsed: ParsedFile,ctx: "ResolverContext",@@ -295,6 +322,18 @@ def _resolve_c_type_refs(bare type name against the files this translation unit includes, fallingback to a unique global stem match, and emit a ``type_use`` edge so theunused-export pass sees the header type as used.++ C++ extensions over the bare C strategy:+ * ``std::*`` container heads (``vector``, ``optional``, ``map`` …)+ are filtered up-front — the inner ``T`` template argument is+ captured separately by the template_argument_list query and+ resolves on its own. The container head will never name a user+ type.+ * The same-target sibling file set from+ :class:`CppWorkspaceIndex` is considered alongside ``#include``d+ files, so a type declared in one TU and used in a sibling TU+ of the same CMake / Bazel target resolves even when no header+ wires them together."""if not parsed.type_refs:return 0@@ -302,19 +341,34 @@ def _resolve_c_type_refs(from .parser_helpers import _C_BUILTIN_TYPESfrom_path = parsed.file_info.path+ is_cpp = parsed.file_info.language == "cpp"import_targets: set[str] = set()for imp in parsed.imports:if imp.resolved_file and not imp.resolved_file.startswith("external:"):import_targets.add(imp.resolved_file)+ sibling_files: set[str] = set()+ if is_cpp:+ try:+ from .resolvers.cpp_workspace import get_or_build_cpp_index++ cpp_index = get_or_build_cpp_index(ctx)+ sibling_files = set(cpp_index.siblings_in_targets(from_path))+ except Exception:+ sibling_files = set()+emitted = 0seen_targets: set[tuple[str, str]] = set()for ref in parsed.type_refs:name = ref.type_nameif not name or name in _C_BUILTIN_TYPES:continue- target = _find_c_type_file(name, from_path, import_targets, ctx, graph)+ if is_cpp and name in _CPP_STL_HEAD_NAMES:+ continue+ target = _find_c_type_file(+ name, from_path, import_targets, sibling_files, ctx, graph+ )if target is None or target == from_path:continueif (name, target) in seen_targets:@@ -330,10 +384,16 @@ def _find_c_type_file(type_name: str,from_path: str,import_targets: set[str],+ sibling_files: set[str],ctx: "ResolverContext",graph: "nx.DiGraph",) -> str | None:- """Find the file defining *type_name*, preferring ``#include``d headers."""+ """Find the file defining *type_name*, preferring ``#include``d headers.++ Falls back to *sibling_files* (same workspace target — usually a+ sibling ``.cc`` declaring an internal class that another ``.cc`` in+ the same target uses by value), then the global stem map.+ """for imp_file in import_targets:if not graph.has_node(imp_file):continue@@ -342,6 +402,14 @@ def _find_c_type_file(if nd.get("node_type") == "symbol" and nd.get("name") == type_name:return imp_file+ for sib in sibling_files:+ if sib == from_path or not graph.has_node(sib):+ continue+ for succ in graph.successors(sib):+ nd = graph.nodes.get(succ, {})+ if nd.get("node_type") == "symbol" and nd.get("name") == type_name:+ return sib+candidates = ctx.stem_map.get(type_name.lower(), [])if len(candidates) == 1 and candidates[0] != from_path:if graph.has_node(candidates[0]):diff --git a/tests/unit/ingestion/test_cpp_extractors.py b/tests/unit/ingestion/test_cpp_extractors.pyindex b32a11037..ae1d779f6 100644--- a/tests/unit/ingestion/test_cpp_extractors.py+++ b/tests/unit/ingestion/test_cpp_extractors.py@@ -140,3 +140,62 @@ class StreamWrapper : public IO {rels = {(r.parent_name, r.kind) for r in result.heritage}assert ("IO", "extends") in relsassert ("IO", "implements") not in rels++ def test_variadic_base_pack_emits_edge(self, parser: ASTParser) -> None:+ """``class C : public Bases...`` — trailing ``...`` stripped, edge emitted."""+ src = b"""\+template<typename... Bases>+class Combined : public Bases... {};+"""+ result = parser.parse_file(_file(), src)+ rels = {(r.child_name, r.parent_name) for r in result.heritage}+ assert ("Combined", "Bases") in rels+++class TestCppPhase2Captures:+ """Symbol-graph hardening (Phase 2): new tree-sitter captures."""++ def test_destructor_declaration_extracted(self, parser: ASTParser) -> None:+ """``~Foo();`` in a class body lands as a symbol named ``~Foo``."""+ src = b"""\+class Foo {+public:+ ~Foo();+};+"""+ result = parser.parse_file(_file(), src)+ names = {s.name for s in result.symbols}+ assert "~Foo" in names++ def test_destructor_definition_qualified(self, parser: ASTParser) -> None:+ """``Foo::~Foo() {}`` out-of-class definition lands too."""+ src = b"""\+class Foo {};+Foo::~Foo() {}+"""+ result = parser.parse_file(_file(), src)+ dtors = [s for s in result.symbols if s.name == "~Foo"]+ assert dtors, "expected at least one ~Foo definition symbol"++ def test_alias_declaration_extracted(self, parser: ASTParser) -> None:+ """``using StringMap = std::map<std::string, int>;`` → type_alias."""+ src = b"""\+#include <map>+#include <string>+using StringMap = std::map<std::string, int>;+"""+ result = parser.parse_file(_file(), src)+ by_name = {s.name: s for s in result.symbols}+ assert "StringMap" in by_name+ assert by_name["StringMap"].kind == "type_alias"++ def test_template_argument_type_captured_as_ref(self, parser: ASTParser) -> None:+ """``std::vector<Widget>`` in a param type captures ``Widget``."""+ src = b"""\+#include <vector>+class Widget;+void Consume(const std::vector<Widget>& xs);+"""+ result = parser.parse_file(_file(), src)+ ref_names = {r.type_name for r in result.type_refs}+ assert "Widget" in ref_namesdiff --git a/tests/unit/ingestion/test_cpp_macros_synthesis.py b/tests/unit/ingestion/test_cpp_macros_synthesis.pynew file mode 100644index 000000000..51fa342f9--- /dev/null+++ b/tests/unit/ingestion/test_cpp_macros_synthesis.py@@ -0,0 +1,91 @@+"""Unit tests for C/C++ registration-macro synthetic-symbol synthesis."""++from __future__ import annotations++from datetime import datetime+from pathlib import Path++from repowise.core.ingestion.models import FileInfo+from repowise.core.ingestion.parser import parse_file+++def _fi(rel: str, abs_: Path, lang: str = "cpp") -> FileInfo:+ return FileInfo(+ path=rel,+ abs_path=str(abs_),+ language=lang,+ size_bytes=abs_.stat().st_size,+ git_hash="",+ last_modified=datetime.now(),+ is_test=False,+ is_config=False,+ is_api_contract=False,+ is_entry_point=False,+ )+++def _parse(tmp_path: Path, name: str, src: str, lang: str = "cpp"):+ f = tmp_path / name+ f.write_text(src)+ return parse_file(_fi(name, f, lang), src.encode("utf-8"))+++class TestCppMacroSynthesis:+ def test_pybind11_module_emits_synthetic_module_symbol(+ self, tmp_path: Path+ ) -> None:+ src = """\+#include <pybind11/pybind11.h>+namespace py = pybind11;+int add(int a, int b) { return a + b; }+PYBIND11_MODULE(my_ext, m) {+ m.def("add", &add);+}+"""+ pf = _parse(tmp_path, "binding.cc", src)+ by_name = {s.name: s for s in pf.symbols}+ assert "my_ext" in by_name+ assert by_name["my_ext"].kind == "module"++ def test_boost_python_module_emits_synthetic_symbol(self, tmp_path: Path) -> None:+ src = """\+#include <boost/python.hpp>+BOOST_PYTHON_MODULE(legacy_ext) {+}+"""+ pf = _parse(tmp_path, "boost_binding.cc", src)+ names = {s.name for s in pf.symbols}+ assert "legacy_ext" in names++ def test_gflags_define_emits_FLAGS_prefixed_symbol(self, tmp_path: Path) -> None:+ src = """\+#include <gflags/gflags.h>+DEFINE_string(host, "localhost", "the host");+DEFINE_int32(port, 8080, "the port");+"""+ pf = _parse(tmp_path, "flags.cc", src)+ names = {s.name for s in pf.symbols}+ assert "FLAGS_host" in names+ assert "FLAGS_port" in names++ def test_absl_flag_emits_FLAGS_prefixed_symbol(self, tmp_path: Path) -> None:+ src = """\+#include <absl/flags/flag.h>+ABSL_FLAG(std::string, host, "localhost", "the host");+"""+ pf = _parse(tmp_path, "absl_flags.cc", src)+ names = {s.name for s in pf.symbols}+ assert "FLAGS_host" in names++ def test_no_macros_no_synthetic_symbols(self, tmp_path: Path) -> None:+ """Cheap reject path: source without any macro token emits nothing."""+ src = """\+int main() { return 0; }+"""+ pf = _parse(tmp_path, "plain.cc", src)+ # Only the real ``main`` symbol — no synthetic adds.+ synth_names = {s.name for s in pf.symbols if "PYBIND11" in (s.signature or "")+ or "BOOST_PYTHON" in (s.signature or "")+ or "ABSL_FLAG" in (s.signature or "")+ or "DEFINE_*" in (s.signature or "")}+ assert synth_names == set()