Navegador

Source Blame History 283 lines
fa82b95… lmata 1 """
fa82b95… lmata 2 C++ AST parser — extracts classes, structs, namespaces, functions, methods,
fa82b95… lmata 3 and #include directives from .cpp, .hpp, .cc, and .cxx files using tree-sitter.
fa82b95… lmata 4 """
fa82b95… lmata 5
fa82b95… lmata 6 import logging
fa82b95… lmata 7 from pathlib import Path
fa82b95… lmata 8
fa82b95… lmata 9 from navegador.graph.schema import EdgeType, NodeLabel
fa82b95… lmata 10 from navegador.graph.store import GraphStore
fa82b95… lmata 11 from navegador.ingestion.parser import LanguageParser
fa82b95… lmata 12
fa82b95… lmata 13 logger = logging.getLogger(__name__)
fa82b95… lmata 14
fa82b95… lmata 15
fa82b95… lmata 16 def _get_cpp_language():
fa82b95… lmata 17 try:
fa82b95… lmata 18 import tree_sitter_cpp as tscpp # type: ignore[import]
fa82b95… lmata 19 from tree_sitter import Language
fa82b95… lmata 20
fa82b95… lmata 21 return Language(tscpp.language())
fa82b95… lmata 22 except ImportError as e:
e5e1a3b… lmata 23 raise ImportError("Install tree-sitter-cpp: pip install tree-sitter-cpp") from e
fa82b95… lmata 24
fa82b95… lmata 25
fa82b95… lmata 26 def _node_text(node, source: bytes) -> str:
fa82b95… lmata 27 return source[node.start_byte : node.end_byte].decode("utf-8", errors="replace")
fa82b95… lmata 28
fa82b95… lmata 29
fa82b95… lmata 30 class CppParser(LanguageParser):
fa82b95… lmata 31 """Parses C++ source files into the navegador graph."""
fa82b95… lmata 32
fa82b95… lmata 33 def __init__(self) -> None:
fa82b95… lmata 34 from tree_sitter import Parser # type: ignore[import]
fa82b95… lmata 35
fa82b95… lmata 36 self._parser = Parser(_get_cpp_language())
fa82b95… lmata 37
fa82b95… lmata 38 def parse_file(self, path: Path, repo_root: Path, store: GraphStore) -> dict[str, int]:
fa82b95… lmata 39 source = path.read_bytes()
fa82b95… lmata 40 tree = self._parser.parse(source)
fa82b95… lmata 41 rel_path = str(path.relative_to(repo_root))
fa82b95… lmata 42
fa82b95… lmata 43 store.create_node(
fa82b95… lmata 44 NodeLabel.File,
fa82b95… lmata 45 {
fa82b95… lmata 46 "name": path.name,
fa82b95… lmata 47 "path": rel_path,
fa82b95… lmata 48 "language": "cpp",
fa82b95… lmata 49 "line_count": source.count(b"\n"),
fa82b95… lmata 50 },
fa82b95… lmata 51 )
fa82b95… lmata 52
fa82b95… lmata 53 stats = {"functions": 0, "classes": 0, "edges": 0}
fa82b95… lmata 54 self._walk(tree.root_node, source, rel_path, store, stats, class_name=None)
fa82b95… lmata 55 return stats
fa82b95… lmata 56
fa82b95… lmata 57 # ── AST walker ────────────────────────────────────────────────────────────
fa82b95… lmata 58
fa82b95… lmata 59 def _walk(
fa82b95… lmata 60 self,
fa82b95… lmata 61 node,
fa82b95… lmata 62 source: bytes,
fa82b95… lmata 63 file_path: str,
fa82b95… lmata 64 store: GraphStore,
fa82b95… lmata 65 stats: dict,
fa82b95… lmata 66 class_name: str | None,
fa82b95… lmata 67 ) -> None:
fa82b95… lmata 68 if node.type in ("class_specifier", "struct_specifier"):
fa82b95… lmata 69 self._handle_class(node, source, file_path, store, stats)
fa82b95… lmata 70 return
fa82b95… lmata 71 if node.type == "function_definition":
fa82b95… lmata 72 self._handle_function(node, source, file_path, store, stats, class_name)
fa82b95… lmata 73 return
fa82b95… lmata 74 if node.type == "preproc_include":
fa82b95… lmata 75 self._handle_include(node, source, file_path, store, stats)
fa82b95… lmata 76 return
fa82b95… lmata 77 if node.type == "namespace_definition":
fa82b95… lmata 78 # Recurse into namespace body
fa82b95… lmata 79 body = node.child_by_field_name("body")
fa82b95… lmata 80 if not body:
e5e1a3b… lmata 81 body = next((c for c in node.children if c.type == "declaration_list"), None)
fa82b95… lmata 82 if body:
fa82b95… lmata 83 for child in body.children:
fa82b95… lmata 84 self._walk(child, source, file_path, store, stats, class_name)
fa82b95… lmata 85 return
fa82b95… lmata 86 for child in node.children:
fa82b95… lmata 87 self._walk(child, source, file_path, store, stats, class_name)
fa82b95… lmata 88
fa82b95… lmata 89 # ── Handlers ──────────────────────────────────────────────────────────────
fa82b95… lmata 90
fa82b95… lmata 91 def _handle_class(
fa82b95… lmata 92 self, node, source: bytes, file_path: str, store: GraphStore, stats: dict
fa82b95… lmata 93 ) -> None:
fa82b95… lmata 94 name_node = node.child_by_field_name("name")
fa82b95… lmata 95 if not name_node:
e5e1a3b… lmata 96 name_node = next((c for c in node.children if c.type == "type_identifier"), None)
fa82b95… lmata 97 if not name_node:
fa82b95… lmata 98 return
fa82b95… lmata 99 name = _node_text(name_node, source)
fa82b95… lmata 100
fa82b95… lmata 101 store.create_node(
fa82b95… lmata 102 NodeLabel.Class,
fa82b95… lmata 103 {
fa82b95… lmata 104 "name": name,
fa82b95… lmata 105 "file_path": file_path,
fa82b95… lmata 106 "line_start": node.start_point[0] + 1,
fa82b95… lmata 107 "line_end": node.end_point[0] + 1,
fa82b95… lmata 108 "docstring": "",
fa82b95… lmata 109 },
fa82b95… lmata 110 )
fa82b95… lmata 111 store.create_edge(
fa82b95… lmata 112 NodeLabel.File,
fa82b95… lmata 113 {"path": file_path},
fa82b95… lmata 114 EdgeType.CONTAINS,
fa82b95… lmata 115 NodeLabel.Class,
fa82b95… lmata 116 {"name": name, "file_path": file_path},
fa82b95… lmata 117 )
fa82b95… lmata 118 stats["classes"] += 1
fa82b95… lmata 119 stats["edges"] += 1
fa82b95… lmata 120
fa82b95… lmata 121 # Base classes
fa82b95… lmata 122 base_clause = node.child_by_field_name("base_clause")
fa82b95… lmata 123 if not base_clause:
e5e1a3b… lmata 124 base_clause = next((c for c in node.children if c.type == "base_class_clause"), None)
fa82b95… lmata 125 if base_clause:
fa82b95… lmata 126 for child in base_clause.children:
fa82b95… lmata 127 if child.type == "type_identifier":
fa82b95… lmata 128 parent_name = _node_text(child, source)
fa82b95… lmata 129 store.create_edge(
fa82b95… lmata 130 NodeLabel.Class,
fa82b95… lmata 131 {"name": name, "file_path": file_path},
fa82b95… lmata 132 EdgeType.INHERITS,
fa82b95… lmata 133 NodeLabel.Class,
fa82b95… lmata 134 {"name": parent_name, "file_path": file_path},
fa82b95… lmata 135 )
fa82b95… lmata 136 stats["edges"] += 1
fa82b95… lmata 137
fa82b95… lmata 138 # Walk class body for member functions
fa82b95… lmata 139 body = node.child_by_field_name("body")
fa82b95… lmata 140 if not body:
fa82b95… lmata 141 body = next((c for c in node.children if c.type == "field_declaration_list"), None)
fa82b95… lmata 142 if body:
fa82b95… lmata 143 for child in body.children:
fa82b95… lmata 144 if child.type == "function_definition":
fa82b95… lmata 145 self._handle_function(child, source, file_path, store, stats, class_name=name)
fa82b95… lmata 146
fa82b95… lmata 147 def _handle_function(
fa82b95… lmata 148 self,
fa82b95… lmata 149 node,
fa82b95… lmata 150 source: bytes,
fa82b95… lmata 151 file_path: str,
fa82b95… lmata 152 store: GraphStore,
fa82b95… lmata 153 stats: dict,
fa82b95… lmata 154 class_name: str | None,
fa82b95… lmata 155 ) -> None:
fa82b95… lmata 156 declarator = node.child_by_field_name("declarator")
fa82b95… lmata 157 name = self._extract_function_name(declarator, source)
fa82b95… lmata 158 if not name:
fa82b95… lmata 159 return
fa82b95… lmata 160
fa82b95… lmata 161 label = NodeLabel.Method if class_name else NodeLabel.Function
fa82b95… lmata 162 store.create_node(
fa82b95… lmata 163 label,
fa82b95… lmata 164 {
fa82b95… lmata 165 "name": name,
fa82b95… lmata 166 "file_path": file_path,
fa82b95… lmata 167 "line_start": node.start_point[0] + 1,
fa82b95… lmata 168 "line_end": node.end_point[0] + 1,
fa82b95… lmata 169 "docstring": "",
fa82b95… lmata 170 "class_name": class_name or "",
fa82b95… lmata 171 },
fa82b95… lmata 172 )
fa82b95… lmata 173
fa82b95… lmata 174 container_label = NodeLabel.Class if class_name else NodeLabel.File
fa82b95… lmata 175 container_key = (
fa82b95… lmata 176 {"name": class_name, "file_path": file_path} if class_name else {"path": file_path}
fa82b95… lmata 177 )
fa82b95… lmata 178 store.create_edge(
fa82b95… lmata 179 container_label,
fa82b95… lmata 180 container_key,
fa82b95… lmata 181 EdgeType.CONTAINS,
fa82b95… lmata 182 label,
fa82b95… lmata 183 {"name": name, "file_path": file_path},
fa82b95… lmata 184 )
fa82b95… lmata 185 stats["functions"] += 1
fa82b95… lmata 186 stats["edges"] += 1
fa82b95… lmata 187
fa82b95… lmata 188 self._extract_calls(node, source, file_path, name, label, store, stats)
fa82b95… lmata 189
fa82b95… lmata 190 def _extract_function_name(self, declarator, source: bytes) -> str | None:
fa82b95… lmata 191 """Recursively dig through C++ declarator nodes to find the function name."""
fa82b95… lmata 192 if declarator is None:
fa82b95… lmata 193 return None
fa82b95… lmata 194 if declarator.type == "identifier":
fa82b95… lmata 195 return _node_text(declarator, source)
fa82b95… lmata 196 if declarator.type == "qualified_identifier":
fa82b95… lmata 197 # MyClass::method — take the last component
fa82b95… lmata 198 name_node = declarator.child_by_field_name("name")
fa82b95… lmata 199 if name_node:
fa82b95… lmata 200 return _node_text(name_node, source)
fa82b95… lmata 201 # fallback: last identifier child
fa82b95… lmata 202 ids = [c for c in declarator.children if c.type == "identifier"]
fa82b95… lmata 203 if ids:
fa82b95… lmata 204 return _node_text(ids[-1], source)
fa82b95… lmata 205 if declarator.type in ("function_declarator", "pointer_declarator", "reference_declarator"):
fa82b95… lmata 206 inner = declarator.child_by_field_name("declarator")
fa82b95… lmata 207 return self._extract_function_name(inner, source)
fa82b95… lmata 208 # Fallback: first identifier child
fa82b95… lmata 209 for child in declarator.children:
fa82b95… lmata 210 if child.type == "identifier":
fa82b95… lmata 211 return _node_text(child, source)
fa82b95… lmata 212 return None
fa82b95… lmata 213
fa82b95… lmata 214 def _handle_include(
fa82b95… lmata 215 self, node, source: bytes, file_path: str, store: GraphStore, stats: dict
fa82b95… lmata 216 ) -> None:
fa82b95… lmata 217 path_node = node.child_by_field_name("path")
fa82b95… lmata 218 if not path_node:
fa82b95… lmata 219 path_node = next(
fa82b95… lmata 220 (c for c in node.children if c.type in ("string_literal", "system_lib_string")),
fa82b95… lmata 221 None,
fa82b95… lmata 222 )
fa82b95… lmata 223 if not path_node:
fa82b95… lmata 224 return
fa82b95… lmata 225 module = _node_text(path_node, source).strip('<>"')
fa82b95… lmata 226 store.create_node(
fa82b95… lmata 227 NodeLabel.Import,
fa82b95… lmata 228 {
fa82b95… lmata 229 "name": module,
fa82b95… lmata 230 "file_path": file_path,
fa82b95… lmata 231 "line_start": node.start_point[0] + 1,
fa82b95… lmata 232 "module": module,
fa82b95… lmata 233 },
fa82b95… lmata 234 )
fa82b95… lmata 235 store.create_edge(
fa82b95… lmata 236 NodeLabel.File,
fa82b95… lmata 237 {"path": file_path},
fa82b95… lmata 238 EdgeType.IMPORTS,
fa82b95… lmata 239 NodeLabel.Import,
fa82b95… lmata 240 {"name": module, "file_path": file_path},
fa82b95… lmata 241 )
fa82b95… lmata 242 stats["edges"] += 1
fa82b95… lmata 243
fa82b95… lmata 244 def _extract_calls(
fa82b95… lmata 245 self,
fa82b95… lmata 246 fn_node,
fa82b95… lmata 247 source: bytes,
fa82b95… lmata 248 file_path: str,
fa82b95… lmata 249 fn_name: str,
fa82b95… lmata 250 fn_label: str,
fa82b95… lmata 251 store: GraphStore,
fa82b95… lmata 252 stats: dict,
fa82b95… lmata 253 ) -> None:
fa82b95… lmata 254 def walk(node):
fa82b95… lmata 255 if node.type == "call_expression":
fa82b95… lmata 256 func = node.child_by_field_name("function")
fa82b95… lmata 257 if not func:
fa82b95… lmata 258 func = next(
e5e1a3b… lmata 259 (
e5e1a3b… lmata 260 c
e5e1a3b… lmata 261 for c in node.children
e5e1a3b… lmata 262 if c.type in ("identifier", "qualified_identifier", "field_expression")
e5e1a3b… lmata 263 ),
fa82b95… lmata 264 None,
fa82b95… lmata 265 )
fa82b95… lmata 266 if func:
fa82b95… lmata 267 callee = _node_text(func, source).split("::")[-1].split(".")[-1].split("->")[-1]
fa82b95… lmata 268 store.create_edge(
fa82b95… lmata 269 fn_label,
fa82b95… lmata 270 {"name": fn_name, "file_path": file_path},
fa82b95… lmata 271 EdgeType.CALLS,
fa82b95… lmata 272 NodeLabel.Function,
fa82b95… lmata 273 {"name": callee, "file_path": file_path},
fa82b95… lmata 274 )
fa82b95… lmata 275 stats["edges"] += 1
fa82b95… lmata 276 for child in node.children:
fa82b95… lmata 277 walk(child)
fa82b95… lmata 278
fa82b95… lmata 279 body = fn_node.child_by_field_name("body")
fa82b95… lmata 280 if not body:
fa82b95… lmata 281 body = next((c for c in fn_node.children if c.type == "compound_statement"), None)
fa82b95… lmata 282 if body:
fa82b95… lmata 283 walk(body)

Keyboard Shortcuts

Open search /
Next entry (timeline) j
Previous entry (timeline) k
Open focused entry Enter
Show this help ?
Toggle theme Top nav button