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.

refactor(core): decompose ASTParser symbol, import and call extraction (#2562)

Raghav Chamadiyab13556b6192b
diff --git a/packages/core/src/repowise/core/ingestion/cpp_export_macros.py b/packages/core/src/repowise/core/ingestion/cpp_export_macros.py
new file mode 100644
index 000000000..00c8d9761
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/cpp_export_macros.py
@@ -0,0 +1,663 @@
+"""C/C++ export-macro recovery: macro state facts and forward-declaration helpers."""
+
+from __future__ import annotations
+
+import re
+import unicodedata
+from bisect import bisect_left
+from collections import deque
+from dataclasses import dataclass, field
+from enum import Enum, auto
+from functools import cached_property
+
+from tree_sitter import Node
+
+from .extractors import node_text as _node_text
+
+# C/C++ node types that spell a type. Each one covers both the definition and
+# the forward declaration of that type; only the ``body`` field tells them
+# apart. See ``_is_bodiless_cpp_type``.
+# ``union_specifier`` is absent because neither grammar's query captures one
+# 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:
+ """True for a C/C++ type forward declaration such as ``class Env;``.
+
+ ``declaration_node_types`` already catches a *function* prototype, whose
+ tree-sitter node genuinely is a ``declaration``. A type forward declaration
+ is not: it arrives as the very same ``class_specifier`` a definition uses,
+ minus the ``body`` field. Left unmarked it reads as a whole class defined
+ on one line, so every consumer that distinguishes a declaration from a
+ definition — call resolution's declaration/definition pairing and the
+ dead-code passes — silently treats the header line as the real thing.
+ """
+ if language not in ("cpp", "c"):
+ return False
+ if node_type == "template_declaration":
+ # ``template <typename T> class Foo;``. The wrapper carries no ``body``
+ # field of its own — the inner specifier does — so asking the wrapper
+ # would call every template a declaration. Ask the type it wraps.
+ inner = next(
+ (c for c in def_node.children if c.type in _CPP_TYPE_SPECIFIER_NODES),
+ None,
+ )
+ return inner is not None and inner.child_by_field_name("body") is None
+ if node_type not in _CPP_TYPE_SPECIFIER_NODES:
+ return False
+ if def_node.child_by_field_name("body") is not None:
+ return False
+ # ``typedef struct CBMAutomaton CBMAutomaton;`` — C's opaque-handle idiom.
+ # The tag and the typedef name are the same identifier, so both patterns
+ # match at one position and dedup keeps a single symbol. That symbol is the
+ # typedef name, which *is* a deletable API artifact and must stay
+ # reportable. Erring toward under-marking: a forward-declared tag under a
+ # differently-named typedef (``typedef struct Impl_s Handle;``) is left
+ # unmarked too, which only costs a suppression we never had.
+ parent = def_node.parent
+ return parent is None or parent.type != "type_definition"
+
+
+def _cpp_export_macro_parent(node: Node, parent_names: dict[int, str]) -> str | None:
+ """Return the real type name for a member inside a macro-decorated C++ type."""
+ ancestor = node.parent
+ while ancestor is not None:
+ parent_name = parent_names.get(ancestor.id)
+ if parent_name is not None:
+ return parent_name
+ ancestor = ancestor.parent
+ return None
+
+
+@dataclass
+class CppExportTypes:
+ """Macro-decorated C++ types (``struct EXPORT Name``) recovered from one file.
+
+ tree-sitter-cpp names such a type after the macro; cpp.scm marks the matches.
+ """
+
+ defs: dict[int, _CppExportType] = field(default_factory=dict)
+ parents: dict[int, str] = field(default_factory=dict)
+ capture_ids: set[int] = field(default_factory=set)
+ macro_names: set[str] = field(default_factory=set)
+ macro_def_ids: set[int] = field(default_factory=set)
+
+ @cached_property
+ def parent_ids(self) -> frozenset[int]:
+ return frozenset(self.parents)
+
+
+def collect_cpp_export_types(matches: list[dict], src: str) -> CppExportTypes:
+ """Recover every macro-decorated type the query matched in one C++ file."""
+ found = CppExportTypes()
+ 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", [])
+ macro_nodes = capture_dict.get("symbol.cpp_export_macro", [])
+ if not type_nodes or not def_nodes or not name_nodes:
+ continue
+ type_name = _node_text(name_nodes[0], src)
+ if not type_name:
+ continue
+ 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:
+ active_macro_def = _forward_declaration_macro(
+ cpp_macro_facts, macro_nodes, capture_node, src
+ )
+ if active_macro_def is None:
+ continue
+ else:
+ # Body-form matches are unambiguous. Preserve #1896's
+ # name-based suppression across conditional definitions.
+ found.macro_names.update(
+ _cpp_normalize_identifier(_node_text(node, src)) for node in macro_nodes
+ )
+ found.defs[def_nodes[0].id] = _CppExportType(
+ range_node=range_node,
+ name=type_name,
+ is_forward_declaration=is_forward_declaration,
+ )
+ found.capture_ids.add(capture_node.id)
+ found.parents[capture_node.id] = type_name
+ found.parents[range_node.id] = type_name
+ if active_macro_def is not None:
+ found.macro_def_ids.add(active_macro_def.id)
+ return found
+
+
+def _forward_declaration_macro(
+ facts: _CppMacroFacts | None, macro_nodes: list[Node], declaration: Node, src: str
+) -> Node | None:
+ """The empty macro definition that makes a bodiless decorated type safe to recover."""
+ if facts is None:
+ return None
+ macro_names = {
+ _cpp_normalize_identifier(_node_text(node, src)) for node in macro_nodes
+ } - {""}
+ if len(macro_names) != 1:
+ return None
+ # A bodiless decorated type is syntactically identical to
+ # an ordinary ``struct Tag variable;`` declaration.
+ return facts.empty_definition_at(next(iter(macro_names)), declaration)
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index caf3859d5..f808304b9 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -25,18 +25,21 @@ 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
import structlog
from tree_sitter import Language, Node, Parser
+from .cpp_export_macros import (
+ CppExportTypes,
+ _cpp_export_macro_parent,
+ _cpp_normalize_identifier,
+ _CppExportType,
+ _is_bodiless_cpp_type,
+ collect_cpp_export_types,
+)
from .extractors import (
build_signature,
extract_go_receiver_type,
@@ -191,559 +194,6 @@ def _call_receiver_from_node(node: Node, src: str) -> CallReceiver | None:
return CallReceiver(target_name, receiver_name, argument_count)
-# C/C++ node types that spell a type. Each one covers both the definition and
-# the forward declaration of that type; only the ``body`` field tells them
-# apart. See ``_is_bodiless_cpp_type``.
-# ``union_specifier`` is absent because neither grammar's query captures one
-# 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:
- """True for a C/C++ type forward declaration such as ``class Env;``.
-
- ``declaration_node_types`` already catches a *function* prototype, whose
- tree-sitter node genuinely is a ``declaration``. A type forward declaration
- is not: it arrives as the very same ``class_specifier`` a definition uses,
- minus the ``body`` field. Left unmarked it reads as a whole class defined
- on one line, so every consumer that distinguishes a declaration from a
- definition — call resolution's declaration/definition pairing and the
- dead-code passes — silently treats the header line as the real thing.
- """
- if language not in ("cpp", "c"):
- return False
- if node_type == "template_declaration":
- # ``template <typename T> class Foo;``. The wrapper carries no ``body``
- # field of its own — the inner specifier does — so asking the wrapper
- # would call every template a declaration. Ask the type it wraps.
- inner = next(
- (c for c in def_node.children if c.type in _CPP_TYPE_SPECIFIER_NODES),
- None,
- )
- return inner is not None and inner.child_by_field_name("body") is None
- if node_type not in _CPP_TYPE_SPECIFIER_NODES:
- return False
- if def_node.child_by_field_name("body") is not None:
- return False
- # ``typedef struct CBMAutomaton CBMAutomaton;`` — C's opaque-handle idiom.
- # The tag and the typedef name are the same identifier, so both patterns
- # match at one position and dedup keeps a single symbol. That symbol is the
- # typedef name, which *is* a deletable API artifact and must stay
- # reportable. Erring toward under-marking: a forward-declared tag under a
- # differently-named typedef (``typedef struct Impl_s Handle;``) is left
- # unmarked too, which only costs a suppression we never had.
- parent = def_node.parent
- return parent is None or parent.type != "type_definition"
-
-
-def _cpp_export_macro_parent(node: Node, parent_names: dict[int, str]) -> str | None:
- """Return the real type name for a member inside a macro-decorated C++ type."""
- ancestor = node.parent
- while ancestor is not None:
- parent_name = parent_names.get(ancestor.id)
- if parent_name is not None:
- return parent_name
- ancestor = ancestor.parent
- return None
-
-
@cache
def _compile_query(lang: str, grammar_tag: str | None = None) -> tuple[object | None, str | None]:
"""Compile and return (Query, None) or (None, error_str).
@@ -981,6 +431,663 @@ def _normalize_php_receiver(text: str) -> str:
# ---------------------------------------------------------------------------
+def _match_identity(
+ capture_dict: dict,
+ config: LanguageConfig,
+ language: str,
+ src: str,
+ cpp_exports: CppExportTypes,
+ seen: set[tuple[int, str]],
+) -> tuple[Node, list[Node], str, _CppExportType | None, int] | None:
+ """``(def_node, name_nodes, name, export_type, start_line)`` for a new symbol match.
+
+ None drops the match: no definition or name, a recovery match this file
+ does not support, a suppressed export macro, or a duplicate. The
+ ``(start_line, name)`` key is recorded in *seen* here.
+ """
+ def_nodes = capture_dict.get("symbol.def", [])
+ name_nodes = capture_dict.get("symbol.name", [])
+ 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_exports.capture_ids
+ ):
+ # The query also sees ordinary ``struct Tag variable;`` forms;
+ # discard only the unsupported recovery match.
+ return None
+
+ if not def_nodes or not name_nodes:
+ return None
+
+ def_node = def_nodes[0]
+ name = _language_symbol_name(
+ language, def_node, config.symbol_name_fn(_node_text(name_nodes[0], src), def_node.type), src
+ )
+ if name is None:
+ return None
+
+ export_type = cpp_exports.defs.get(def_node.id)
+ 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.
+ return None
+
+ if def_node.type == "preproc_def" and (
+ _cpp_normalize_identifier(name) in cpp_exports.macro_names
+ or def_node.id in cpp_exports.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.
+ return None
+
+ 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:
+ return None
+ seen.add(dedup_key)
+ return def_node, name_nodes, name, export_type, start_line
+
+
+def _is_declaration(
+ def_node: Node, config: LanguageConfig, language: str, export_type: _CppExportType | None
+) -> bool:
+ node_type = def_node.type
+ if node_type in config.declaration_node_types:
+ return True
+ if export_type is not None:
+ return export_type.is_forward_declaration
+ return _is_bodiless_cpp_type(language, node_type, def_node)
+
+
+def _objc_call_target(
+ site_node: Node, target_node: Node, target_name: str, has_receiver: bool, src: str
+) -> str | None:
+ """Objective-C call target name, or None to drop the match."""
+ # A message send binds one `method:` child per keyword, so
+ # `[view setTitle:t forState:s]` matches the query twice. Join the whole
+ # selector on the first match and drop the rest.
+ if site_node.type == "message_expression":
+ return _objc_message_selector(site_node, target_node, src)
+ # A block variable invoked with C call syntax (`completionBlock(hit)`) is
+ # not a call to a same-named function or property.
+ if not has_receiver and _objc_call_is_block_variable(site_node, target_name, src):
+ return None
+ return target_name
+
+
+def _jsx_supplied_props(site_node: Node, src: str) -> frozenset[str] | None:
+ """Props written on a JSX element, or None when not JSX or a spread hides them."""
+ if site_node.type not in ("jsx_self_closing_element", "jsx_opening_element"):
+ return None
+ props_set: set[str] = set()
+ for child in site_node.children:
+ if child.type == "jsx_attribute":
+ name = next(
+ (sub for sub in child.children if sub.type in ("property_identifier", "identifier")),
+ None,
+ )
+ if name is not None:
+ props_set.add(_node_text(name, src))
+ elif child.type == "jsx_expression" and any(
+ sub.type == "spread_element" for sub in child.children
+ ):
+ return None
+ return frozenset(props_set)
+
+
+def _dedupe_calls(calls: list[CallSite]) -> list[CallSite]:
+ """One call per ``(line, target, receiver)``, keeping the richest record.
+
+ Two scoped-call patterns can match the same two-part call (one keeps the
+ qualifier), so the richer record wins whichever order they arrive in.
+ """
+ deduplicated: dict[tuple[int, str, str | None], CallSite] = {}
+ for call in calls:
+ key = (call.line, call.target_name, call.receiver_name)
+ existing = deduplicated.get(key)
+ if (
+ existing is None
+ or (existing.receiver_call is None and call.receiver_call is not None)
+ or (existing.scope_name is None and call.scope_name is not None)
+ ):
+ deduplicated[key] = call
+ return list(deduplicated.values())
+
+
+_FSHARP_BINDING_NODE_TYPES = ("function_declaration_left", "value_declaration_left")
+_DART_FUNCTION_NODE_TYPES = ("function_signature", "getter_signature", "setter_signature")
+
+
+def _is_fsharp_binding(language: str, node_type: str) -> bool:
+ return language == "fsharp" and node_type in _FSHARP_BINDING_NODE_TYPES
+
+
+def _language_symbol_name(language: str, def_node: Node, name: str, src: str) -> str | None:
+ """Apply a language's own naming rule; None drops the match."""
+ if not name:
+ return None
+ if language == "elixir":
+ # A `def` inside `quote do ... end` is macro body, not a
+ # definition of the module that writes it.
+ if _elixir_is_template_definition(def_node, src):
+ return None
+ # `defimpl Proto, for: Type` is named for the module the
+ # compiler generates, not for the protocol alone.
+ return _elixir_symbol_name(def_node, name, src)
+ if language == "objectivec":
+ # `typedef NS_ENUM(NSInteger, Kind) { ... }` has no grammar
+ # rule, so only its enum *cases* survive as declarators and
+ # each would become a symbol named as though it were the type.
+ if _objc_is_macro_enum(def_node, src):
+ return None
+ # A method is named by its whole selector
+ # (`initWithName:age:`), which no single node holds, and a
+ # category by the class it extends plus its own name.
+ return _objc_symbol_name(def_node, name, src)
+ return name
+
+
+def _refine_symbol_kind(
+ kind: str, def_node: Node, config: LanguageConfig, language: str, src: str
+) -> str:
+ """Narrow a node-type kind where one node shape spells several kinds."""
+ node_type = def_node.type
+ # A value binding that carries parameter patterns beside its
+ # name is a function the grammar reparsed as a value because
+ # of its return-type annotation.
+ if (
+ language == "fsharp"
+ and node_type == "value_declaration_left"
+ and _fsharp_binding_has_params(def_node)
+ ):
+ kind = "function"
+
+ # Refine "struct" kind for Go type_spec (check if struct or interface body)
+ if kind == "struct" and config.parent_extraction == "receiver":
+ kind = refine_go_type_kind(def_node, src)
+
+ # Refine "class" kind for Kotlin (interface / enum class share class_declaration)
+ if kind == "class" and language == "kotlin" and node_type == "class_declaration":
+ kind = refine_kotlin_class_kind(def_node)
+
+ # Pascal ``declType`` wraps class, record, interface, enum and more.
+ if kind == "class" and language == "pascal" and node_type == "declType":
+ kind = refine_pascal_type_kind(def_node)
+
+ # Elixir: every definition is a ``call``; its keyword names the kind.
+ if language == "elixir" and node_type == "call":
+ kind = refine_elixir_call_kind(def_node, src)
+
+ # F# writes a class, a struct and an interface with the same
+ # ``anon_type_defn`` node; only the body says which it is.
+ if kind == "class" and language == "fsharp" and node_type == "anon_type_defn":
+ kind = refine_fsharp_type_kind(def_node)
+ return kind
+
+
+def _symbol_end_line(
+ def_node: Node,
+ config: LanguageConfig,
+ language: str,
+ export_type: _CppExportType | None,
+) -> int | None:
+ """The symbol's last line, or None for a Dart local function (not a symbol)."""
+ node_type = def_node.type
+ end_line = def_node.end_point[0] + 1
+ if config.symbol_end_line_fn is not None:
+ end_line = config.symbol_end_line_fn(def_node, end_line)
+ if export_type is not None:
+ end_line = export_type.range_node.end_point[0] + 1
+ # F#: the captured left-hand side stops at the parameters; extend over the body.
+ if _is_fsharp_binding(language, node_type):
+ end_line = _fsharp_binding_end_line(def_node)
+ if language == "dart" and node_type in _DART_FUNCTION_NODE_TYPES:
+ return _dart_function_end_line(def_node, end_line)
+ return end_line
+
+
+def _dart_function_end_line(def_node: Node, end_line: int) -> int | None:
+ """Dart: a function's body is a sibling of its signature.
+
+ Local functions nested inside another function's body have no callable
+ *ancestor* (the enclosing signature is a sibling), so they are dropped
+ here (None); and the line range extends to the trailing body sibling or
+ call-site attribution stops at the signature line.
+ """
+ ancestor = def_node.parent
+ while ancestor is not None:
+ if ancestor.type in ("function_body", "function_expression"):
+ return None
+ ancestor = ancestor.parent
+ anchor = def_node
+ if def_node.parent is not None and def_node.parent.type == "method_signature":
+ anchor = def_node.parent
+ body_sibling = anchor.next_named_sibling
+ if body_sibling is not None and body_sibling.type == "function_body":
+ return body_sibling.end_point[0] + 1
+ return end_line
+
+
+def _module_binding_kind(def_node: Node, name: str, language: str, src: str) -> str | None:
+ """Kind of a module-level assignment, or None when it only binds a module.
+
+ SCREAMING_CASE names are constants by convention; the rest are module
+ variables (singletons like ``app = FastAPI()``, registries, caches).
+ ``str.isupper()`` requires at least one cased char, so names with no
+ letters (``_``, ``__all__``) fall to "variable" rather than being
+ mislabelled constants by ``name == name.upper()``.
+ """
+ # TS/JS: ``const svc = require('./svc')`` binds a module (already an
+ # import), so it is not a symbol.
+ if language in _TS_JS_LANGUAGES and declarator_value_is_module_ref(def_node, src):
+ return None
+ # A structurally callable value is a function whatever its name says.
+ callable_kind = (
+ declarator_binds_callable(def_node, src) if language in _TS_JS_LANGUAGES else None
+ )
+ return callable_kind or ("constant" if name.isupper() else "variable")
+
+
+def _attribute_decorators(def_node: Node, language: str, src: str) -> list[str]:
+ """Attribute texts that act as decorators (Rust, C#, C/C++), brackets stripped.
+
+ They land beside ``@`` decorators so one deprecation check reads them all.
+ """
+ if language == "rust":
+ return _rust_outer_attributes(def_node, src)
+ # C#: [Obsolete] / [System.Obsolete] are ``attribute_list`` nodes.
+ # In tree-sitter-c-sharp the attribute_list is child[0] of the
+ # declaration node itself (method_declaration, class_declaration, etc.),
+ # NOT a preceding sibling in the class body.
+ if language == "csharp":
+ return _leading_child_attributes(def_node, "attribute_list", "[", "]", src)
+ # C/C++: [[deprecated]] / [[deprecated("reason")]] are
+ # ``attribute_declaration`` nodes, child[0] of function_definition itself
+ # (NOT a preceding sibling at translation_unit level).
+ if language in ("cpp", "c"):
+ return _leading_child_attributes(def_node, "attribute_declaration", "[[", "]]", src)
+ return []
+
+
+def _rust_outer_attributes(def_node: Node, src: str) -> list[str]:
+ """Rust: outer attributes (#[...]) are preceding siblings of the item."""
+ attrs: list[str] = []
+ if def_node.parent is None:
+ return attrs
+ siblings = def_node.parent.children
+ for j, sib in enumerate(siblings):
+ if sib.id != def_node.id:
+ continue
+ k = j - 1
+ while k >= 0 and siblings[k].type == "attribute_item":
+ attr_text = _node_text(siblings[k], src).strip()
+ # Strip #[ and ] to get the inner attribute text
+ if attr_text.startswith("#[") and attr_text.endswith("]"):
+ attrs.append(attr_text[2:-1])
+ k -= 1
+ break
+ return attrs
+
+
+def _leading_child_attributes(
+ def_node: Node, node_type: str, opener: str, closer: str, src: str
+) -> list[str]:
+ """Inner text of the attribute children leading *def_node*, until the first other child."""
+ attrs: list[str] = []
+ for child in def_node.children:
+ if child.type != node_type:
+ break
+ attr_text = _node_text(child, src).strip()
+ if attr_text.startswith(opener) and attr_text.endswith(closer):
+ attrs.append(attr_text[len(opener) : -len(closer)])
+ return attrs
+
+
+def _refine_visibility(
+ def_node: Node,
+ language: str,
+ visibility: str,
+ name: str,
+ ts_deferred_exports: frozenset[str] | None,
+ src: str,
+) -> tuple[str, bool]:
+ """``(visibility, is_exported_symbol)`` after the language's AST-context rules."""
+ # C/C++ visibility is dictated by AST context (access
+ # specifiers / storage class / export attributes), not by
+ # modifier text. Refine after the generic fn ran.
+ if language in ("cpp", "c"):
+ return refine_cpp_visibility(def_node, visibility, src)
+ # C#: an unmodified declaration's default depends on what encloses
+ # it, which the modifier-text fn cannot see.
+ if language == "csharp":
+ return refine_csharp_visibility(def_node, visibility), False
+ # TS/JS: a top-level declaration is only public when exported —
+ # inline, via ``export { x }`` lists, or ``export default x``.
+ if language in _TS_JS_LANGUAGES:
+ return refine_ts_visibility(def_node, visibility, name, ts_deferred_exports), False
+ # Rust: a trait's items may not write ``pub`` of their own, so the
+ # trait's modifier is the only place their visibility is stated.
+ if language == "rust":
+ return refine_rust_visibility(def_node, visibility, src), False
+ return visibility, False
+
+
+def _dart_mixin_parent(def_node: Node, config: LanguageConfig, src: str) -> str | None:
+ """Name of the Dart ``mixin`` enclosing *def_node*, if it is the nearest type."""
+ ancestor = def_node.parent
+ while ancestor is not None:
+ if ancestor.type == "mixin_declaration":
+ ident = next((c for c in ancestor.children if c.type == "identifier"), None)
+ return _node_text(ident, src) if ident is not None else None
+ if ancestor.type in config.parent_class_types:
+ return None
+ ancestor = ancestor.parent
+ return None
+
+
+def _pascal_imports(
+ stmt_node: Node, module_node: Node, src: str, seen_units: set[str]
+) -> list[Import]:
+ """One Pascal ``uses`` unit, deduped case-insensitively across the file.
+
+ pascal.scm fires once per unit name, so a 3-unit clause arrives as 3
+ matches sharing one statement span: deduping by raw text would drop all
+ but the first. A unit named in both ``uses`` clauses is one dependency.
+ ``uses`` exposes the unit's whole interface, hence the ``*`` wildcard.
+ """
+ raw = _node_text(stmt_node, src).strip()
+ unit_name = _node_text(module_node, src).strip()
+ if not unit_name or unit_name.lower() in seen_units:
+ return []
+ seen_units.add(unit_name.lower())
+ return [
+ Import(
+ raw_statement=raw,
+ module_path=unit_name,
+ imported_names=["*"],
+ is_relative=False,
+ resolved_file=None,
+ bindings=[],
+ is_reexport=False,
+ )
+ ]
+
+
+def _elixir_imports(
+ stmt_node: Node, module_node: Node, src: str, seen_modules: set[str]
+) -> list[Import]:
+ """Elixir directives, one Import per module and deduped by module path.
+
+ ``alias Foo.{Bar, Baz}`` names two modules in one statement. ``import``
+ pulls in every public function (``*``); alias/require/use bind the module.
+ """
+ raw = _node_text(stmt_node, src).split("\n", 1)[0].strip()
+ directive_node = stmt_node.child_by_field_name("target")
+ directive = _node_text(directive_node, src).strip() if directive_node else ""
+ imports: list[Import] = []
+ for module_path in elixir_import_modules(module_node, src):
+ if module_path in seen_modules:
+ continue
+ seen_modules.add(module_path)
+ imports.append(
+ Import(
+ raw_statement=raw,
+ module_path=module_path,
+ imported_names=["*"] if directive == "import" else [],
+ is_relative=False,
+ resolved_file=None,
+ bindings=[],
+ is_reexport=False,
+ )
+ )
+ return imports
+
+
+def _fsharp_imports(
+ stmt_node: Node, module_node: Node, src: str, seen_raws: set[str]
+) -> list[Import]:
+ """F# ``open``: every public name of the module (``*``), which bare-name
+ call resolution reads. ``open type A.B.T`` binds the type's static members,
+ so the module the file depends on is ``A.B``.
+ """
+ raw = _node_text(stmt_node, src).strip()
+ if raw in seen_raws:
+ return []
+ seen_raws.add(raw)
+ module_path = _node_text(module_node, src).strip()
+ if not module_path:
+ return []
+ names: list[str] = ["*"]
+ if any(child.type == "type" for child in stmt_node.children):
+ head, _, type_name = module_path.rpartition(".")
+ if head:
+ module_path, names = head, [type_name]
+ else:
+ names = []
+ return [
+ Import(
+ raw_statement=raw,
+ module_path=module_path,
+ imported_names=names,
+ is_relative=False,
+ resolved_file=None,
+ bindings=[],
+ is_reexport=False,
+ )
+ ]
+
+
+def _statement_imports(
+ stmt_node: Node,
+ module_node: Node,
+ module_text: str,
+ raw: str,
+ language: str,
+ src: str,
+) -> list[Import]:
+ """The imports one deduplicated statement declares."""
+ if language == "scala" and stmt_node.type == "import_declaration":
+ return _scala_imports(stmt_node, raw, src)
+ if language == "php" and stmt_node.type == "namespace_use_declaration":
+ return _php_imports(stmt_node, raw, src)
+ if language == "dart":
+ return [_dart_import(stmt_node, module_node, module_text, raw, src)]
+ if language in _TS_JS_LANGUAGES and _is_dynamic_esm_import(stmt_node):
+ # ``import('./mod')`` binds a module namespace at runtime, so it is a
+ # wildcard, which keeps the target's exports live.
+ return [
+ Import(
+ raw_statement=raw,
+ module_path=module_text,
+ imported_names=["*"],
+ is_relative=module_text.startswith("."),
+ resolved_file=None,
+ bindings=[],
+ is_reexport=False,
+ )
+ ]
+ if language in ("javascript", "typescript") and stmt_node.type in (
+ "assignment_expression",
+ "call_expression",
+ ):
+ return _cjs_imports(stmt_node, raw, src)
+ return [_generic_import(stmt_node, module_text, raw, language, src)]
+
+
+def _scala_imports(stmt_node: Node, raw: str, src: str) -> list[Import]:
+ """Scala: one Import per selected name, with full dotted paths.
+
+ The query's ``(identifier)`` capture is only the first path segment, and
+ one declaration can hold several clauses, brace selectors, renames and
+ wildcards.
+ """
+ from .extractors.bindings.scala import expand_scala_import_clauses
+ from .models import NamedBinding
+
+ imports: list[Import] = []
+ for clause_path, clause_names in expand_scala_import_clauses(stmt_node, src):
+ local = clause_names[0]
+ exported = None if local == "*" else clause_path.rsplit(".", 1)[-1]
+ imports.append(
+ Import(
+ raw_statement=raw,
+ module_path=clause_path,
+ imported_names=clause_names,
+ is_relative=False,
+ resolved_file=None,
+ bindings=[
+ NamedBinding(
+ local_name=local,
+ exported_name=exported,
+ source_file=None,
+ )
+ ],
+ is_reexport=False,
+ )
+ )
+ return imports
+
+
+def _php_imports(stmt_node: Node, raw: str, src: str) -> list[Import]:
+ """PHP: one ``use`` declaration can name several classes, each its own file."""
+ from .extractors.bindings.php import php_use_clauses
+ from .models import NamedBinding
+
+ return [
+ Import(
+ raw_statement=raw,
+ module_path=fqn,
+ imported_names=[local],
+ is_relative=False,
+ resolved_file=None,
+ bindings=[NamedBinding(local_name=local, exported_name=fqn, source_file=None)],
+ is_reexport=False,
+ )
+ for fqn, local in php_use_clauses(stmt_node, src)
+ ]
+
+
+def _dart_import(
+ stmt_node: Node, module_node: Node, module_text: str, raw: str, src: str
+) -> Import:
+ """Dart: URIs are relative unless schemed, ``export`` re-exports, and the
+ dotted ``part of library.name;`` form resolves through ``library:``.
+ """
+ module_path = module_text
+ if module_node.type == "dotted_identifier_list":
+ module_path = f"library:{module_text}"
+ imported_names, bindings = extract_import_bindings(stmt_node, src, "dart")
+ return Import(
+ raw_statement=raw,
+ module_path=module_path,
+ imported_names=imported_names,
+ is_relative=not module_path.startswith(("package:", "dart:", "library:")),
+ resolved_file=None,
+ bindings=bindings,
+ is_reexport=stmt_node.type == "library_export",
+ )
+
+
+def _is_dynamic_esm_import(stmt_node: Node) -> bool:
+ if stmt_node.type != "call_expression":
+ return False
+ fn = stmt_node.child_by_field_name("function")
+ return fn is not None and fn.type == "import"
+
+
+def _cjs_imports(stmt_node: Node, raw: str, src: str) -> list[Import]:
+ """CommonJS: every ``require()`` in the statement, re-exports marked.
+
+ A hub like ``Object.assign(module.exports, require('./a'), ...)`` is
+ several imports, and ``module.exports`` shapes are barrels.
+ """
+ from .extractors.bindings.ts_js import (
+ cjs_statement_is_reexport,
+ collect_cjs_requires,
+ )
+
+ cjs_reexport = cjs_statement_is_reexport(stmt_node, src)
+ return [
+ Import(
+ raw_statement=raw,
+ module_path=cjs_module,
+ imported_names=["*"] if cjs_reexport else [],
+ is_relative=cjs_module.startswith("."),
+ resolved_file=None,
+ bindings=[],
+ is_reexport=cjs_reexport,
+ )
+ for cjs_module in collect_cjs_requires(stmt_node, src)
+ ]
+
+
+def _generic_import(
+ stmt_node: Node, module_text: str, raw: str, language: str, src: str
+) -> Import:
+ """The single Import of a statement no language-specific shape claims."""
+ if language == "rust" and stmt_node.type == "mod_item":
+ module_text = _rust_mod_path_attribute(stmt_node, src) or module_text
+
+ # JVM wildcard imports: the query captures the scoped identifier only,
+ # so ``import com.foo.*`` arrives as ``com.foo``. Restore the ``.*``.
+ if language in ("java", "kotlin") and not module_text.endswith("*"):
+ stmt_text = raw.rstrip().rstrip(";").rstrip()
+ if stmt_text.endswith(".*"):
+ module_text += ".*"
+
+ # Language-specific import name + binding extraction
+ imported_names, bindings = extract_import_bindings(stmt_node, src, language)
+ is_relative = (
+ module_text.startswith(".")
+ or module_text.startswith("./")
+ or module_text.startswith(("self::", "super::", "crate::"))
+ )
+ return Import(
+ raw_statement=raw,
+ module_path=module_text,
+ imported_names=imported_names,
+ is_relative=is_relative,
+ resolved_file=None,
+ bindings=bindings,
+ is_reexport=_is_reexport_import(stmt_node, raw, language),
+ )
+
+
+def _rust_mod_path_attribute(stmt_node: Node, src: str) -> str | None:
+ """The ``#[path = "..."]`` override on a Rust ``mod`` item, if any.
+
+ Outer attributes are preceding siblings of the item, not children.
+ """
+ parent = stmt_node.parent
+ if parent is None:
+ return None
+ siblings = parent.children
+ for j, sib in enumerate(siblings):
+ if sib.id != stmt_node.id:
+ continue
+ # Walk backward through preceding attribute_item siblings
+ k = j - 1
+ while k >= 0 and siblings[k].type == "attribute_item":
+ path_match = re.search(r'path\s*=\s*"([^"]+)"', _node_text(siblings[k], src))
+ if path_match:
+ return path_match.group(1)
+ k -= 1
+ return None
+ return None
+
+
+def _is_reexport_import(stmt_node: Node, raw: str, language: str) -> bool:
+ """``pub use`` (Rust) and ``@_exported import`` (Swift) re-export the module."""
+ if language == "rust" and stmt_node.type == "use_declaration":
+ return any(child.type == "visibility_modifier" for child in stmt_node.children)
+ return language == "swift" and raw.startswith("@_exported")
+
+
class ASTParser:
"""Unified AST parser — works for all languages via .scm query files.
@@ -1203,6 +1310,7 @@ class ASTParser:
file_info: FileInfo,
src: str,
) -> list[Symbol]:
+ language = file_info.language
symbols: list[Symbol] = []
seen: set[tuple[int, str]] = set() # (start_line, name) — dedup decorated dupes
# Parallel to ``symbols`` (same indices) -- only populated/consumed
@@ -1218,512 +1326,212 @@ class ASTParser:
# Deferred-export names (``export { x }`` / ``export default x``),
# computed once per file for the TS/JS visibility refinement.
ts_deferred_exports: frozenset[str] | None = None
- if file_info.language in _TS_JS_LANGUAGES:
+ if language in _TS_JS_LANGUAGES:
ts_deferred_exports = ts_deferred_export_names(src)
-
- # 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 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":
- 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", [])
- macro_nodes = capture_dict.get("symbol.cpp_export_macro", [])
- if not type_nodes or not def_nodes or not name_nodes:
- continue
- type_name = _node_text(name_nodes[0], src)
- if not type_name:
- continue
- 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)
+ cpp_exports = (
+ collect_cpp_export_types(matches, src) if language == "cpp" else CppExportTypes()
+ )
for capture_dict in matches:
- def_nodes = capture_dict.get("symbol.def", [])
- name_nodes = capture_dict.get("symbol.name", [])
- 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:
+ built = self._symbol_from_match(
+ capture_dict, config, file_info, src, cpp_exports, ts_deferred_exports, seen
+ )
+ if built is None:
continue
+ symbol, def_node = built
+ symbols.append(symbol)
+ node_types.append(def_node.type)
+ if language == "objectivec":
+ container = _objc_container_node(def_node, config.parent_class_types)
+ objc_container_kinds.append(container.type if container else None)
- def_node = def_nodes[0]
- name = config.symbol_name_fn(_node_text(name_nodes[0], src), def_node.type)
- if not name:
- continue
+ if language == "pascal":
+ symbols = _dedupe_pascal_interface_symbols(symbols, node_types)
- if file_info.language == "elixir":
- # A `def` inside `quote do ... end` is macro body, not a
- # definition of the module that writes it.
- if _elixir_is_template_definition(def_node, src):
- continue
- # `defimpl Proto, for: Type` is named for the module the
- # compiler generates, not for the protocol alone.
- name = _elixir_symbol_name(def_node, name, src)
-
- elif file_info.language == "objectivec":
- # `typedef NS_ENUM(NSInteger, Kind) { ... }` has no grammar
- # rule, so only its enum *cases* survive as declarators and
- # each would become a symbol named as though it were the type.
- if _objc_is_macro_enum(def_node, src):
- continue
- # A method is named by its whole selector
- # (`initWithName:age:`), which no single node holds, and a
- # category by the class it extends plus its own name.
- name = _objc_symbol_name(def_node, name, src)
-
- export_type = cpp_export_type_defs.get(def_node.id)
- 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
+ # A .m file routinely declares its private methods in a class
+ # extension and defines them below in the @implementation, which
+ # builds each symbol id twice in one file.
+ if language == "objectivec":
+ symbols = _dedupe_objc_interface_symbols(symbols, node_types, objc_container_kinds)
- 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
+ return symbols
- 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
- seen.add(dedup_key)
+ def _symbol_from_match(
+ self,
+ capture_dict: dict,
+ config: LanguageConfig,
+ file_info: FileInfo,
+ src: str,
+ cpp_exports: CppExportTypes,
+ ts_deferred_exports: frozenset[str] | None,
+ seen: set[tuple[int, str]],
+ ) -> tuple[Symbol, Node] | None:
+ """One query match as a symbol and its definition node, or None to drop it.
+
+ Records the match's ``(start_line, name)`` in *seen* once it passes the
+ name checks, so a later duplicate is dropped even if this one is.
+ """
+ language = file_info.language
+ identity = _match_identity(capture_dict, config, language, src, cpp_exports, seen)
+ if identity is None:
+ return None
+ def_node, name_nodes, name, export_type, start_line = identity
- # Kind from node type
- node_type = def_node.type
- kind = config.symbol_node_types.get(node_type)
- if kind is None:
- continue
+ node_type = def_node.type
+ kind = self._symbol_kind(def_node, config, language, src, cpp_exports.parent_ids)
+ if kind is None:
+ return None
- # Skip symbols nested inside another function/method body. The
- # Tree-sitter query is recursive, so helpers defined inside a
- # React component or an async orchestrator method get hoisted
- # to the top-level symbol list and read as unused public
- # exports. Filtering by callable ancestor restricts extraction
- # to module-top-level + class-body members. Class bodies don't
- # match (``class_definition`` is not callable), so methods are
- # preserved. Module-anchored node types skip the check: their
- # .scm patterns only match at module/program level, and a TS
- # variable_declarator's parent (lexical_declaration → "function")
- # would otherwise read as a callable ancestor.
- if node_type not in _MODULE_ANCHORED_NODE_TYPES and _has_callable_ancestor(
- def_node, config.symbol_node_types, cpp_export_type_parent_ids
- ):
- continue
+ end_line = _symbol_end_line(def_node, config, language, export_type)
+ if end_line is None:
+ return None
- # F#: a ``let`` nested in another binding's body has the same node
- # shape as a top-level one, so the ancestor filter above cannot
- # see it -- what it captures is the binding's left-hand side, and
- # a nested binding's left-hand side has no callable ancestor
- # either. A ``let`` inside a type body is a field and stays.
- if file_info.language == "fsharp" and node_type in (
- "function_declaration_left",
- "value_declaration_left",
- ):
- if _fsharp_binding_is_nested(def_node):
- continue
- # A value binding that carries parameter patterns beside its
- # name is a function the grammar reparsed as a value because
- # of its return-type annotation.
- if node_type == "value_declaration_left" and _fsharp_binding_has_params(
- def_node
- ):
- kind = "function"
-
- # Refine "struct" kind for Go type_spec (check if struct or interface body)
- if kind == "struct" and config.parent_extraction == "receiver":
- kind = refine_go_type_kind(def_node, src)
-
- # Refine "class" kind for Kotlin (interface / enum class share class_declaration)
- if (
- kind == "class"
- and file_info.language == "kotlin"
- and def_node.type == "class_declaration"
- ):
- kind = refine_kotlin_class_kind(def_node)
-
- # Refine "class" kind for Pascal (declType wraps class / record /
- # object / interface / class-helper / enum / set / array / alias
- # in one node shape -- see the spec docstring and
- # refine_pascal_type_kind's own docstring for the disambiguation).
- if kind == "class" and file_info.language == "pascal" and def_node.type == "declType":
- kind = refine_pascal_type_kind(def_node)
-
- # Elixir: every definition is a ``call``, so the node type cannot
- # name the kind and the config maps it to a deliberately
- # non-callable placeholder (see refine_elixir_call_kind). The
- # keyword in the call's target is what actually says what was
- # defined.
- if file_info.language == "elixir" and def_node.type == "call":
- kind = refine_elixir_call_kind(def_node, src)
-
- # F# writes a class, a struct and an interface with the same
- # ``anon_type_defn`` node; only the body says which it is.
- if (
- kind == "class"
- and file_info.language == "fsharp"
- and def_node.type == "anon_type_defn"
- ):
- kind = refine_fsharp_type_kind(def_node)
-
- # Dart: a function is a ``function_signature`` whose BODY is a
- # sibling ``function_body`` node (members wrap the signature in
- # ``method_signature``). Two consequences the generic path can't
- # see: local functions nested inside another function's body have
- # no callable *ancestor* (the enclosing signature is a sibling),
- # so filter them here; and the symbol's line range must extend to
- # the trailing body sibling or call-site attribution stops at the
- # signature line.
- end_line = def_node.end_point[0] + 1
- if config.symbol_end_line_fn is not None:
- end_line = config.symbol_end_line_fn(def_node, end_line)
- if export_type is not None:
- end_line = export_type.range_node.end_point[0] + 1
- # F#: the captured node is the binding's left-hand side, so its
- # own span stops at the parameter list. Extend it over the body
- # (and any return-type annotation between the two) or every call
- # in the body is attributed to whatever encloses the binding.
- if file_info.language == "fsharp" and node_type in (
- "function_declaration_left",
- "value_declaration_left",
- ):
- end_line = _fsharp_binding_end_line(def_node)
- if file_info.language == "dart" and node_type in (
- "function_signature",
- "getter_signature",
- "setter_signature",
- ):
- ancestor = def_node.parent
- is_local = False
- while ancestor is not None:
- if ancestor.type in ("function_body", "function_expression"):
- is_local = True
- break
- ancestor = ancestor.parent
- if is_local:
- continue
- anchor = def_node
- if def_node.parent is not None and def_node.parent.type == "method_signature":
- anchor = def_node.parent
- body_sibling = anchor.next_named_sibling
- if body_sibling is not None and body_sibling.type == "function_body":
- end_line = body_sibling.end_point[0] + 1
-
- # Refine module-level assignments: SCREAMING_CASE names are
- # constants by convention; the rest are module variables
- # (singletons like ``app = FastAPI()``, registries, caches).
- # ``str.isupper()`` requires at least one cased char, so names
- # with no letters (``_``, ``__all__``) fall to "variable" rather
- # than being mislabelled constants by ``name == name.upper()``.
- if node_type in _MODULE_ANCHORED_NODE_TYPES:
- # TS/JS: the symbol query admits call_expression values so
- # forwardRef / memo / onCall / styled() bindings exist at all,
- # which also lets `const svc = require('./svc')` through. Those
- # bind a module and are already imports — drop them here rather
- # than in the query, which cannot see past the await / paren /
- # non-null / member-pick shells.
- if file_info.language in _TS_JS_LANGUAGES and declarator_value_is_module_ref(
- def_node, src
- ):
- continue
- # A declarator whose value is structurally callable is not
- # data, whatever its name looks like: `const C =
- # forwardRef(fn)` and `const f = function(){}` are a component
- # and a function. Naming decides only for the rest, which is
- # what it was ever able to answer.
- callable_kind = (
- declarator_binds_callable(def_node, src)
- if file_info.language in _TS_JS_LANGUAGES
- else None
- )
- kind = callable_kind or ("constant" if name.isupper() else "variable")
-
- # Params signature text
- params_text = _node_text(params_nodes[0], src) if params_nodes else ""
-
- # Visibility
- modifier_texts = [_node_text(m, src) for m in modifier_nodes]
-
- # Rust: outer attributes (#[...]) are preceding siblings of the item
- rust_attrs: list[str] = []
- if file_info.language == "rust" and def_node.parent is not None:
- siblings = def_node.parent.children
- for j, sib in enumerate(siblings):
- if sib.id == def_node.id:
- k = j - 1
- while k >= 0 and siblings[k].type == "attribute_item":
- attr_text = _node_text(siblings[k], src).strip()
- # Strip #[ and ] to get the inner attribute text
- if attr_text.startswith("#[") and attr_text.endswith("]"):
- rust_attrs.append(attr_text[2:-1])
- k -= 1
- break
-
- # C#: [Obsolete] / [System.Obsolete] are ``attribute_list`` nodes.
- # In tree-sitter-c-sharp the attribute_list is child[0] of the
- # declaration node itself (method_declaration, class_declaration, etc.),
- # NOT a preceding sibling in the class body. Iterate def_node.children
- # and collect attribute_list nodes until the first non-attribute child.
- # Strip the outer [ ] so the inner content matches the same
- # _DEPRECATED_DECORATOR_BASES the analyzer uses for every other lang.
- csharp_attrs: list[str] = []
- if file_info.language == "csharp":
- for child in def_node.children:
- if child.type != "attribute_list":
- break
- attr_text = _node_text(child, src).strip()
- # "[Obsolete]" → "Obsolete"
- if attr_text.startswith("[") and attr_text.endswith("]"):
- csharp_attrs.append(attr_text[1:-1])
-
- # C/C++: [[deprecated]] / [[deprecated("reason")]] are
- # ``attribute_declaration`` nodes. In tree-sitter-cpp the
- # attribute_declaration is child[0] of function_definition itself
- # (NOT a preceding sibling at translation_unit level). Iterate
- # def_node.children and collect attribute_declaration nodes until
- # the first non-attribute child.
- # Strip the outer [[ ]] so the inner content lands in the same
- # checker as the Rust and C# forms.
- cpp_attrs: list[str] = []
- if file_info.language in ("cpp", "c"):
- for child in def_node.children:
- if child.type != "attribute_declaration":
- break
- attr_text = _node_text(child, src).strip()
- # "[[deprecated]]" → "deprecated"
- if attr_text.startswith("[[") and attr_text.endswith("]]"):
- cpp_attrs.append(attr_text[2:-2])
-
- visibility = config.visibility_fn(name, modifier_texts)
- is_exported_symbol = False
- # C/C++ visibility is dictated by AST context (access
- # specifiers / storage class / export attributes), not by
- # modifier text. Refine after the generic fn ran.
- if file_info.language in ("cpp", "c"):
- visibility, is_exported_symbol = refine_cpp_visibility(def_node, visibility, src)
- # C#: an unmodified declaration's default depends on what encloses
- # it, which the modifier-text fn cannot see.
- elif file_info.language == "csharp":
- visibility = refine_csharp_visibility(def_node, visibility)
- # TS/JS: a top-level declaration is only public when exported —
- # inline, via ``export { x }`` lists, or ``export default x``.
- elif file_info.language in _TS_JS_LANGUAGES:
- visibility = refine_ts_visibility(def_node, visibility, name, ts_deferred_exports)
- # Rust: a trait's items may not write ``pub`` of their own, so the
- # trait's modifier is the only place their visibility is stated.
- elif file_info.language == "rust":
- visibility = refine_rust_visibility(def_node, visibility, src)
-
- # Parent class detection
- parent_name = self._find_parent(def_node, config, receiver_nodes, src)
-
- if parent_name is None and file_info.language == "cpp" and export_type is None:
- parent_name = _cpp_export_macro_parent(def_node, cpp_export_type_parents)
-
- # Dart mixin_declaration exposes no ``name`` field, so
- # ``_find_parent``'s field lookup misses mixin members.
- if parent_name is None and file_info.language == "dart":
- ancestor = def_node.parent
- while ancestor is not None:
- if ancestor.type == "mixin_declaration":
- ident = next((c for c in ancestor.children if c.type == "identifier"), None)
- if ident is not None:
- parent_name = _node_text(ident, src)
- break
- if ancestor.type in config.parent_class_types:
- break
- ancestor = ancestor.parent
-
- # F#: no type node carries a ``name`` field -- the name hangs off
- # a ``type_name`` child -- so the generic walk finds the ancestor
- # and then reads nothing off it.
- if parent_name is None and file_info.language == "fsharp":
- parent_name = _fsharp_parent_name(def_node, src)
-
- # C/C++ qualified definitions: ``void Foo::method() { … }``
- # carries the class as the scope of a ``qualified_identifier``
- # parent of the name node. Without this resolution, every
- # ``Class::method`` lands as a free function and bloats the
- # unused_export pass with thousands of method symbols.
- if parent_name is None and file_info.language in ("cpp", "c") and name_nodes:
- parent_name = _qualified_cpp_parent(name_nodes[0], src)
-
- # Pascal out-of-line implementation: ``function TFoo.Bar(...);``
- # -- the ``defProc`` node lives in the unit's implementation
- # section, outside the class's ``declType`` body declared in the
- # interface section, so nesting-based ``_find_parent`` above
- # can't see it. The qualifying class lives beside the captured
- # name in the ``genericDot`` header instead.
- if parent_name is None and file_info.language == "pascal" and name_nodes:
- parent_name = _qualified_pascal_parent(name_nodes[0], src)
-
- # Elixir: the enclosing ``defmodule`` is a ``call`` with no
- # ``name`` field for the generic nesting walk to read, so the
- # module name has to be dug out of its first argument.
- if parent_name is None and file_info.language == "elixir":
- parent_name = _elixir_module_parent(def_node, src)
-
- # Objective-C: an @interface / @implementation / @protocol names
- # itself with a bare first identifier and no ``name`` field, so
- # the nesting walk above finds the right ancestor and reads
- # nothing off it.
- if parent_name is None and file_info.language == "objectivec":
- parent_name = _objc_container_parent(def_node, config.parent_class_types, src)
-
- # A ``field_declaration`` cannot occur outside a class body, so a
- # missing parent means the class did not parse. Grammar recovery,
- # not a member function.
- if node_type == "function_declarator" and parent_name is None:
- continue
+ if node_type in _MODULE_ANCHORED_NODE_TYPES:
+ kind = _module_binding_kind(def_node, name, language, src)
+ if kind is None:
+ return None
+
+ modifier_texts = [_node_text(m, src) for m in capture_dict.get("symbol.modifiers", [])]
+ visibility, is_exported_symbol = _refine_visibility(
+ def_node,
+ language,
+ config.visibility_fn(name, modifier_texts),
+ name,
+ ts_deferred_exports,
+ src,
+ )
- # Upgrade function → method when a parent class is detected.
- # F#: a nested module is a parent too (for id uniqueness), but it
- # is not a type, so a `let` inside one stays a function.
- if parent_name and kind == "function" and (
- file_info.language != "fsharp" or _fsharp_parent_is_type(def_node)
- ):
- kind = "method"
+ parent_name = self._resolve_parent_name(
+ def_node,
+ config,
+ capture_dict.get("symbol.receiver", []),
+ name_nodes,
+ language,
+ src,
+ no_export_type=export_type is None,
+ export_type_parents=cpp_exports.parents,
+ )
- # Build signature
- signature = build_signature(node_type, name, params_text, def_node, src)
+ # A ``field_declaration`` cannot occur outside a class body, so a
+ # missing parent means the class did not parse. Grammar recovery,
+ # not a member function.
+ if node_type == "function_declarator" and parent_name is None:
+ return None
- # Docstring
- docstring = extract_symbol_docstring(def_node, src, file_info.language)
+ # Upgrade function → method when a parent class is detected.
+ # F#: a nested module is a parent too (for id uniqueness), but it
+ # is not a type, so a `let` inside one stays a function.
+ if parent_name and kind == "function" and (
+ language != "fsharp" or _fsharp_parent_is_type(def_node)
+ ):
+ kind = "method"
+
+ params_nodes = capture_dict.get("symbol.params", [])
+ params_text = _node_text(params_nodes[0], src) if params_nodes else ""
+ sym_id = (
+ f"{file_info.path}::{parent_name}::{name}"
+ if parent_name
+ else f"{file_info.path}::{name}"
+ )
+ symbol = Symbol(
+ id=sym_id,
+ name=name,
+ qualified_name=_build_qualified_name(file_info.path, parent_name, name),
+ kind=kind, # type: ignore[arg-type]
+ signature=build_signature(node_type, name, params_text, def_node, src),
+ start_line=start_line,
+ end_line=end_line,
+ docstring=extract_symbol_docstring(def_node, src, language),
+ decorators=(
+ [m for m in modifier_texts if m.startswith("@")]
+ + _attribute_decorators(def_node, language, src)
+ ),
+ visibility=visibility, # type: ignore[arg-type]
+ is_async=_is_async_node(def_node, src),
+ language=language,
+ parent_name=parent_name,
+ is_exported_symbol=is_exported_symbol,
+ is_declaration=_is_declaration(def_node, config, language, export_type),
+ )
+ return symbol, def_node
- # Async detection
- is_async = _is_async_node(def_node, src)
+ def _symbol_kind(
+ self,
+ def_node: Node,
+ config: LanguageConfig,
+ language: str,
+ src: str,
+ export_type_parent_ids: frozenset[int],
+ ) -> str | None:
+ """The symbol kind for *def_node*, or None when it is not a symbol here."""
+ node_type = def_node.type
+ kind = config.symbol_node_types.get(node_type)
+ if kind is None:
+ return None
- sym_id = (
- f"{file_info.path}::{parent_name}::{name}"
- if parent_name
- else f"{file_info.path}::{name}"
- )
- qualified = _build_qualified_name(file_info.path, parent_name, name)
-
- symbols.append(
- Symbol(
- id=sym_id,
- name=name,
- qualified_name=qualified,
- kind=kind, # type: ignore[arg-type]
- signature=signature,
- start_line=start_line,
- end_line=end_line,
- docstring=docstring,
- decorators=(
- [m for m in modifier_texts if m.startswith("@")]
- + rust_attrs
- + csharp_attrs
- + cpp_attrs
- ),
- visibility=visibility, # type: ignore[arg-type]
- is_async=is_async,
- language=file_info.language,
- parent_name=parent_name,
- 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)
- )
- ),
- )
- )
- node_types.append(node_type)
- if file_info.language == "objectivec":
- container = _objc_container_node(def_node, config.parent_class_types)
- objc_container_kinds.append(container.type if container else None)
+ # Only module-level and class-body members are symbols; the query is
+ # recursive, so defs nested in a callable are dropped. Module-anchored
+ # node types only match at module level and skip the check.
+ if node_type not in _MODULE_ANCHORED_NODE_TYPES and _has_callable_ancestor(
+ def_node, config.symbol_node_types, export_type_parent_ids
+ ):
+ return None
- if file_info.language == "pascal":
- symbols = _dedupe_pascal_interface_symbols(symbols, node_types)
+ # F#: a ``let`` nested in another binding has no callable ancestor, so
+ # it is checked separately. A ``let`` in a type body is a field and stays.
+ if _is_fsharp_binding(language, node_type) and _fsharp_binding_is_nested(def_node):
+ return None
+ return _refine_symbol_kind(kind, def_node, config, language, src)
- # A .m file routinely declares its private methods in a class
- # extension and defines them below in the @implementation, which
- # builds each symbol id twice in one file.
- if file_info.language == "objectivec":
- symbols = _dedupe_objc_interface_symbols(symbols, node_types, objc_container_kinds)
+ def _resolve_parent_name(
+ self,
+ def_node: Node,
+ config: LanguageConfig,
+ receiver_nodes: list[Node],
+ name_nodes: list[Node],
+ language: str,
+ src: str,
+ *,
+ no_export_type: bool,
+ export_type_parents: dict[int, str],
+ ) -> str | None:
+ """The enclosing type or module name, trying each language's own shape."""
+ parent_name = self._find_parent(def_node, config, receiver_nodes, src)
+ if parent_name is not None:
+ return parent_name
- return symbols
+ if language == "cpp" and no_export_type:
+ parent_name = _cpp_export_macro_parent(def_node, export_type_parents)
+ if parent_name is not None:
+ return parent_name
+
+ # Dart mixin_declaration exposes no ``name`` field, so
+ # ``_find_parent``'s field lookup misses mixin members.
+ if language == "dart":
+ return _dart_mixin_parent(def_node, config, src)
+
+ # F#: no type node carries a ``name`` field -- the name hangs off
+ # a ``type_name`` child -- so the generic walk finds the ancestor
+ # and then reads nothing off it.
+ if language == "fsharp":
+ return _fsharp_parent_name(def_node, src)
+
+ # C/C++ out-of-line ``void Foo::method()`` names its class in the scope.
+ if language in ("cpp", "c") and name_nodes:
+ return _qualified_cpp_parent(name_nodes[0], src)
+
+ # Pascal out-of-line ``function TFoo.Bar`` names its class in the header.
+ if language == "pascal" and name_nodes:
+ return _qualified_pascal_parent(name_nodes[0], src)
+
+ # Elixir: ``defmodule`` is a ``call``; the name is its first argument.
+ if language == "elixir":
+ return _elixir_module_parent(def_node, src)
+
+ # Objective-C containers name themselves with a bare first identifier.
+ if language == "objectivec":
+ return _objc_container_parent(def_node, config.parent_class_types, src)
+ return None
def _find_parent(
self,
@@ -1775,6 +1583,7 @@ class ASTParser:
file_info: FileInfo,
src: str,
) -> list[Import]:
+ language = file_info.language
imports: list[Import] = []
seen_raws: set[str] = set()
seen_pascal_units: set[str] = set()
@@ -1789,121 +1598,19 @@ class ASTParser:
stmt_node = stmt_nodes[0]
- # Pascal: `uses UnitA, UnitB, Ns.UnitC;` -- pascal.scm's
- # unquantified pattern (see that file's comment on why) fires
- # once PER moduleName, so a 3-unit clause arrives as 3 separate
- # matches sharing one @import.statement span, each carrying a
- # single-element ``module_nodes``. Handled before the
- # ``seen_raws`` dedup below: that guard exists to skip a
- # statement re-matched by an *overlapping* pattern (the normal
- # case elsewhere), but here every match legitimately carries a
- # different unit despite the identical raw statement text --
- # dedup-by-raw would keep only the first and silently drop the
- # rest, which is exactly the bug this branch fixes.
- #
- # Deduped separately by unit name (case-insensitive -- Pascal
- # identifiers are): a unit named in both the ``interface`` and
- # ``implementation`` ``uses`` clauses of the same file is a
- # single logical dependency and must not become two Import
- # entries for it.
- if file_info.language == "pascal":
- raw = _node_text(stmt_node, src).strip()
- unit_name = _node_text(module_nodes[0], src).strip()
- if unit_name and unit_name.lower() not in seen_pascal_units:
- seen_pascal_units.add(unit_name.lower())
- imports.append(
- Import(
- raw_statement=raw,
- module_path=unit_name,
- # ``uses UnitA;`` exposes UnitA's ENTIRE public
- # interface section, unlike Python/JS's
- # name-scoped `from x import y` -- Pascal has no
- # per-symbol import syntax to name a specific
- # one. ``imported_names=[]`` (empty, not
- # wildcard) meant dead_code/analyzer.py's
- # `sym_name in imported_names` / `"*" in
- # imported_names` file-level unused-export
- # rescue could structurally never fire for
- # Pascal -- every public symbol fell straight
- # through to the (now Phase-1-fixed, but still
- # best-effort) symbol-level call/type_use
- # rescue instead. ``["*"]`` is this codebase's
- # existing wildcard-import sentinel (see the
- # Python `import *` and CJS re-export branches
- # of this function) and is the semantically
- # correct value here, not a workaround: it says
- # exactly what a Pascal `uses` clause does.
- imported_names=["*"],
- is_relative=False,
- resolved_file=None,
- bindings=[],
- is_reexport=False,
- )
- )
+ # These three dedupe on their own key, before the raw-statement
+ # dedup below.
+ if language == "pascal":
+ imports.extend(_pascal_imports(stmt_node, module_nodes[0], src, seen_pascal_units))
continue
-
- # Elixir: `alias Foo.{Bar, Baz}` names two modules in one
- # statement, so dedup by raw statement text (below) would drop all
- # but the first. Deduped by module path instead, which is also
- # what makes a module aliased twice in one file one dependency.
- if file_info.language == "elixir":
- raw = _node_text(stmt_node, src).split("\n", 1)[0].strip()
- directive_node = stmt_node.child_by_field_name("target")
- directive = _node_text(directive_node, src).strip() if directive_node else ""
- for module_path in elixir_import_modules(module_nodes[0], src):
- if module_path in seen_elixir_modules:
- continue
- seen_elixir_modules.add(module_path)
- imports.append(
- Import(
- raw_statement=raw,
- # `import Foo` pulls in every public function;
- # alias/require/use bind the module itself, which
- # is the same wildcard sentinel the regex tier
- # writes for this language.
- module_path=module_path,
- imported_names=["*"] if directive == "import" else [],
- is_relative=False,
- resolved_file=None,
- bindings=[],
- is_reexport=False,
- )
- )
- continue
-
- # F#: `open Foo.Bar` binds every public name in Foo.Bar, which is
- # the wildcard sentinel this codebase already uses -- and which
- # the call resolver reads to decide which imports a bare name may
- # be looked up in (F# bare names are lexically scoped).
- # `open type Foo.Bar.Baz` binds a TYPE's static members instead,
- # so the module the file depends on is the path holding the type.
- if file_info.language == "fsharp":
- raw = _node_text(stmt_node, src).strip()
- if raw in seen_raws:
- continue
- seen_raws.add(raw)
- module_path = _node_text(module_nodes[0], src).strip()
- if not module_path:
- continue
- names: list[str] = ["*"]
- if any(child.type == "type" for child in stmt_node.children):
- head, _, type_name = module_path.rpartition(".")
- if head:
- module_path, names = head, [type_name]
- else:
- names = []
- imports.append(
- Import(
- raw_statement=raw,
- module_path=module_path,
- imported_names=names,
- is_relative=False,
- resolved_file=None,
- bindings=[],
- is_reexport=False,
- )
+ if language == "elixir":
+ imports.extend(
+ _elixir_imports(stmt_node, module_nodes[0], src, seen_elixir_modules)
)
continue
+ if language == "fsharp":
+ imports.extend(_fsharp_imports(stmt_node, module_nodes[0], src, seen_raws))
+ continue
raw = _node_text(stmt_node, src).strip()
if raw in seen_raws:
@@ -1914,204 +1621,11 @@ class ASTParser:
if not module_text:
continue
- # Scala: the query's ``(identifier)`` capture is only the FIRST
- # path segment (``import com.foo.Bar`` arrived as ``com``), and
- # one declaration can hold several clauses, brace selectors,
- # renames, and wildcards. Reconstruct full dotted paths and emit
- # one Import per selected name.
- if file_info.language == "scala" and stmt_node.type == "import_declaration":
- from .extractors.bindings.scala import expand_scala_import_clauses
- from .models import NamedBinding
-
- for clause_path, clause_names in expand_scala_import_clauses(stmt_node, src):
- local = clause_names[0]
- exported = None if local == "*" else clause_path.rsplit(".", 1)[-1]
- imports.append(
- Import(
- raw_statement=raw,
- module_path=clause_path,
- imported_names=clause_names,
- is_relative=False,
- resolved_file=None,
- bindings=[
- NamedBinding(
- local_name=local,
- exported_name=exported,
- source_file=None,
- )
- ],
- is_reexport=False,
- )
- )
- continue
-
- # PHP: one ``use`` declaration can name several classes, each its
- # own file (``use A\B, C\D;`` and the grouped ``use A\{B, C}``).
- if file_info.language == "php" and stmt_node.type == "namespace_use_declaration":
- from .extractors.bindings.php import php_use_clauses
- from .models import NamedBinding
-
- for fqn, local in php_use_clauses(stmt_node, src):
- imports.append(
- Import(
- raw_statement=raw,
- module_path=fqn,
- imported_names=[local],
- is_relative=False,
- resolved_file=None,
- bindings=[
- NamedBinding(local_name=local, exported_name=fqn, source_file=None)
- ],
- is_reexport=False,
- )
- )
- continue
-
- # Dart: URIs are relative unless schemed (``package:``/``dart:``),
- # ``export`` directives are barrel re-exports, and the legacy
- # dotted ``part of library.name;`` form resolves through the
- # library-name index (the ``library:`` prefix is the resolver's
- # contract, shared with the lightweight regex tier).
- if file_info.language == "dart":
- module_path = module_text
- if module_nodes[0].type == "dotted_identifier_list":
- module_path = f"library:{module_text}"
- imported_names, bindings = extract_import_bindings(
- stmt_node, src, file_info.language
- )
- imports.append(
- Import(
- raw_statement=raw,
- module_path=module_path,
- imported_names=imported_names,
- is_relative=not module_path.startswith(("package:", "dart:", "library:")),
- resolved_file=None,
- bindings=bindings,
- is_reexport=stmt_node.type == "library_export",
- )
- )
- continue
-
- # Dynamic ESM import: ``import('./mod')``. The query captures the
- # call_expression, which would otherwise fall into the CommonJS
- # branch below and be dropped on the floor — a dynamic import
- # holds no ``require()`` for ``collect_cjs_requires`` to find.
- # The construct binds a module namespace at runtime, so record a
- # wildcard rather than a static name. Downstream unused-export
- # analysis treats ``*`` as namespace consumption and therefore
- # keeps the target's exports live without a broad analyzer
- # exemption.
- if (
- file_info.language in _TS_JS_LANGUAGES
- and stmt_node.type == "call_expression"
- and (_fn := stmt_node.child_by_field_name("function")) is not None
- and _fn.type == "import"
- ):
- imports.append(
- Import(
- raw_statement=raw,
- module_path=module_text,
- imported_names=["*"],
- is_relative=module_text.startswith("."),
- resolved_file=None,
- bindings=[],
- is_reexport=False,
- )
- )
- continue
-
- # CommonJS assignment / Object.assign shapes: the query captures
- # the outer statement once; walk it for every require() it
- # contains (a hub like Object.assign(module.exports,
- # require('./a'), require('./b')) is several imports) and mark
- # module.exports/exports shapes as re-exports so barrel logic
- # treats CJS hubs like ESM barrels.
- if file_info.language in ("javascript", "typescript") and stmt_node.type in (
- "assignment_expression",
- "call_expression",
- ):
- from .extractors.bindings.ts_js import (
- cjs_statement_is_reexport,
- collect_cjs_requires,
- )
-
- cjs_reexport = cjs_statement_is_reexport(stmt_node, src)
- for cjs_module in collect_cjs_requires(stmt_node, src):
- imports.append(
- Import(
- raw_statement=raw,
- module_path=cjs_module,
- imported_names=["*"] if cjs_reexport else [],
- is_relative=cjs_module.startswith("."),
- resolved_file=None,
- bindings=[],
- is_reexport=cjs_reexport,
- )
- )
- continue
-
- # Rust #[path = "..."] attribute overrides module file location.
- # In tree-sitter-rust, outer attributes are preceding siblings of
- # the item, not children.
- if file_info.language == "rust" and stmt_node.type == "mod_item":
- parent = stmt_node.parent
- if parent is not None:
- siblings = parent.children
- for j, sib in enumerate(siblings):
- if sib.id == stmt_node.id:
- # Walk backward through preceding attribute_item siblings
- k = j - 1
- while k >= 0 and siblings[k].type == "attribute_item":
- attr_text = _node_text(siblings[k], src)
- path_match = re.search(r'path\s*=\s*"([^"]+)"', attr_text)
- if path_match:
- module_text = path_match.group(1)
- break
- k -= 1
- break
-
- # JVM wildcard imports: the grammar query captures the scoped
- # identifier only — the trailing ``*`` is a sibling node, so
- # ``import com.foo.*`` arrives as ``com.foo`` and the resolvers'
- # package fan-out branch can never fire. Restore it from the
- # raw statement text.
- if file_info.language in ("java", "kotlin") and not module_text.endswith("*"):
- stmt_text = raw.rstrip().rstrip(";").rstrip()
- if stmt_text.endswith(".*"):
- module_text += ".*"
-
- # Language-specific import name + binding extraction
- imported_names, bindings = extract_import_bindings(stmt_node, src, file_info.language)
- is_relative = (
- module_text.startswith(".")
- or module_text.startswith("./")
- or module_text.startswith(("self::", "super::", "crate::"))
- )
-
- is_reexport = False
- if file_info.language == "rust" and stmt_node.type == "use_declaration":
- for child in stmt_node.children:
- if child.type == "visibility_modifier":
- is_reexport = True
- break
- # Swift: ``@_exported import FooKit`` re-exports the module —
- # importers of THIS module see FooKit's symbols too.
- elif file_info.language == "swift" and raw.startswith("@_exported"):
- is_reexport = True
-
- imports.append(
- Import(
- raw_statement=raw,
- module_path=module_text,
- imported_names=imported_names,
- is_relative=is_relative,
- resolved_file=None,
- bindings=bindings,
- is_reexport=is_reexport,
- )
+ imports.extend(
+ _statement_imports(stmt_node, module_nodes[0], module_text, raw, language, src)
)
- if file_info.language == "python":
+ if language == "python":
imports = expand_bare_relative_imports(imports)
return imports
@@ -2159,23 +1673,11 @@ class ASTParser:
if not target_name:
continue
- # Objective-C: a message send binds one `method:` child per
- # keyword, so `[view setTitle:t forState:s]` matches the one
- # query pattern twice. Join the whole selector on the first match
- # so it can meet the symbol side, and drop the rest.
if file_info.language == "objectivec":
- if site_node.type == "message_expression":
- joined = _objc_message_selector(site_node, target_nodes[0], src)
- if joined is None:
- continue
- target_name = joined
- # A block held in a parameter or a local is invoked with C call
- # syntax, so `completionBlock(hit)` is indistinguishable from a
- # call to a C function by name alone. Left in, the resolver
- # binds it to whatever same-named @property the repo holds.
- elif not receiver_nodes and _objc_call_is_block_variable(
- site_node, target_name, src
- ):
+ target_name = _objc_call_target(
+ site_node, target_node, target_name, bool(receiver_nodes), src
+ )
+ if target_name is None:
continue
if target_name in _call_builtins:
@@ -2197,8 +1699,8 @@ class ASTParser:
# capture a receiver from -- so the split happens on the text.
# After the builtin check above, so a name is filtered as written.
if file_info.language == "fsharp" and receiver_name is None and "." in target_name:
- receiver_name, _, target_name = target_name.rpartition(".")
- receiver_name = receiver_name.strip()
+ receiver_part, _, target_name = target_name.rpartition(".")
+ receiver_name = receiver_part.strip()
target_name = target_name.strip()
if not target_name:
continue
@@ -2209,29 +1711,7 @@ class ASTParser:
)
scope_name = _node_text(scope_nodes[0], src).strip() if scope_nodes else None
- arg_count: int | None = None
- if arg_nodes:
- arg_node = arg_nodes[0]
- arg_count = _count_arguments(arg_node)
-
- supplied_props: frozenset[str] | None = None
- if site_node.type in ("jsx_self_closing_element", "jsx_opening_element"):
- props_set: set[str] = set()
- has_spread = False
- for child in site_node.children:
- if child.type == "jsx_attribute":
- for sub in child.children:
- if sub.type in ("property_identifier", "identifier"):
- props_set.add(_node_text(sub, src))
- break
- elif child.type == "jsx_expression":
- for sub in child.children:
- if sub.type == "spread_element":
- has_spread = True
- break
- if not has_spread:
- supplied_props = frozenset(props_set)
-
+ arg_count = _count_arguments(arg_nodes[0]) if arg_nodes else None
caller_id = _find_enclosing_symbol(line, symbol_ranges)
calls.append(
@@ -2248,27 +1728,10 @@ class ASTParser:
if site_node.type in config.reference_call_node_types
else "calls"
),
- supplied_props=supplied_props,
+ supplied_props=_jsx_supplied_props(site_node, src),
)
)
-
- deduplicated: dict[tuple[int, str, str | None], CallSite] = {}
- for call in calls:
- key = (call.line, call.target_name, call.receiver_name)
- existing = deduplicated.get(key)
- # Two of the three scoped-call patterns can match the same two-part call
- # (one keeps the qualifier, one does not) and both dedup to this key, so
- # the richer record has to win whichever order they arrive in. The
- # three-part pattern (ns::util::fn()) never collides here, it's the
- # only pattern that can match a nested qualified_identifier, so it
- # always lands as a fresh key.
- if (
- existing is None
- or (existing.receiver_call is None and call.receiver_call is not None)
- or (existing.scope_name is None and call.scope_name is not None)
- ):
- deduplicated[key] = call
- return list(deduplicated.values())
+ return _dedupe_calls(calls)
def _extract_references(
self,