|
| 1 | +import subprocess |
| 2 | +from pathlib import Path |
| 3 | + |
| 4 | +from multilspy import SyncLanguageServer |
| 5 | +from ...entities.entity import Entity |
| 6 | +from ...entities.file import File |
| 7 | +from typing import Optional |
| 8 | +from ..analyzer import AbstractAnalyzer |
| 9 | + |
| 10 | +import tree_sitter_c_sharp as tscsharp |
| 11 | +from tree_sitter import Language, Node, QueryCursor |
| 12 | + |
| 13 | +import logging |
| 14 | +logger = logging.getLogger('code_graph') |
| 15 | + |
| 16 | +class CSharpAnalyzer(AbstractAnalyzer): |
| 17 | + def __init__(self) -> None: |
| 18 | + super().__init__(Language(tscsharp.language())) |
| 19 | + |
| 20 | + def _captures(self, pattern: str, node: Node) -> dict: |
| 21 | + """Run a tree-sitter query and return captures dict.""" |
| 22 | + query = self.language.query(pattern) |
| 23 | + cursor = QueryCursor(query) |
| 24 | + return cursor.captures(node) |
| 25 | + |
| 26 | + def add_dependencies(self, path: Path, files: list[Path]): |
| 27 | + if Path(f"{path}/temp_deps_cs").is_dir(): |
| 28 | + return |
| 29 | + if any(Path(f"{path}").glob("*.csproj")) or any(Path(f"{path}").glob("*.sln")): |
| 30 | + subprocess.run(["dotnet", "restore"], cwd=str(path)) |
| 31 | + |
| 32 | + def get_entity_label(self, node: Node) -> str: |
| 33 | + if node.type == 'class_declaration': |
| 34 | + return "Class" |
| 35 | + elif node.type == 'interface_declaration': |
| 36 | + return "Interface" |
| 37 | + elif node.type == 'enum_declaration': |
| 38 | + return "Enum" |
| 39 | + elif node.type == 'struct_declaration': |
| 40 | + return "Struct" |
| 41 | + elif node.type == 'method_declaration': |
| 42 | + return "Method" |
| 43 | + elif node.type == 'constructor_declaration': |
| 44 | + return "Constructor" |
| 45 | + raise ValueError(f"Unknown entity type: {node.type}") |
| 46 | + |
| 47 | + def get_entity_name(self, node: Node) -> str: |
| 48 | + if node.type in ['class_declaration', 'interface_declaration', 'enum_declaration', |
| 49 | + 'struct_declaration', 'method_declaration', 'constructor_declaration']: |
| 50 | + name_node = node.child_by_field_name('name') |
| 51 | + if name_node is None: |
| 52 | + return '' |
| 53 | + return name_node.text.decode('utf-8') |
| 54 | + raise ValueError(f"Unknown entity type: {node.type}") |
| 55 | + |
| 56 | + def get_entity_docstring(self, node: Node) -> Optional[str]: |
| 57 | + if node.type in ['class_declaration', 'interface_declaration', 'enum_declaration', |
| 58 | + 'struct_declaration', 'method_declaration', 'constructor_declaration']: |
| 59 | + # Walk back through contiguous comment siblings to collect |
| 60 | + # multi-line XML doc comments (each /// line is a separate node) |
| 61 | + lines = [] |
| 62 | + sibling = node.prev_sibling |
| 63 | + while sibling and sibling.type == "comment": |
| 64 | + lines.insert(0, sibling.text.decode('utf-8')) |
| 65 | + sibling = sibling.prev_sibling |
| 66 | + return '\n'.join(lines) if lines else None |
| 67 | + raise ValueError(f"Unknown entity type: {node.type}") |
| 68 | + |
| 69 | + def get_entity_types(self) -> list[str]: |
| 70 | + return ['class_declaration', 'interface_declaration', 'enum_declaration', |
| 71 | + 'struct_declaration', 'method_declaration', 'constructor_declaration'] |
| 72 | + |
| 73 | + def add_symbols(self, entity: Entity) -> None: |
| 74 | + if entity.node.type in ['class_declaration', 'struct_declaration']: |
| 75 | + base_list_captures = self._captures("(base_list (_) @base_type)", entity.node) |
| 76 | + if 'base_type' in base_list_captures: |
| 77 | + first = True |
| 78 | + for base_type in base_list_captures['base_type']: |
| 79 | + if first and entity.node.type == 'class_declaration': |
| 80 | + # NOTE: Without semantic analysis, we cannot distinguish a base |
| 81 | + # class from an interface in C# base_list. By convention, the |
| 82 | + # base class is listed first; if a class only implements |
| 83 | + # interfaces, this will produce a spurious base_class edge that |
| 84 | + # the LSP resolution in second_pass can correct. |
| 85 | + entity.add_symbol("base_class", base_type) |
| 86 | + first = False |
| 87 | + else: |
| 88 | + entity.add_symbol("implement_interface", base_type) |
| 89 | + elif entity.node.type == 'interface_declaration': |
| 90 | + base_list_captures = self._captures("(base_list (_) @base_type)", entity.node) |
| 91 | + if 'base_type' in base_list_captures: |
| 92 | + for base_type in base_list_captures['base_type']: |
| 93 | + entity.add_symbol("extend_interface", base_type) |
| 94 | + elif entity.node.type in ['method_declaration', 'constructor_declaration']: |
| 95 | + captures = self._captures("(invocation_expression) @reference.call", entity.node) |
| 96 | + if 'reference.call' in captures: |
| 97 | + for caller in captures['reference.call']: |
| 98 | + entity.add_symbol("call", caller) |
| 99 | + captures = self._captures("(parameter_list (parameter type: (_) @parameter))", entity.node) |
| 100 | + if 'parameter' in captures: |
| 101 | + for parameter in captures['parameter']: |
| 102 | + entity.add_symbol("parameters", parameter) |
| 103 | + if entity.node.type == 'method_declaration': |
| 104 | + return_type = entity.node.child_by_field_name('type') |
| 105 | + if return_type: |
| 106 | + entity.add_symbol("return_type", return_type) |
| 107 | + |
| 108 | + def is_dependency(self, file_path: str) -> bool: |
| 109 | + return "temp_deps_cs" in file_path |
| 110 | + |
| 111 | + def resolve_path(self, file_path: str, path: Path) -> str: |
| 112 | + return file_path |
| 113 | + |
| 114 | + def resolve_type(self, files: dict[Path, File], lsp: SyncLanguageServer, file_path: Path, path: Path, node: Node) -> list[Entity]: |
| 115 | + res = [] |
| 116 | + for file, resolved_node in self.resolve(files, lsp, file_path, path, node): |
| 117 | + type_dec = self.find_parent(resolved_node, ['class_declaration', 'interface_declaration', 'enum_declaration', 'struct_declaration']) |
| 118 | + if type_dec in file.entities: |
| 119 | + res.append(file.entities[type_dec]) |
| 120 | + return res |
| 121 | + |
| 122 | + def resolve_method(self, files: dict[Path, File], lsp: SyncLanguageServer, file_path: Path, path: Path, node: Node) -> list[Entity]: |
| 123 | + res = [] |
| 124 | + if node.type == 'invocation_expression': |
| 125 | + func_node = node.child_by_field_name('function') |
| 126 | + if func_node and func_node.type == 'member_access_expression': |
| 127 | + func_node = func_node.child_by_field_name('name') |
| 128 | + if func_node: |
| 129 | + node = func_node |
| 130 | + for file, resolved_node in self.resolve(files, lsp, file_path, path, node): |
| 131 | + method_dec = self.find_parent(resolved_node, ['method_declaration', 'constructor_declaration', 'class_declaration', 'interface_declaration', 'enum_declaration', 'struct_declaration']) |
| 132 | + if method_dec and method_dec.type in ['class_declaration', 'interface_declaration', 'enum_declaration', 'struct_declaration']: |
| 133 | + continue |
| 134 | + if method_dec in file.entities: |
| 135 | + res.append(file.entities[method_dec]) |
| 136 | + return res |
| 137 | + |
| 138 | + def resolve_symbol(self, files: dict[Path, File], lsp: SyncLanguageServer, file_path: Path, path: Path, key: str, symbol: Node) -> list[Entity]: |
| 139 | + if key in ["implement_interface", "base_class", "extend_interface", "parameters", "return_type"]: |
| 140 | + return self.resolve_type(files, lsp, file_path, path, symbol) |
| 141 | + elif key in ["call"]: |
| 142 | + return self.resolve_method(files, lsp, file_path, path, symbol) |
| 143 | + else: |
| 144 | + raise ValueError(f"Unknown key {key}") |
0 commit comments