|
| 1 | +"""JavaScript analyzer using tree-sitter for code entity extraction.""" |
| 2 | + |
| 3 | +from pathlib import Path |
| 4 | +from typing import Optional |
| 5 | + |
| 6 | +from multilspy import SyncLanguageServer |
| 7 | +from ...entities.entity import Entity |
| 8 | +from ...entities.file import File |
| 9 | +from ..analyzer import AbstractAnalyzer |
| 10 | + |
| 11 | +import tree_sitter_javascript as tsjs |
| 12 | +from tree_sitter import Language, Node |
| 13 | + |
| 14 | +import logging |
| 15 | +logger = logging.getLogger('code_graph') |
| 16 | + |
| 17 | + |
| 18 | +class JavaScriptAnalyzer(AbstractAnalyzer): |
| 19 | + """Analyzer for JavaScript source files using tree-sitter. |
| 20 | +
|
| 21 | + Extracts functions, classes, and methods from JavaScript code. |
| 22 | + Resolves class inheritance (extends) and function/method call references. |
| 23 | + """ |
| 24 | + |
| 25 | + def __init__(self) -> None: |
| 26 | + """Initialize the JavaScript analyzer with the tree-sitter JS grammar.""" |
| 27 | + super().__init__(Language(tsjs.language())) |
| 28 | + |
| 29 | + def add_dependencies(self, path: Path, files: list[Path]) -> None: |
| 30 | + """Detect and register JavaScript project dependencies. |
| 31 | +
|
| 32 | + Currently a no-op; npm dependency resolution is not yet implemented. |
| 33 | + """ |
| 34 | + pass |
| 35 | + |
| 36 | + def get_entity_label(self, node: Node) -> str: |
| 37 | + """Return the graph label for a given AST node type. |
| 38 | +
|
| 39 | + Args: |
| 40 | + node: A tree-sitter AST node representing a JavaScript entity. |
| 41 | +
|
| 42 | + Returns: |
| 43 | + One of 'Function', 'Class', or 'Method'. |
| 44 | +
|
| 45 | + Raises: |
| 46 | + ValueError: If the node type is not a recognised entity. |
| 47 | + """ |
| 48 | + if node.type == 'function_declaration': |
| 49 | + return "Function" |
| 50 | + elif node.type == 'class_declaration': |
| 51 | + return "Class" |
| 52 | + elif node.type == 'method_definition': |
| 53 | + return "Method" |
| 54 | + raise ValueError(f"Unknown entity type: {node.type}") |
| 55 | + |
| 56 | + def get_entity_name(self, node: Node) -> str: |
| 57 | + """Extract the declared name from a JavaScript entity node. |
| 58 | +
|
| 59 | + Args: |
| 60 | + node: A tree-sitter AST node for a function, class, or method. |
| 61 | +
|
| 62 | + Returns: |
| 63 | + The entity name, or an empty string if no name node is found. |
| 64 | +
|
| 65 | + Raises: |
| 66 | + ValueError: If the node type is not a recognised entity. |
| 67 | + """ |
| 68 | + if node.type in ['function_declaration', 'class_declaration', 'method_definition']: |
| 69 | + name_node = node.child_by_field_name('name') |
| 70 | + if name_node is None: |
| 71 | + return '' |
| 72 | + return name_node.text.decode('utf-8') |
| 73 | + raise ValueError(f"Unknown entity type: {node.type}") |
| 74 | + |
| 75 | + def get_entity_docstring(self, node: Node) -> Optional[str]: |
| 76 | + """Extract a leading comment as a docstring for the entity. |
| 77 | +
|
| 78 | + Looks for a comment node immediately preceding the entity in the AST. |
| 79 | +
|
| 80 | + Args: |
| 81 | + node: A tree-sitter AST node for a function, class, or method. |
| 82 | +
|
| 83 | + Returns: |
| 84 | + The comment text, or None if no leading comment exists. |
| 85 | +
|
| 86 | + Raises: |
| 87 | + ValueError: If the node type is not a recognised entity. |
| 88 | + """ |
| 89 | + if node.type in ['function_declaration', 'class_declaration', 'method_definition']: |
| 90 | + if node.prev_sibling and node.prev_sibling.type == 'comment': |
| 91 | + return node.prev_sibling.text.decode('utf-8') |
| 92 | + return None |
| 93 | + raise ValueError(f"Unknown entity type: {node.type}") |
| 94 | + |
| 95 | + def get_entity_types(self) -> list[str]: |
| 96 | + """Return the tree-sitter node types recognised as JavaScript entities.""" |
| 97 | + return ['function_declaration', 'class_declaration', 'method_definition'] |
| 98 | + |
| 99 | + def add_symbols(self, entity: Entity) -> None: |
| 100 | + """Extract symbols (references) from a JavaScript entity. |
| 101 | +
|
| 102 | + For classes: extracts base-class identifiers from ``extends`` clauses. |
| 103 | + For functions/methods: extracts call-expression references. |
| 104 | +
|
| 105 | + Note: |
| 106 | + JavaScript parameters are untyped, so they are not captured as |
| 107 | + symbols — unlike typed languages (Java, Python) where parameter |
| 108 | + type annotations are meaningful for resolution. |
| 109 | + """ |
| 110 | + if entity.node.type == 'class_declaration': |
| 111 | + for child in entity.node.children: |
| 112 | + if child.type == 'class_heritage': |
| 113 | + for heritage_child in child.children: |
| 114 | + if heritage_child.type == 'identifier': |
| 115 | + entity.add_symbol("base_class", heritage_child) |
| 116 | + elif entity.node.type in ['function_declaration', 'method_definition']: |
| 117 | + captures = self._captures("(call_expression) @reference.call", entity.node) |
| 118 | + if 'reference.call' in captures: |
| 119 | + for caller in captures['reference.call']: |
| 120 | + entity.add_symbol("call", caller) |
| 121 | + |
| 122 | + def is_dependency(self, file_path: str) -> bool: |
| 123 | + """Check whether a file path belongs to an external dependency. |
| 124 | +
|
| 125 | + Uses path-segment matching so that directories merely containing |
| 126 | + 'node_modules' in their name (e.g. ``node_modules_utils``) are not |
| 127 | + treated as dependencies. |
| 128 | + """ |
| 129 | + return "node_modules" in Path(file_path).parts |
| 130 | + |
| 131 | + def resolve_path(self, file_path: str, path: Path) -> str: |
| 132 | + """Resolve an import path relative to the project root.""" |
| 133 | + return file_path |
| 134 | + |
| 135 | + def resolve_type(self, files: dict[Path, File], lsp: SyncLanguageServer, file_path: Path, path: Path, node: Node) -> list[Entity]: |
| 136 | + """Resolve a type reference to its class declaration entity.""" |
| 137 | + res = [] |
| 138 | + for file, resolved_node in self.resolve(files, lsp, file_path, path, node): |
| 139 | + type_dec = self.find_parent(resolved_node, ['class_declaration']) |
| 140 | + if type_dec in file.entities: |
| 141 | + res.append(file.entities[type_dec]) |
| 142 | + return res |
| 143 | + |
| 144 | + def resolve_method(self, files: dict[Path, File], lsp: SyncLanguageServer, file_path: Path, path: Path, node: Node) -> list[Entity]: |
| 145 | + """Resolve a call expression to the target function or method entity.""" |
| 146 | + res = [] |
| 147 | + if node.type == 'call_expression': |
| 148 | + func_node = node.child_by_field_name('function') |
| 149 | + if func_node and func_node.type == 'member_expression': |
| 150 | + func_node = func_node.child_by_field_name('property') |
| 151 | + if func_node: |
| 152 | + node = func_node |
| 153 | + for file, resolved_node in self.resolve(files, lsp, file_path, path, node): |
| 154 | + method_dec = self.find_parent(resolved_node, ['function_declaration', 'method_definition', 'class_declaration']) |
| 155 | + if method_dec and method_dec.type == 'class_declaration': |
| 156 | + continue |
| 157 | + if method_dec in file.entities: |
| 158 | + res.append(file.entities[method_dec]) |
| 159 | + return res |
| 160 | + |
| 161 | + def resolve_symbol(self, files: dict[Path, File], lsp: SyncLanguageServer, file_path: Path, path: Path, key: str, symbol: Node) -> list[Entity]: |
| 162 | + """Dispatch symbol resolution based on the symbol category. |
| 163 | +
|
| 164 | + Routes ``base_class`` symbols to type resolution and ``call`` symbols |
| 165 | + to method resolution. |
| 166 | + """ |
| 167 | + if key == "base_class": |
| 168 | + return self.resolve_type(files, lsp, file_path, path, symbol) |
| 169 | + elif key == "call": |
| 170 | + return self.resolve_method(files, lsp, file_path, path, symbol) |
| 171 | + else: |
| 172 | + raise ValueError(f"Unknown key {key}") |
0 commit comments