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(ingestion): parse C++ export-macro forward declarations (#1913)

Excelius27e270789268
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index a38e9dac2..062dd20a5 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -25,7 +25,12 @@ Capture-name conventions (shared across ALL .scm files):
from __future__ import annotations
import re
+import unicodedata
+from bisect import bisect_left
+from collections import deque
from collections.abc import Iterable
+from dataclasses import dataclass
+from enum import Enum, auto
from functools import cache
from pathlib import Path
@@ -172,6 +177,502 @@ def _call_receiver_from_node(node: Node, src: str) -> CallReceiver | None:
# as a symbol today. If a union capture is ever added, add it here too, or a
# bodiless ``union U;`` goes back to reading as a definition.
_CPP_TYPE_SPECIFIER_NODES = frozenset({"class_specifier", "struct_specifier", "enum_specifier"})
+_CPP_EXPORT_FORWARD_DECLARATION_NODES = frozenset({"declaration", "field_declaration"})
+
+_CPP_PREPROC_CONDITIONAL_NODES = frozenset(
+ {"preproc_if", "preproc_ifdef", "preproc_ifndef", "preproc_elif", "preproc_else"}
+)
+_CPP_PREPROC_ALTERNATIVE_NODES = frozenset({"preproc_elif", "preproc_else"})
+_CPP_LINE_SPLICE_RE = re.compile(r"\\(?:\r\n?|\n)")
+_CPP_PREPROC_COMMENT_RE = re.compile(r"/\*.*?\*/|//[^\r\n]*", re.DOTALL)
+_CPP_MACRO_STACK_RE = re.compile(r'\b(push_macro|pop_macro)\s*\(\s*"([^"]+)"\s*\)')
+_CPP_UNIVERSAL_CHARACTER_NAME_RE = re.compile(r"\\(?:u([0-9A-Fa-f]{4})|U([0-9A-Fa-f]{8}))")
+_CPP_IDENTIFIER_TOKEN_RE = re.compile(r"(?:[^\W\d]|\$)[\w$]*")
+_CPP_INCLUDE_LIKE_DIRECTIVES = frozenset({"include_next", "import"})
+
+
+class _CppMacroState(Enum):
+ EMPTY_OBJECT = auto()
+ NOT_EMPTY_OBJECT = auto()
+ UNDEFINED = auto()
+ UNKNOWN = auto()
+
+
+class _CppMacroAction(Enum):
+ DEFINE_EMPTY = auto()
+ DEFINE_OTHER = auto()
+ UNDEFINE = auto()
+ PUSH = auto()
+ POP = auto()
+ UNKNOWN = auto()
+
+
+@dataclass(frozen=True)
+class _CppMacroEvent:
+ position: int
+ state: _CppMacroState
+ definition: Node | None = None
+ branch_path: tuple[int, ...] = ()
+
+
+@dataclass(frozen=True)
+class _CppMacroOperation:
+ position: int
+ action: _CppMacroAction
+ name: str
+ node: Node
+ definition: Node | None = None
+
+
+@dataclass(frozen=True)
+class _CppMacroStackEntry:
+ event: _CppMacroEvent | None
+ branch_path: tuple[int, ...]
+
+
+@dataclass(frozen=True)
+class _CppMacroFacts:
+ events: dict[str, tuple[_CppMacroEvent, ...]]
+ barriers: tuple[int, ...]
+
+ def empty_definition_at(self, name: str, declaration: Node) -> Node | None:
+ """Prove that *name* is an empty object macro at *declaration*."""
+ events = self.events.get(name, ())
+ event_index = (
+ bisect_left(events, declaration.start_byte, key=lambda event: event.position) - 1
+ )
+ active_event = events[event_index] if event_index >= 0 else None
+ if (
+ active_event is None
+ or active_event.state is not _CppMacroState.EMPTY_OBJECT
+ or active_event.definition is None
+ ):
+ return None
+
+ declaration_branch = _cpp_preproc_branch_path(declaration)
+ event_branch = active_event.branch_path
+ definition_branch = _cpp_preproc_branch_path(active_event.definition)
+ if declaration_branch[: len(event_branch)] != event_branch:
+ return None
+ if declaration_branch[: len(definition_branch)] != definition_branch:
+ return None
+
+ barrier_index = bisect_left(self.barriers, declaration.start_byte) - 1
+ latest_barrier = self.barriers[barrier_index] if barrier_index >= 0 else None
+ if latest_barrier is not None and latest_barrier > active_event.position:
+ return None
+ return active_event.definition
+
+
+@dataclass(frozen=True)
+class _CppExportType:
+ range_node: Node
+ name: str
+ is_forward_declaration: bool
+
+
+def _cpp_normalize_preproc_text(text: str) -> str:
+ """Apply the preprocessing transforms needed for directive arguments."""
+ without_splices = _CPP_LINE_SPLICE_RE.sub("", text)
+ return _CPP_PREPROC_COMMENT_RE.sub(" ", without_splices)
+
+
+def _cpp_preproc_call_parts(text: str) -> tuple[str | None, str]:
+ """Return a generic preprocessing call's directive and normalized argument."""
+ normalized = _cpp_normalize_preproc_text(text).strip()
+ match = re.match(r"(?:#|%:)[^\S\r\n]*([A-Za-z_]\w*)", normalized)
+ if match is None:
+ return None, ""
+ return match.group(1), normalized[match.end() :].lstrip()
+
+
+def _cpp_identifier_continues(char: str) -> bool:
+ """Whether *char* can continue a C++ identifier in supported grammars."""
+ return char in {"_", "$", "\\"} or f"a{char}".isidentifier()
+
+
+def _cpp_normalize_identifier(text: str) -> str:
+ """Normalize literal and universal-character-name identifier spellings."""
+
+ def replace_ucn(match: re.Match[str]) -> str:
+ digits = match.group(1) or match.group(2)
+ try:
+ codepoint = int(digits, 16)
+ if 0xD800 <= codepoint <= 0xDFFF:
+ return match.group()
+ return chr(codepoint)
+ except ValueError:
+ return match.group()
+
+ decoded = _CPP_UNIVERSAL_CHARACTER_NAME_RE.sub(replace_ucn, text)
+ return unicodedata.normalize("NFC", decoded)
+
+
+def _cpp_known_macro_from_argument(
+ argument: str, known_names_by_length: tuple[str, ...]
+) -> str | None:
+ """Match the first preprocessing token against locally known macro names."""
+ normalized = _cpp_normalize_identifier(_cpp_normalize_preproc_text(argument)).lstrip()
+ for name in known_names_by_length:
+ if not normalized.startswith(name):
+ continue
+ remainder = normalized[len(name) :]
+ if not remainder or not _cpp_identifier_continues(remainder[0]):
+ return name
+ return None
+
+
+def _cpp_known_macros_in_text(text: str, known_names: set[str]) -> set[str]:
+ """Return locally defined macro identifiers referenced anywhere in *text*."""
+ normalized = _cpp_normalize_identifier(_cpp_normalize_preproc_text(text))
+ return {
+ match.group()
+ for match in _CPP_IDENTIFIER_TOKEN_RE.finditer(normalized)
+ if match.group() in known_names
+ }
+
+
+def _cpp_macro_stack_operation(text: str) -> tuple[str | None, str | None]:
+ """Return a push/pop operation and normalized target from pragma text."""
+ normalized = _cpp_normalize_preproc_text(text).replace(r"\"", '"')
+ operation_match = re.search(r"\b(push_macro|pop_macro)\b", normalized)
+ if operation_match is None:
+ return None, None
+ match = _CPP_MACRO_STACK_RE.search(normalized)
+ if match is None:
+ return operation_match.group(1), None
+ return match.group(1), _cpp_normalize_identifier(match.group(2))
+
+
+def _cpp_preproc_branch_path(node: Node) -> tuple[int, ...]:
+ """Return the effective C/C++ preprocessor branches around *node*."""
+ branch_ids: list[int] = []
+ covered_conditionals: set[int] = set()
+ ancestor = node.parent
+ while ancestor is not None:
+ if ancestor.type in _CPP_PREPROC_ALTERNATIVE_NODES:
+ # An ``else``/``elif`` is its own branch; do not also label its
+ # contents as belonging to the parent conditional's main branch.
+ if ancestor.id not in covered_conditionals:
+ branch_ids.append(ancestor.id)
+ parent = ancestor.parent
+ if parent is not None and parent.type in _CPP_PREPROC_CONDITIONAL_NODES:
+ covered_conditionals.add(parent.id)
+ elif (
+ ancestor.type in _CPP_PREPROC_CONDITIONAL_NODES
+ and ancestor.id not in covered_conditionals
+ ):
+ branch_ids.append(ancestor.id)
+ ancestor = ancestor.parent
+ branch_ids.reverse()
+ return tuple(branch_ids)
+
+
+def _build_cpp_macro_facts(matches: list[dict], src: str) -> _CppMacroFacts:
+ """Build the conservative, source-ordered macro facts used by C++ recovery."""
+ macro_definitions: dict[int, tuple[Node, str]] = {}
+ preproc_calls: dict[int, Node] = {}
+ include_nodes: dict[int, Node] = {}
+ call_sites: dict[int, tuple[Node, str]] = {}
+
+ for capture_dict in matches:
+ def_nodes = capture_dict.get("symbol.def", [])
+ name_nodes = capture_dict.get("symbol.name", [])
+ if (
+ def_nodes
+ and def_nodes[0].type in ("preproc_def", "preproc_function_def")
+ and name_nodes
+ ):
+ macro_node = def_nodes[0]
+ macro_name = _cpp_normalize_identifier(_node_text(name_nodes[0], src))
+ if macro_name:
+ macro_definitions[macro_node.id] = (macro_node, macro_name)
+
+ for node in capture_dict.get("symbol.cpp_preproc_call", []):
+ preproc_calls[node.id] = node
+ for node in capture_dict.get("symbol.cpp_macro_state_barrier", []):
+ include_nodes[node.id] = node
+
+ site_nodes = capture_dict.get("call.site", [])
+ target_nodes = capture_dict.get("call.target", [])
+ if site_nodes and target_nodes:
+ call_sites[site_nodes[0].id] = (site_nodes[0], _node_text(target_nodes[0], src))
+
+ known_names = {name for _, name in macro_definitions.values()}
+ known_names_by_length = tuple(sorted(known_names, key=len, reverse=True))
+
+ # A macro whose replacement contains a pragma stack operation is itself a
+ # state hazard when invoked. Resolve simple wrapper aliases transitively;
+ # anything more dynamic remains conservative at the invocation site.
+ hazard_targets: dict[str, set[str]] = {name: set() for name in known_names}
+ hazard_unknown: set[str] = set()
+ replacement_references: dict[str, set[str]] = {name: set() for name in known_names}
+ for macro_node, macro_name in macro_definitions.values():
+ value_node = macro_node.child_by_field_name("value")
+ replacement = _node_text(value_node, src) if value_node is not None else ""
+ replacement_operation, target = _cpp_macro_stack_operation(replacement)
+ if replacement_operation is not None:
+ if target in known_names:
+ hazard_targets[macro_name].add(target)
+ elif target is None:
+ hazard_unknown.add(macro_name)
+ replacement_references[macro_name].update(
+ _cpp_known_macros_in_text(replacement, known_names) - {macro_name}
+ )
+
+ alias_dependents: dict[str, set[str]] = {name: set() for name in known_names}
+ for macro_name, references in replacement_references.items():
+ for referenced_name in references:
+ alias_dependents[referenced_name].add(macro_name)
+
+ pending = deque(name for name in known_names if hazard_targets[name] or name in hazard_unknown)
+ queued = set(pending)
+ while pending:
+ referenced_name = pending.popleft()
+ queued.remove(referenced_name)
+ for macro_name in alias_dependents[referenced_name]:
+ inherited_targets = hazard_targets[referenced_name] - hazard_targets[macro_name]
+ inherited_unknown = (
+ referenced_name in hazard_unknown and macro_name not in hazard_unknown
+ )
+ if not inherited_targets and not inherited_unknown:
+ continue
+ hazard_targets[macro_name].update(inherited_targets)
+ if inherited_unknown:
+ hazard_unknown.add(macro_name)
+ if macro_name not in queued:
+ pending.append(macro_name)
+ queued.add(macro_name)
+
+ object_hazard_names = {
+ macro_name
+ for macro_node, macro_name in macro_definitions.values()
+ if macro_node.type == "preproc_def"
+ and (hazard_targets[macro_name] or macro_name in hazard_unknown)
+ }
+
+ # Object-like macros expand wherever their identifier token appears, not
+ # only as a standalone expression. Walk the existing tree only when a
+ # local definition proves that the name wraps a stack operation. An include
+ # is a barrier at its own position, but without preprocessing context it is
+ # not evidence that every later identifier is an imported wrapper.
+ possible_invocations: dict[int, Node] = {}
+ if object_hazard_names:
+ root = next(iter(macro_definitions.values()))[0]
+ while root.parent is not None:
+ root = root.parent
+ pending_nodes = [root]
+ while pending_nodes:
+ node = pending_nodes.pop()
+ if node.type in {"preproc_def", "preproc_function_def"}:
+ continue
+ if node.type == "identifier":
+ name = _cpp_normalize_identifier(_node_text(node, src))
+ if name in object_hazard_names:
+ possible_invocations[node.id] = node
+ pending_nodes.extend(node.children)
+
+ operations: list[_CppMacroOperation] = []
+ operation_keys: set[tuple[int, _CppMacroAction, str]] = set()
+ barriers = {node.start_byte for node in include_nodes.values()}
+
+ def add_operation(
+ node: Node,
+ action: _CppMacroAction,
+ name: str,
+ *,
+ definition: Node | None = None,
+ ) -> None:
+ key = (node.start_byte, action, name)
+ if key in operation_keys:
+ return
+ operation_keys.add(key)
+ operations.append(
+ _CppMacroOperation(
+ position=node.start_byte,
+ action=action,
+ name=name,
+ node=node,
+ definition=definition,
+ )
+ )
+
+ def add_stack_operation(node: Node, text: str, *, direct: bool) -> bool:
+ operation, target = _cpp_macro_stack_operation(text)
+ if operation is None:
+ return False
+ if target in known_names:
+ action = (
+ _CppMacroAction.PUSH
+ if direct and operation == "push_macro"
+ else _CppMacroAction.POP
+ if direct and operation == "pop_macro"
+ else _CppMacroAction.UNKNOWN
+ )
+ add_operation(node, action, target)
+ elif target is None:
+ barriers.add(node.start_byte)
+ return True
+
+ for macro_node, macro_name in macro_definitions.values():
+ is_empty_object = (
+ macro_node.type == "preproc_def" and macro_node.child_by_field_name("value") is None
+ )
+ add_operation(
+ macro_node,
+ (_CppMacroAction.DEFINE_EMPTY if is_empty_object else _CppMacroAction.DEFINE_OTHER),
+ macro_name,
+ definition=macro_node if is_empty_object else None,
+ )
+
+ for node in preproc_calls.values():
+ directive, argument = _cpp_preproc_call_parts(_node_text(node, src))
+ if directive in _CPP_INCLUDE_LIKE_DIRECTIVES:
+ barriers.add(node.start_byte)
+ elif directive == "undef":
+ target = _cpp_known_macro_from_argument(argument, known_names_by_length)
+ if target is not None:
+ add_operation(node, _CppMacroAction.UNDEFINE, target)
+ elif directive == "pragma":
+ add_stack_operation(node, argument, direct=True)
+
+ direct_pragma_call_ids: set[int] = set()
+ for node, target_text in call_sites.values():
+ normalized_target = _cpp_normalize_identifier(target_text)
+ if normalized_target in {"_Pragma", "__pragma"}:
+ direct_pragma_call_ids.add(node.id)
+ add_stack_operation(node, _node_text(node, src), direct=True)
+
+ def add_indirect_hazards(node: Node, text: str, target_text: str = "") -> None:
+ if add_stack_operation(node, text, direct=False):
+ return
+ target_name = _cpp_normalize_identifier(target_text)
+ if not target_name:
+ target_name = _cpp_known_macro_from_argument(text, known_names_by_length) or ""
+ referenced_names = _cpp_known_macros_in_text(text, known_names)
+ if target_name:
+ referenced_names.add(target_name)
+ affected_names = set().union(
+ *(hazard_targets.get(name, set()) for name in referenced_names)
+ )
+ for affected_name in affected_names:
+ add_operation(node, _CppMacroAction.UNKNOWN, affected_name)
+ if affected_names or referenced_names & hazard_unknown:
+ # The wrapper may push or pop even when its final macro value is
+ # conservatively represented as UNKNOWN. Taint the stack too, so
+ # a later direct pop cannot restore a stale local snapshot.
+ barriers.add(node.start_byte)
+
+ for node, target_text in call_sites.values():
+ if node.id not in direct_pragma_call_ids:
+ add_indirect_hazards(node, _node_text(node, src), target_text)
+
+ for node in possible_invocations.values():
+ add_indirect_hazards(node, _node_text(node, src))
+
+ operations.sort(key=lambda operation: operation.position)
+ sorted_barriers = sorted(barriers)
+ events: dict[str, list[_CppMacroEvent]] = {}
+ current: dict[str, _CppMacroEvent] = {}
+ stacks: dict[str, list[_CppMacroStackEntry]] = {}
+ barrier_index = 0
+
+ def append_event(operation: _CppMacroOperation, event: _CppMacroEvent) -> None:
+ events.setdefault(operation.name, []).append(event)
+ current[operation.name] = event
+
+ for operation in operations:
+ crossed_barrier = False
+ while (
+ barrier_index < len(sorted_barriers)
+ and sorted_barriers[barrier_index] < operation.position
+ ):
+ barrier_index += 1
+ crossed_barrier = True
+ if crossed_barrier:
+ # Includes and opaque pragma wrappers may mutate both the macro
+ # and its push/pop stack. A later local definition can establish
+ # the current value again, but only a later local push can
+ # establish a stack entry that is safe to restore.
+ current.clear()
+ stacks.clear()
+
+ branch_path = _cpp_preproc_branch_path(operation.node)
+ if operation.action in {
+ _CppMacroAction.DEFINE_EMPTY,
+ _CppMacroAction.DEFINE_OTHER,
+ _CppMacroAction.UNDEFINE,
+ _CppMacroAction.UNKNOWN,
+ }:
+ state = {
+ _CppMacroAction.DEFINE_EMPTY: _CppMacroState.EMPTY_OBJECT,
+ _CppMacroAction.DEFINE_OTHER: _CppMacroState.NOT_EMPTY_OBJECT,
+ _CppMacroAction.UNDEFINE: _CppMacroState.UNDEFINED,
+ _CppMacroAction.UNKNOWN: _CppMacroState.UNKNOWN,
+ }[operation.action]
+ append_event(
+ operation,
+ _CppMacroEvent(
+ position=operation.position,
+ state=state,
+ definition=operation.definition,
+ branch_path=branch_path,
+ ),
+ )
+ continue
+
+ if operation.action is _CppMacroAction.PUSH:
+ snapshot = current.get(operation.name)
+ if (
+ snapshot is not None
+ and branch_path[: len(snapshot.branch_path)] != snapshot.branch_path
+ ):
+ snapshot = None
+ stacks.setdefault(operation.name, []).append(
+ _CppMacroStackEntry(event=snapshot, branch_path=branch_path)
+ )
+ continue
+
+ stack = stacks.get(operation.name, [])
+ entry = stack.pop() if stack else None
+ current_event = current.get(operation.name)
+ if (
+ entry is None
+ and current_event is not None
+ and bisect_left(sorted_barriers, operation.position) == 0
+ and branch_path[: len(current_event.branch_path)] == current_event.branch_path
+ ):
+ restored = _CppMacroEvent(
+ position=operation.position,
+ state=current_event.state,
+ definition=current_event.definition,
+ branch_path=branch_path,
+ )
+ elif (
+ entry is None
+ or branch_path[: len(entry.branch_path)] != entry.branch_path
+ or entry.event is None
+ ):
+ restored = _CppMacroEvent(
+ position=operation.position,
+ state=_CppMacroState.UNKNOWN,
+ branch_path=branch_path,
+ )
+ if entry is not None:
+ stack.clear()
+ else:
+ restored = _CppMacroEvent(
+ position=operation.position,
+ state=entry.event.state,
+ definition=entry.event.definition,
+ branch_path=branch_path,
+ )
+ append_event(operation, restored)
+
+ return _CppMacroFacts(
+ events={name: tuple(name_events) for name, name_events in events.items()},
+ barriers=tuple(sorted(barriers)),
+ )
def _is_bodiless_cpp_type(language: str, node_type: str, def_node: Node) -> bool:
@@ -629,16 +1130,32 @@ class ASTParser:
if file_info.language in _TS_JS_LANGUAGES:
ts_deferred_exports = ts_deferred_export_names(src)
- # tree-sitter-cpp parses ``struct EXPORT Name { ... }`` as a
- # function_definition whose return type is ``struct EXPORT`` and whose
- # bare declarator is the real type name. cpp.scm marks those matches so
+ # tree-sitter-cpp parses ``struct EXPORT Name { ... }`` and
+ # ``struct EXPORT Name;`` with ``EXPORT`` as the specifier name and the
+ # real type name as a bare declarator. cpp.scm marks those matches so
# the specifier can keep its class/struct kind while the outer recovery
- # node acts as the type body for nested members.
- cpp_export_type_defs: dict[int, tuple[Node, str]] = {}
+ # node supplies the real range and nested-member context when present.
+ cpp_export_type_defs: dict[int, _CppExportType] = {}
cpp_export_type_parents: dict[int, str] = {}
+ cpp_export_type_capture_ids: set[int] = set()
cpp_export_macro_names: set[str] = set()
+ cpp_export_macro_def_ids: set[int] = set()
if file_info.language == "cpp":
- for capture_dict in matches:
+ cpp_export_matches = [
+ capture_dict
+ for capture_dict in matches
+ if capture_dict.get("symbol.cpp_export_type", [])
+ ]
+ has_forward_candidate = any(
+ capture_dict["symbol.cpp_export_type"][0].type
+ in _CPP_EXPORT_FORWARD_DECLARATION_NODES
+ for capture_dict in cpp_export_matches
+ )
+ cpp_macro_facts = (
+ _build_cpp_macro_facts(matches, src) if has_forward_candidate else None
+ )
+
+ for capture_dict in cpp_export_matches:
type_nodes = capture_dict.get("symbol.cpp_export_type", [])
def_nodes = capture_dict.get("symbol.def", [])
name_nodes = capture_dict.get("symbol.name", [])
@@ -648,10 +1165,46 @@ class ASTParser:
type_name = _node_text(name_nodes[0], src)
if not type_name:
continue
- outer_node = type_nodes[0]
- cpp_export_type_defs[def_nodes[0].id] = (outer_node, type_name)
- cpp_export_type_parents[outer_node.id] = type_name
- cpp_export_macro_names.update(_node_text(node, src) for node in macro_nodes)
+ capture_node = type_nodes[0]
+ is_forward_declaration = capture_node.type in _CPP_EXPORT_FORWARD_DECLARATION_NODES
+ range_node = capture_node
+ if (
+ is_forward_declaration
+ and capture_node.parent is not None
+ and capture_node.parent.type == "template_declaration"
+ ):
+ range_node = capture_node.parent
+ active_macro_def: Node | None = None
+ if is_forward_declaration:
+ if cpp_macro_facts is None:
+ continue
+ macro_names = {
+ _cpp_normalize_identifier(_node_text(node, src)) for node in macro_nodes
+ } - {""}
+ if len(macro_names) != 1:
+ continue
+ macro_name = next(iter(macro_names))
+ # A bodiless decorated type is syntactically identical to
+ # an ordinary ``struct Tag variable;`` declaration.
+ active_macro_def = cpp_macro_facts.empty_definition_at(macro_name, capture_node)
+ if active_macro_def is None:
+ continue
+ else:
+ # Body-form matches are unambiguous. Preserve #1896's
+ # name-based suppression across conditional definitions.
+ cpp_export_macro_names.update(
+ _cpp_normalize_identifier(_node_text(node, src)) for node in macro_nodes
+ )
+ cpp_export_type_defs[def_nodes[0].id] = _CppExportType(
+ range_node=range_node,
+ name=type_name,
+ is_forward_declaration=is_forward_declaration,
+ )
+ cpp_export_type_capture_ids.add(capture_node.id)
+ cpp_export_type_parents[capture_node.id] = type_name
+ cpp_export_type_parents[range_node.id] = type_name
+ if active_macro_def is not None:
+ cpp_export_macro_def_ids.add(active_macro_def.id)
cpp_export_type_parent_ids = frozenset(cpp_export_type_parents)
@@ -661,6 +1214,15 @@ class ASTParser:
params_nodes = capture_dict.get("symbol.params", [])
modifier_nodes = capture_dict.get("symbol.modifiers", [])
receiver_nodes = capture_dict.get("symbol.receiver", [])
+ captured_export_type_nodes = capture_dict.get("symbol.cpp_export_type", [])
+
+ if (
+ captured_export_type_nodes
+ and captured_export_type_nodes[0].id not in cpp_export_type_capture_ids
+ ):
+ # The query also sees ordinary ``struct Tag variable;`` forms;
+ # discard only the unsupported recovery match.
+ continue
if not def_nodes or not name_nodes:
continue
@@ -671,18 +1233,24 @@ class ASTParser:
continue
export_type = cpp_export_type_defs.get(def_node.id)
- if export_type is not None and name != export_type[1]:
+ if export_type is not None and name != export_type.name:
# The ordinary struct/class query sees the same specifier, but
# tree-sitter calls the export macro its name. Keep only the
# dedicated match whose name is the outer declarator.
continue
- if def_node.type == "preproc_def" and name in cpp_export_macro_names:
- # A locally stubbed empty export macro is declaration
- # scaffolding, not a runtime variable in the symbol graph.
+ if def_node.type == "preproc_def" and (
+ _cpp_normalize_identifier(name) in cpp_export_macro_names
+ or def_node.id in cpp_export_macro_def_ids
+ ):
+ # Body-form macros are suppressed by name as before #1901;
+ # ambiguous forward declarations suppress only the exact
+ # active definition that made recovery safe.
continue
start_line = def_node.start_point[0] + 1
+ if export_type is not None:
+ start_line = export_type.range_node.start_point[0] + 1
dedup_key = (start_line, name)
if dedup_key in seen:
continue
@@ -739,7 +1307,7 @@ class ASTParser:
# signature line.
end_line = def_node.end_point[0] + 1
if export_type is not None:
- end_line = export_type[0].end_point[0] + 1
+ end_line = export_type.range_node.end_point[0] + 1
if file_info.language == "dart" and node_type in (
"function_signature",
"getter_signature",
@@ -948,6 +1516,7 @@ class ASTParser:
is_exported_symbol=is_exported_symbol,
is_declaration=(
node_type in config.declaration_node_types
+ or (export_type is not None and export_type.is_forward_declaration)
or (
export_type is None
and _is_bodiless_cpp_type(file_info.language, node_type, def_node)
diff --git a/packages/core/src/repowise/core/ingestion/queries/cpp.scm b/packages/core/src/repowise/core/ingestion/queries/cpp.scm
index f61804d9f..6523b5de5 100644
--- a/packages/core/src/repowise/core/ingestion/queries/cpp.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/cpp.scm
@@ -31,6 +31,41 @@
body: (compound_statement)
) @symbol.cpp_export_type
+; Export-macro forward declarations have the same split-name shape, but the
+; real type name is the declaration's bare declarator and there is no body.
+(declaration
+ type: (class_specifier
+ name: (type_identifier) @symbol.cpp_export_macro
+ !body
+ ) @symbol.def
+ declarator: (identifier) @symbol.name
+) @symbol.cpp_export_type
+
+(declaration
+ type: (struct_specifier
+ name: (type_identifier) @symbol.cpp_export_macro
+ !body
+ ) @symbol.def
+ declarator: (identifier) @symbol.name
+) @symbol.cpp_export_type
+
+; The same forward-declaration shape uses field nodes inside a class body.
+(field_declaration
+ type: (class_specifier
+ name: (type_identifier) @symbol.cpp_export_macro
+ !body
+ ) @symbol.def
+ declarator: (field_identifier) @symbol.name
+) @symbol.cpp_export_type
+
+(field_declaration
+ type: (struct_specifier
+ name: (type_identifier) @symbol.cpp_export_macro
+ !body
+ ) @symbol.def
+ declarator: (field_identifier) @symbol.name
+) @symbol.cpp_export_type
+
; Function definition: ReturnType funcName(params) { body }
; The name is nested inside function_declarator
(function_definition
@@ -142,6 +177,14 @@
parameters: (preproc_params) @symbol.params
) @symbol.def
+; Generic preprocessor calls cover #undef and pragma-based macro restoration.
+(preproc_call) @symbol.cpp_preproc_call
+
+; Included files can redefine or undef any locally known macro. The one-file
+; parser cannot inspect that state transition, so includes form a conservative
+; recovery barrier until a later local definition establishes a new state.
+(preproc_include) @symbol.cpp_macro_state_barrier
+
; Forward declarations: void func(int x);
(declaration
declarator: (function_declarator
diff --git a/tests/unit/ingestion/parser/test_cpp.py b/tests/unit/ingestion/parser/test_cpp.py
index 2a200a454..6a4e6c378 100644
--- a/tests/unit/ingestion/parser/test_cpp.py
+++ b/tests/unit/ingestion/parser/test_cpp.py
@@ -6,6 +6,8 @@ Covers Python, TypeScript, Go, Rust, Java, C++ — one test class per language.
from __future__ import annotations
+import pytest
+
from repowise.core.ingestion.parser import ASTParser
from tests.unit.ingestion.parser._helpers import _make_file_info
@@ -68,6 +70,683 @@ struct PlainOptions {
"""
+CPP_EXPORT_MACRO_FORWARD_DECLARATIONS = b"""#define MYLIB_EXPORT
+#define UNRELATED_MACRO 1
+
+struct MYLIB_EXPORT Fwd;
+class MYLIB_EXPORT Fwd2;
+struct PlainFwd;
+class PlainFwd2;
+"""
+
+
+CPP_CONDITIONAL_EXPORT_MACRO_TYPE = b"""#if defined(_WIN32)
+#define COFFEE_EXPORT __declspec(dllexport)
+#else
+#define COFFEE_EXPORT
+#endif
+
+struct COFFEE_EXPORT Brewer {
+ void brew();
+};
+"""
+
+
+CPP_EXPORT_MACRO_FORWARD_DECLARATION_CONTEXTS = b"""#define API
+
+namespace sdk {
+struct API Namespaced;
+template <typename T> class API Generic;
+
+class Outer {
+ struct API Nested;
+};
+}
+"""
+
+
+SPACED_CPP_UNDEF_FORWARD_DECLARATIONS = (
+ b"""#define API
+# undef API
+struct API Fwd;
+""",
+ b"""#define API
+#\tundef API
+struct API Fwd;
+""",
+ b"""#define API
+ # \t undef API // trailing text is not part of the macro name
+struct API Fwd;
+""",
+)
+
+
+CPP_EXPORT_MACRO_LIFETIME_CASES = (
+ (
+ b"""#define API Existing
+#define API
+struct API Fwd;
+""",
+ {
+ ("API", "variable", 1, False),
+ ("Fwd", "struct", 3, True),
+ },
+ ),
+ (
+ b"""#define API
+#define API Existing
+struct API Fwd;
+""",
+ {
+ ("API", "variable", 1, False),
+ ("API", "variable", 2, False),
+ },
+ ),
+ (
+ b"""#define API
+#undef API
+#define API
+struct API Fwd;
+""",
+ {
+ ("API", "variable", 1, False),
+ ("Fwd", "struct", 4, True),
+ },
+ ),
+ (
+ b"""#define API(value)
+#define API
+struct API Fwd;
+""",
+ {
+ ("API", "function", 1, False),
+ ("Fwd", "struct", 3, True),
+ },
+ ),
+ (
+ b"""#define API
+#define API(value)
+struct API Fwd;
+""",
+ {
+ ("API", "variable", 1, False),
+ ("API", "function", 2, False),
+ },
+ ),
+ (
+ b"""#define API
+struct API Early;
+#undef API
+struct API Late;
+""",
+ {
+ ("Early", "struct", 2, True),
+ },
+ ),
+ (
+ b"""#define API
+#undef API_EXTRA
+struct API Fwd;
+""",
+ {
+ ("Fwd", "struct", 3, True),
+ },
+ ),
+ (
+ b"""#define API /* no-op on this platform */
+struct API Fwd;
+""",
+ {
+ ("Fwd", "struct", 2, True),
+ },
+ ),
+ (
+ b"""#define API
+struct API First;
+#define API
+class API Second;
+""",
+ {
+ ("First", "struct", 2, True),
+ ("Second", "class", 4, True),
+ },
+ ),
+)
+
+
+CPP_EXPORT_MACRO_BRANCH_CONTEXT_CASES = (
+ (
+ b"""#ifndef SDK_HEADER_H
+#define SDK_HEADER_H
+#define API
+struct API Fwd;
+#endif
+""",
+ {
+ ("SDK_HEADER_H", "variable", 2, False),
+ ("Fwd", "struct", 4, True),
+ },
+ ),
+ (
+ b"""#ifdef FEATURE
+#define API
+#if INNER
+struct API Fwd;
+#endif
+#endif
+""",
+ {
+ ("Fwd", "struct", 4, True),
+ },
+ ),
+ (
+ b"""#ifdef FEATURE
+#define API
+#else
+struct API Fwd;
+#endif
+""",
+ {
+ ("API", "variable", 2, False),
+ },
+ ),
+ (
+ b"""#ifdef FEATURE
+#define API
+#endif
+struct API Fwd;
+""",
+ {
+ ("API", "variable", 2, False),
+ },
+ ),
+ (
+ b"""#if FIRST
+#define API
+struct API First;
+#elif SECOND
+#define API
+struct API Second;
+#else
+#define API
+class API Last;
+#endif
+""",
+ {
+ ("First", "struct", 3, True),
+ ("Second", "struct", 6, True),
+ ("Last", "class", 9, True),
+ },
+ ),
+ (
+ b"""#if FIRST
+#define API
+struct API First;
+#elif SECOND
+struct API WrongSecond;
+#else
+class API WrongLast;
+#endif
+""",
+ {
+ ("First", "struct", 3, True),
+ },
+ ),
+)
+
+
+CPP_EXPORT_MACRO_STATE_BOUNDARY_CASES = (
+ (
+ b"""#define API
+#include "redefine.hpp"
+struct API Fwd;
+""",
+ {("API", "variable", 1, False)},
+ ),
+ (
+ b"""#define API
+#include PLATFORM_HEADER
+struct API Fwd;
+""",
+ {("API", "variable", 1, False)},
+ ),
+ (
+ b"""#define API
+#include_next <possibly_redefines.hpp>
+struct API Fwd;
+""",
+ {("API", "variable", 1, False)},
+ ),
+ (
+ b"""#define API
+#import "possibly_redefines.hpp"
+struct API Fwd;
+""",
+ {("API", "variable", 1, False)},
+ ),
+ (
+ b"""#define API Existing
+#pragma push_macro("API")
+#undef API
+#define API
+#pragma pop_macro("API")
+struct API Fwd;
+""",
+ {
+ ("API", "variable", 1, False),
+ ("API", "variable", 4, False),
+ },
+ ),
+ (
+ b"""#pragma push_macro("API")
+#define API
+#pragma pop_macro("API")
+struct API Fwd;
+""",
+ {("API", "variable", 2, False)},
+ ),
+ (
+ b'#define API Existing\n#pragma push_macro("API")\n#undef API\n#define API\n#pragma pop_ma\\\ncro("API")\nstruct API Fwd;\n',
+ {
+ ("API", "variable", 1, False),
+ ("API", "variable", 4, False),
+ },
+ ),
+ (
+ b'#define API Existing\n#pragma push_macro("API")\n#undef API\n#define API\n#pragma pop_macro("A\\\nPI")\nstruct API Fwd;\n',
+ {
+ ("API", "variable", 1, False),
+ ("API", "variable", 4, False),
+ },
+ ),
+ (
+ b"""#define API Existing
+_Pragma("push_macro(\"API\")")
+#undef API
+#define API
+_Pragma("pop_macro(\"API\")")
+struct API Fwd;
+""",
+ {
+ ("API", "variable", 1, False),
+ ("API", "variable", 4, False),
+ },
+ ),
+ (
+ b"""#define API Existing
+__pragma(push_macro("API"))
+#undef API
+#define API
+__pragma(pop_macro("API"))
+struct API Fwd;
+""",
+ {
+ ("API", "variable", 1, False),
+ ("API", "variable", 4, False),
+ },
+ ),
+ (
+ b"""#define API Existing
+#pragma push_macro("API")
+#undef API
+#define API
+#define RESTORE_API() _Pragma("pop_macro(\"API\")")
+RESTORE_API()
+struct API Fwd;
+""",
+ {
+ ("API", "variable", 1, False),
+ ("API", "variable", 4, False),
+ ("RESTORE_API", "function", 5, False),
+ },
+ ),
+ (
+ b"""#define API Existing
+#pragma push_macro("API")
+#undef API
+#define API
+#pragma push_macro("API")
+#define API ExistingAgain
+#define RESTORE_API() _Pragma("pop_macro(\"API\")")
+RESTORE_API()
+#pragma pop_macro("API")
+struct API Fwd;
+""",
+ {
+ ("API", "variable", 1, False),
+ ("API", "variable", 4, False),
+ ("API", "variable", 6, False),
+ ("RESTORE_API", "function", 7, False),
+ },
+ ),
+ (
+ b"""#define API Existing
+#pragma push_macro("API")
+#undef API
+#define API
+#define RESTORE_API() __pragma(pop_macro("API"))
+RESTORE_API()
+struct API Fwd;
+""",
+ {
+ ("API", "variable", 1, False),
+ ("API", "variable", 4, False),
+ ("RESTORE_API", "function", 5, False),
+ },
+ ),
+ (
+ b"""#define API Existing
+#pragma push_macro("API")
+#undef API
+#define API
+#define DO_PRAGMA(value) _Pragma(#value)
+DO_PRAGMA(pop_macro("API"))
+struct API Fwd;
+""",
+ {
+ ("API", "variable", 1, False),
+ ("API", "variable", 4, False),
+ ("DO_PRAGMA", "function", 5, False),
+ },
+ ),
+ (
+ b"""#define API Existing
+#pragma push_macro("API")
+#undef API
+#define API
+#define RESTORE_API _Pragma("pop_macro(\"API\")")
+RESTORE_API;
+struct API Fwd;
+""",
+ {
+ ("API", "variable", 1, False),
+ ("API", "variable", 4, False),
+ ("RESTORE_API", "variable", 5, False),
+ },
+ ),
+ (
+ b"""#define API Existing
+#pragma push_macro("API")
+#undef API
+#define API
+#define RESTORE_API _Pragma("pop_macro(\"API\")") 1
+int restored[RESTORE_API];
+struct API Fwd;
+""",
+ {
+ ("API", "variable", 1, False),
+ ("API", "variable", 4, False),
+ ("RESTORE_API", "variable", 5, False),
+ },
+ ),
+ (
+ b"""#define API
+#pragma push_macro("API")
+#undef API
+#pragma pop_macro("API")
+struct API Fwd;
+""",
+ {("Fwd", "struct", 5, True)},
+ ),
+ (
+ b"""#define API
+_Pragma("push_macro(\"API\")")
+#undef API
+_Pragma("pop_macro(\"API\")")
+struct API Fwd;
+""",
+ {("Fwd", "struct", 5, True)},
+ ),
+ (
+ b"""#define API
+#pragma pop_macro("API")
+struct API Fwd;
+""",
+ {("Fwd", "struct", 3, True)},
+ ),
+ (
+ b"""#define API
+_Pragma("pop_macro(\"API\")")
+struct API Fwd;
+""",
+ {("Fwd", "struct", 3, True)},
+ ),
+ (
+ b"""#define API
+#define RESTORE_API() _Pragma("pop_macro(\"API\")")
+struct API Fwd;
+""",
+ {
+ ("RESTORE_API", "function", 2, False),
+ ("Fwd", "struct", 3, True),
+ },
+ ),
+ (
+ b"""#define API Existing
+#pragma push_macro("API")
+#undef API
+#define API
+#define RESTORE_API() _Pragma("pop_macro(\"API\")")
+#define RESTORE_ALIAS() RESTORE_API()
+RESTORE_ALIAS()
+struct API Fwd;
+""",
+ {
+ ("API", "variable", 1, False),
+ ("API", "variable", 4, False),
+ ("RESTORE_API", "function", 5, False),
+ ("RESTORE_ALIAS", "function", 6, False),
+ },
+ ),
+ (
+ b"""#define API Existing
+#pragma push_macro("API")
+#undef API
+#define API
+#define RESTORE_API() _Pragma("pop_macro(\"API\")")
+#define RESTORE_WRAPPED() (RESTORE_API())
+RESTORE_WRAPPED()
+struct API Fwd;
+""",
+ {
+ ("API", "variable", 1, False),
+ ("API", "variable", 4, False),
+ ("RESTORE_API", "function", 5, False),
+ ("RESTORE_WRAPPED", "function", 6, False),
+ },
+ ),
+ (
+ b"""#define API Existing
+#pragma push_macro("API")
+#undef API
+#define API
+#define RESTORE_API() _Pragma("pop_macro(\"API\")")
+#define APPLY(value) value()
+APPLY(RESTORE_API)
+struct API Fwd;
+""",
+ {
+ ("API", "variable", 1, False),
+ ("API", "variable", 4, False),
+ ("RESTORE_API", "function", 5, False),
+ ("APPLY", "function", 6, False),
+ },
+ ),
+ (
+ b"""#define API
+#pragma push_macro("API")
+#include "possibly_mutates_macro_stack.hpp"
+#pragma pop_macro("API")
+struct API Fwd;
+""",
+ {("API", "variable", 1, False)},
+ ),
+ (
+ b"""#define API
+#include "possibly_mutates_macro_stack.hpp"
+#pragma push_macro("API")
+#undef API
+#define API Existing
+#pragma pop_macro("API")
+struct API Fwd;
+""",
+ {("API", "variable", 1, False), ("API", "variable", 5, False)},
+ ),
+ (
+ b"""#include "possibly_mutates_macro_stack.hpp"
+#define API
+#pragma push_macro("API")
+#undef API
+#define API Existing
+#pragma pop_macro("API")
+struct API Fwd;
+""",
+ {("API", "variable", 5, False), ("Fwd", "struct", 7, True)},
+ ),
+ (
+ b"""#define API
+#pragma push_macro("API")
+#define API Existing
+#pragma push_macro("API")
+#undef API
+#pragma pop_macro("API")
+#pragma pop_macro("API")
+struct API Fwd;
+""",
+ {
+ ("API", "variable", 3, False),
+ ("Fwd", "struct", 8, True),
+ },
+ ),
+ (
+ b"#define API\n#undef A\\\nPI\nstruct API Fwd;\n",
+ {("API", "variable", 1, False)},
+ ),
+ (
+ b"#define API\n#un\\\ndef API\nstruct API Fwd;\n",
+ {("API", "variable", 1, False)},
+ ),
+ (
+ """#define ÉXPORT
+#undef ÉXPORT
+struct ÉXPORT Fwd;
+""".encode(),
+ {("ÉXPORT", "variable", 1, False)},
+ ),
+ (
+ """#define ÉXPORT
+#undef \\u00C9XPORT
+struct ÉXPORT Fwd;
+""".encode(),
+ {("ÉXPORT", "variable", 1, False)},
+ ),
+ (
+ """#define \\u00C9XPORT
+#undef ÉXPORT
+struct ÉXPORT Fwd;
+""".encode(),
+ {("\\u00C9XPORT", "variable", 1, False)},
+ ),
+ (
+ """#define \\u00C9XPORT
+struct ÉXPORT Fwd;
+""".encode(),
+ {("Fwd", "struct", 2, True)},
+ ),
+ (
+ b"""#define API
+#include "possibly_redefines.hpp"
+#define API
+struct API Fwd;
+""",
+ {
+ ("API", "variable", 1, False),
+ ("Fwd", "struct", 4, True),
+ },
+ ),
+ (
+ b"""#define API
+#pragma pop_macro("OTHER")
+struct API Fwd;
+""",
+ {("Fwd", "struct", 3, True)},
+ ),
+ (
+ b"""#define API
+#pragma pop_macro("API")
+#define API
+struct API Fwd;
+""",
+ {
+ ("API", "variable", 1, False),
+ ("Fwd", "struct", 4, True),
+ },
+ ),
+)
+
+
+UNSAFE_CPP_EXPORT_MACRO_FORWARD_DECLARATIONS = (
+ (
+ b"""struct MYLIB_EXPORT Fwd;
+#define MYLIB_EXPORT
+""",
+ "MYLIB_EXPORT",
+ "variable",
+ ),
+ (
+ b"""#define MYLIB_EXPORT
+#undef MYLIB_EXPORT
+struct MYLIB_EXPORT Fwd;
+""",
+ "MYLIB_EXPORT",
+ "variable",
+ ),
+ (
+ b"""#if 0
+#define MYLIB_EXPORT
+#endif
+struct MYLIB_EXPORT Fwd;
+""",
+ "MYLIB_EXPORT",
+ "variable",
+ ),
+ (
+ b"""#define LEGACY_API Existing
+struct LEGACY_API Fwd;
+""",
+ "LEGACY_API",
+ "variable",
+ ),
+ (
+ b"""#define MYLIB_EXPORT(value)
+struct MYLIB_EXPORT Fwd;
+""",
+ "MYLIB_EXPORT",
+ "function",
+ ),
+ (
+ b"""#define MYLIB_EXPORT
+#if FEATURE
+#undef MYLIB_EXPORT
+#endif
+struct MYLIB_EXPORT Fwd;
+""",
+ "MYLIB_EXPORT",
+ "variable",
+ ),
+ (
+ b"""#define MYLIB_EXPORT
+#if FEATURE
+#define MYLIB_EXPORT Existing
+#endif
+struct MYLIB_EXPORT Fwd;
+""",
+ "MYLIB_EXPORT",
+ "variable",
+ ),
+)
+
+
class TestCppParser:
def test_finds_class_in_header(self, parser: ASTParser) -> None:
fi = _make_file_info("cpp_pkg/calculator.hpp", "cpp")
@@ -104,3 +783,310 @@ class TestCppParser:
assert symbols[(None, "PlainOptions")].kind == "struct"
assert symbols[("PlainOptions", "PlainOptions")].kind == "method"
assert not any(symbol.name == "MYLIB_EXPORT" for symbol in result.symbols)
+
+ def test_preserves_conditional_export_macro_body_recovery(self, parser: ASTParser) -> None:
+ fi = _make_file_info("cpp_pkg/conditional_options.hpp", "cpp")
+ result = parser.parse_file(fi, CPP_CONDITIONAL_EXPORT_MACRO_TYPE)
+
+ assert {
+ (symbol.parent_name, symbol.name, symbol.kind, symbol.is_declaration)
+ for symbol in result.symbols
+ } == {
+ (None, "Brewer", "struct", False),
+ ("Brewer", "brew", "method", True),
+ }
+
+ @pytest.mark.parametrize(
+ "source",
+ (
+ "#define \\u00C9XPORT\nstruct ÉXPORT Body { int x; };\n".encode(),
+ "#define ÉXPORT\nstruct \\u00C9XPORT Body { int x; };\n".encode(),
+ ),
+ ids=("ucn-definition", "ucn-use"),
+ )
+ def test_normalizes_ucn_spellings_for_export_macro_body_recovery(
+ self, parser: ASTParser, source: bytes
+ ) -> None:
+ fi = _make_file_info("cpp_pkg/ucn_body.hpp", "cpp")
+ result = parser.parse_file(fi, source)
+
+ assert {
+ (symbol.name, symbol.kind, symbol.start_line, symbol.is_declaration)
+ for symbol in result.symbols
+ } == {("Body", "struct", 2, False)}
+
+ def test_finds_types_forward_declared_through_export_macros(self, parser: ASTParser) -> None:
+ fi = _make_file_info("cpp_pkg/forward.hpp", "cpp")
+ result = parser.parse_file(fi, CPP_EXPORT_MACRO_FORWARD_DECLARATIONS)
+ expected_symbols = {
+ (None, "Fwd", "struct", True),
+ (None, "Fwd2", "class", True),
+ (None, "PlainFwd", "struct", True),
+ (None, "PlainFwd2", "class", True),
+ (None, "UNRELATED_MACRO", "variable", False),
+ }
+
+ assert len(result.symbols) == len(expected_symbols)
+ assert {
+ (symbol.parent_name, symbol.name, symbol.kind, symbol.is_declaration)
+ for symbol in result.symbols
+ } == expected_symbols
+
+ def test_ignores_unrelated_identifiers_after_include_for_forward_recovery(
+ self, parser: ASTParser
+ ) -> None:
+ source = b"""#include <vector>
+#define API
+int helper(int x) { return x; }
+struct API Fwd;
+"""
+ fi = _make_file_info("cpp_pkg/forward_after_helper.hpp", "cpp")
+ result = parser.parse_file(fi, source)
+
+ assert {
+ (symbol.name, symbol.kind, symbol.start_line, symbol.is_declaration)
+ for symbol in result.symbols
+ } == {
+ ("helper", "function", 3, False),
+ ("Fwd", "struct", 4, True),
+ }
+
+ def test_ignores_unrelated_calls_after_include_for_forward_recovery(
+ self, parser: ASTParser
+ ) -> None:
+ source = b"""#include <vector>
+#define API
+int value = transform(1);
+struct API Fwd;
+"""
+ fi = _make_file_info("cpp_pkg/forward_after_call.hpp", "cpp")
+ result = parser.parse_file(fi, source)
+
+ assert {
+ (symbol.name, symbol.kind, symbol.start_line, symbol.is_declaration)
+ for symbol in result.symbols
+ } == {("Fwd", "struct", 4, True)}
+
+ def test_preserves_local_macro_stack_hazard_after_include(self, parser: ASTParser) -> None:
+ source = b"""#include <vector>
+#define API
+#define RESTORE_API() _Pragma("pop_macro(\\"API\\")")
+RESTORE_API()
+struct API Fwd;
+"""
+ fi = _make_file_info("cpp_pkg/forward_after_wrapper.hpp", "cpp")
+ result = parser.parse_file(fi, source)
+
+ assert {
+ (symbol.name, symbol.kind, symbol.start_line, symbol.is_declaration)
+ for symbol in result.symbols
+ } == {
+ ("API", "variable", 2, False),
+ ("RESTORE_API", "function", 3, False),
+ }
+
+ def test_does_not_reinterpret_tag_variable_declaration_as_export_macro(
+ self, parser: ASTParser
+ ) -> None:
+ fi = _make_file_info("cpp_pkg/tag_variable.hpp", "cpp")
+ result = parser.parse_file(fi, b"struct API Fwd;\n")
+
+ assert not any(symbol.name == "Fwd" for symbol in result.symbols)
+
+ def test_finds_export_macro_forward_declarations_in_cpp_contexts(
+ self, parser: ASTParser
+ ) -> None:
+ fi = _make_file_info("cpp_pkg/forward_contexts.hpp", "cpp")
+ result = parser.parse_file(fi, CPP_EXPORT_MACRO_FORWARD_DECLARATION_CONTEXTS)
+
+ assert {
+ (symbol.parent_name, symbol.name, symbol.kind, symbol.is_declaration)
+ for symbol in result.symbols
+ } == {
+ (None, "sdk", "module", False),
+ (None, "Namespaced", "struct", True),
+ (None, "Generic", "class", True),
+ (None, "Outer", "class", False),
+ ("Outer", "Nested", "struct", True),
+ }
+
+ def test_includes_template_lines_in_export_macro_forward_declaration_range(
+ self, parser: ASTParser
+ ) -> None:
+ source = b"""#define API
+template <typename T>
+class API Generic;
+"""
+ fi = _make_file_info("cpp_pkg/template_forward.hpp", "cpp")
+ result = parser.parse_file(fi, source)
+
+ generic = next(symbol for symbol in result.symbols if symbol.name == "Generic")
+ assert (generic.start_line, generic.end_line, generic.is_declaration) == (2, 3, True)
+
+ @pytest.mark.parametrize(
+ ("source", "macro_name", "macro_kind"),
+ UNSAFE_CPP_EXPORT_MACRO_FORWARD_DECLARATIONS,
+ ids=(
+ "defined-later",
+ "undefined",
+ "conditional",
+ "non-empty-alias",
+ "function-like",
+ "conditional-undef-before-use",
+ "conditional-redefinition-before-use",
+ ),
+ )
+ def test_does_not_guess_export_macro_forward_declarations(
+ self, parser: ASTParser, source: bytes, macro_name: str, macro_kind: str
+ ) -> None:
+ fi = _make_file_info("cpp_pkg/ambiguous_forward.hpp", "cpp")
+ result = parser.parse_file(fi, source)
+
+ assert not any(symbol.name == "Fwd" for symbol in result.symbols)
+ assert any(
+ symbol.name == macro_name and symbol.kind == macro_kind for symbol in result.symbols
+ )
+
+ @pytest.mark.parametrize(
+ "source",
+ SPACED_CPP_UNDEF_FORWARD_DECLARATIONS,
+ ids=("space-after-hash", "tab-after-hash", "leading-and-mixed-space"),
+ )
+ def test_respects_spaced_undef_before_export_macro_forward_declaration(
+ self, parser: ASTParser, source: bytes
+ ) -> None:
+ fi = _make_file_info("cpp_pkg/spaced_undef.hpp", "cpp")
+ result = parser.parse_file(fi, source)
+
+ assert {
+ (symbol.name, symbol.kind, symbol.start_line, symbol.is_declaration)
+ for symbol in result.symbols
+ } == {("API", "variable", 1, False)}
+
+ def test_recovers_export_macro_forward_declaration_inside_conditional_branch(
+ self, parser: ASTParser
+ ) -> None:
+ source = b"""#define API
+#ifdef FEATURE
+struct API Fwd;
+#endif
+"""
+ fi = _make_file_info("cpp_pkg/conditional_forward.hpp", "cpp")
+ result = parser.parse_file(fi, source)
+
+ assert {
+ (symbol.parent_name, symbol.name, symbol.kind, symbol.is_declaration)
+ for symbol in result.symbols
+ } == {(None, "Fwd", "struct", True)}
+
+ @pytest.mark.parametrize(
+ ("source", "expected_symbols"),
+ CPP_EXPORT_MACRO_LIFETIME_CASES,
+ ids=(
+ "non-empty-to-empty",
+ "empty-to-non-empty",
+ "undef-then-redefine",
+ "function-to-object",
+ "object-to-function",
+ "undef-after-use",
+ "unrelated-undef",
+ "comment-only-empty-macro",
+ "redefine-between-uses",
+ ),
+ )
+ def test_tracks_export_macro_lifetime_for_forward_declarations(
+ self,
+ parser: ASTParser,
+ source: bytes,
+ expected_symbols: set[tuple[str, str, int, bool]],
+ ) -> None:
+ fi = _make_file_info("cpp_pkg/macro_lifetime.hpp", "cpp")
+ result = parser.parse_file(fi, source)
+
+ assert {
+ (symbol.name, symbol.kind, symbol.start_line, symbol.is_declaration)
+ for symbol in result.symbols
+ } == expected_symbols
+
+ @pytest.mark.parametrize(
+ ("source", "expected_symbols"),
+ CPP_EXPORT_MACRO_BRANCH_CONTEXT_CASES,
+ ids=(
+ "include-guard",
+ "outer-definition-inner-declaration",
+ "definition-in-sibling-branch",
+ "definition-in-finished-branch",
+ "definitions-in-each-elif-branch",
+ "definition-missing-from-elif-branches",
+ ),
+ )
+ def test_requires_compatible_preprocessor_branches_for_forward_declarations(
+ self,
+ parser: ASTParser,
+ source: bytes,
+ expected_symbols: set[tuple[str, str, int, bool]],
+ ) -> None:
+ fi = _make_file_info("cpp_pkg/branch_context.hpp", "cpp")
+ result = parser.parse_file(fi, source)
+
+ assert {
+ (symbol.name, symbol.kind, symbol.start_line, symbol.is_declaration)
+ for symbol in result.symbols
+ } == expected_symbols
+
+ @pytest.mark.parametrize(
+ ("source", "expected_symbols"),
+ CPP_EXPORT_MACRO_STATE_BOUNDARY_CASES,
+ ids=(
+ "include-literal-invalidates-state",
+ "include-macro-invalidates-state",
+ "include-next-invalidates-state",
+ "import-invalidates-state",
+ "pragma-pop-restores-non-empty",
+ "pragma-pop-restores-undefined",
+ "line-spliced-pop-macro-keyword",
+ "line-spliced-pop-macro-target",
+ "pragma-operator-pop-restores-state",
+ "msvc-pragma-pop-restores-state",
+ "macro-wrapped-pragma-restores-non-empty",
+ "macro-wrapped-pop-taints-later-direct-pop",
+ "macro-wrapped-msvc-pragma-restores-non-empty",
+ "two-level-macro-wrapped-pragma-restores-non-empty",
+ "object-macro-wrapped-pragma-restores-non-empty",
+ "object-wrapper-in-array-bound-restores-non-empty",
+ "pragma-pop-restores-empty",
+ "pragma-operator-pop-restores-empty",
+ "unmatched-pragma-pop-preserves-empty",
+ "unmatched-pragma-operator-pop-preserves-empty",
+ "unused-pragma-wrapper-preserves-known-state",
+ "aliased-pragma-wrapper-invalidates-state",
+ "parenthesized-alias-wrapper-invalidates-state",
+ "parameter-relayed-wrapper-invalidates-state",
+ "include-invalidates-existing-macro-stack",
+ "push-after-include-snapshots-unknown-state",
+ "local-definition-and-push-after-include-restore-empty",
+ "nested-pragma-stack-restores-empty",
+ "line-spliced-undef-name",
+ "line-spliced-undef-directive",
+ "unicode-undef-name",
+ "ucn-undef-name",
+ "ucn-definition-literal-undef",
+ "ucn-definition-literal-use",
+ "definition-after-include-restores-known-state",
+ "unrelated-pop-does-not-invalidate-state",
+ "definition-after-pop-restores-known-state",
+ ),
+ )
+ def test_treats_uncertain_macro_state_as_unsafe_for_forward_recovery(
+ self,
+ parser: ASTParser,
+ source: bytes,
+ expected_symbols: set[tuple[str, str, int, bool]],
+ ) -> None:
+ fi = _make_file_info("cpp_pkg/macro_state_boundary.hpp", "cpp")
+ result = parser.parse_file(fi, source)
+
+ assert {
+ (symbol.name, symbol.kind, symbol.start_line, symbol.is_declaration)
+ for symbol in result.symbols
+ } == expected_symbols