|
| 1 | +"""Base parser using Tree-sitter.""" |
| 2 | + |
| 3 | +from pathlib import Path |
| 4 | +from typing import Any, Optional |
| 5 | + |
| 6 | +from tree_sitter import Language, Parser, Tree |
| 7 | +import tree_sitter_languages |
| 8 | + |
| 9 | +from knowcode.models import ( |
| 10 | + Entity, |
| 11 | + EntityKind, |
| 12 | + Location, |
| 13 | + ParseResult, |
| 14 | + Relationship, |
| 15 | + RelationshipKind, |
| 16 | +) |
| 17 | + |
| 18 | + |
| 19 | +class TreeSitterParser: |
| 20 | + """Base class for parsers using Tree-sitter.""" |
| 21 | + |
| 22 | + def __init__(self, language_name: str) -> None: |
| 23 | + """Initialize parser for a specific language. |
| 24 | +
|
| 25 | + Args: |
| 26 | + language_name: Name of the language (e.g., 'python', 'javascript', 'java'). |
| 27 | + """ |
| 28 | + self.language_name = language_name |
| 29 | + self.language = tree_sitter_languages.get_language(language_name) |
| 30 | + self.parser = Parser() |
| 31 | + self.parser.set_language(self.language) |
| 32 | + |
| 33 | + def parse_file(self, file_path: str | Path) -> ParseResult: |
| 34 | + """Parse a source file. |
| 35 | +
|
| 36 | + Args: |
| 37 | + file_path: Path to the source file. |
| 38 | +
|
| 39 | + Returns: |
| 40 | + ParseResult with entities and relationships. |
| 41 | + """ |
| 42 | + file_path = Path(file_path) |
| 43 | + errors: list[str] = [] |
| 44 | + |
| 45 | + try: |
| 46 | + source_code = file_path.read_text(encoding="utf-8") |
| 47 | + except Exception as e: |
| 48 | + return ParseResult( |
| 49 | + file_path=str(file_path), |
| 50 | + entities=[], |
| 51 | + relationships=[], |
| 52 | + errors=[f"Failed to read file: {e}"], |
| 53 | + ) |
| 54 | + |
| 55 | + try: |
| 56 | + tree = self.parser.parse(bytes(source_code, "utf8")) |
| 57 | + except Exception as e: |
| 58 | + return ParseResult( |
| 59 | + file_path=str(file_path), |
| 60 | + entities=[], |
| 61 | + relationships=[], |
| 62 | + errors=[f"Parse error: {e}"], |
| 63 | + ) |
| 64 | + |
| 65 | + entities: list[Entity] = [] |
| 66 | + relationships: list[Relationship] = [] |
| 67 | + source_lines = source_code.splitlines() |
| 68 | + |
| 69 | + # Create module entity |
| 70 | + module_name = file_path.stem |
| 71 | + module_id = f"{file_path}::{module_name}" |
| 72 | + module_entity = Entity( |
| 73 | + id=module_id, |
| 74 | + kind=EntityKind.MODULE, |
| 75 | + name=module_name, |
| 76 | + qualified_name=module_name, |
| 77 | + location=Location( |
| 78 | + file_path=str(file_path), |
| 79 | + line_start=1, |
| 80 | + line_end=len(source_lines), |
| 81 | + ), |
| 82 | + ) |
| 83 | + entities.append(module_entity) |
| 84 | + |
| 85 | + # Delegate to language-specific extraction |
| 86 | + child_entities, child_rels = self._extract_entities( |
| 87 | + tree.root_node, file_path, module_id, source_code, source_lines |
| 88 | + ) |
| 89 | + entities.extend(child_entities) |
| 90 | + relationships.extend(child_rels) |
| 91 | + |
| 92 | + # Handle errors from tree-sitter |
| 93 | + if tree.root_node.has_error: |
| 94 | + # We might want to be more specific here, but for now just flag it |
| 95 | + # Don't fail completely, as partial AST is often useful |
| 96 | + errors.append("Tree-sitter reported syntax errors in file") |
| 97 | + |
| 98 | + return ParseResult( |
| 99 | + file_path=str(file_path), |
| 100 | + entities=entities, |
| 101 | + relationships=relationships, |
| 102 | + errors=errors, |
| 103 | + ) |
| 104 | + |
| 105 | + def _extract_entities( |
| 106 | + self, |
| 107 | + node: Any, |
| 108 | + file_path: Path, |
| 109 | + parent_id: str, |
| 110 | + source_code: str, |
| 111 | + source_lines: list[str], |
| 112 | + ) -> tuple[list[Entity], list[Relationship]]: |
| 113 | + """Extract entities from the AST. Must be implemented by subclasses.""" |
| 114 | + raise NotImplementedError |
| 115 | + |
| 116 | + def _get_text(self, node: Any, source_bytes: bytes) -> str: |
| 117 | + """Get text content of a node.""" |
| 118 | + return node.text.decode("utf8") |
| 119 | + |
| 120 | + def _get_location(self, node: Any, file_path: Path) -> Location: |
| 121 | + """Get location object for a node.""" |
| 122 | + return Location( |
| 123 | + file_path=str(file_path), |
| 124 | + line_start=node.start_point[0] + 1, |
| 125 | + line_end=node.end_point[0] + 1, |
| 126 | + column_start=node.start_point[1], |
| 127 | + column_end=node.end_point[1], |
| 128 | + ) |
| 129 | + |
| 130 | + def _create_entity( |
| 131 | + self, |
| 132 | + node: Any, |
| 133 | + kind: EntityKind, |
| 134 | + name: str, |
| 135 | + qualified_name: str, |
| 136 | + file_path: Path, |
| 137 | + source_lines: list[str], |
| 138 | + docstring: Optional[str] = None, |
| 139 | + signature: Optional[str] = None, |
| 140 | + ) -> Entity: |
| 141 | + """Helper to create an entity.""" |
| 142 | + # Extract source code for the node |
| 143 | + start_line = node.start_point[0] |
| 144 | + end_line = node.end_point[0] + 1 |
| 145 | + node_source = "\n".join(source_lines[start_line:end_line]) |
| 146 | + |
| 147 | + return Entity( |
| 148 | + id=f"{file_path}::{qualified_name}", |
| 149 | + kind=kind, |
| 150 | + name=name, |
| 151 | + qualified_name=qualified_name, |
| 152 | + location=self._get_location(node, file_path), |
| 153 | + docstring=docstring, |
| 154 | + signature=signature, |
| 155 | + source_code=node_source, |
| 156 | + ) |
0 commit comments