|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +""" |
| 4 | +Symbol Search & Fallback Provider für CodeBox. |
| 5 | +
|
| 6 | +Bietet schnelle, heuristische Symbol- und Referenzsuche, falls kein LSP-Server |
| 7 | +installiert oder aktiv ist oder der Language Server für eine Datei keine Ergebnisse liefert. |
| 8 | +""" |
| 9 | + |
| 10 | +from __future__ import annotations |
| 11 | + |
| 12 | +import re |
| 13 | +from pathlib import Path |
| 14 | +from typing import List, Optional |
| 15 | + |
| 16 | + |
| 17 | +IGNORED_DIRS = { |
| 18 | + ".git", |
| 19 | + "__pycache__", |
| 20 | + ".pytest_cache", |
| 21 | + ".mypy_cache", |
| 22 | + ".ruff_cache", |
| 23 | + "node_modules", |
| 24 | + ".venv", |
| 25 | + "venv", |
| 26 | + "env", |
| 27 | + "build", |
| 28 | + "dist", |
| 29 | + ".idea", |
| 30 | + ".vscode", |
| 31 | +} |
| 32 | + |
| 33 | +MAX_FILE_SIZE_BYTES = 1024 * 1024 * 2 # 2 MB Begrenzung pro Textdatei |
| 34 | + |
| 35 | + |
| 36 | +def get_definition_patterns(symbol: str) -> List[re.Pattern]: |
| 37 | + """Erstellt reguläre Ausdrücke zur Erkennung typischer Definitionen für das Symbol.""" |
| 38 | + escaped = re.escape(symbol) |
| 39 | + patterns = [ |
| 40 | + # Python: def func / async def func / class Class / Var = |
| 41 | + rf"^\s*(?:async\s+)?def\s+{escaped}\b", |
| 42 | + rf"^\s*class\s+{escaped}\b", |
| 43 | + rf"^\s*{escaped}\s*=", |
| 44 | + # JS / TS: function func / class Class / const/let/var x = / type / interface |
| 45 | + rf"^\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s+{escaped}\b", |
| 46 | + rf"^\s*(?:export\s+)?class\s+{escaped}\b", |
| 47 | + rf"^\s*(?:export\s+)?(?:const|let|var)\s+{escaped}\s*=", |
| 48 | + rf"^\s*(?:export\s+)?(?:interface|type)\s+{escaped}\b", |
| 49 | + # Rust / Go / C / C++ |
| 50 | + rf"^\s*(?:pub(?:\([^)]*\))?\s+)?fn\s+{escaped}\b", |
| 51 | + rf"^\s*func\s+(?:\([^)]+\)\s+)?{escaped}\b", |
| 52 | + rf"^\s*(?:pub\s+)?(?:struct|enum|trait)\s+{escaped}\b", |
| 53 | + ] |
| 54 | + return [re.compile(p, re.MULTILINE) for p in patterns] |
| 55 | + |
| 56 | + |
| 57 | +def _scan_text_for_definitions( |
| 58 | + text: str, |
| 59 | + patterns: List[re.Pattern], |
| 60 | + symbol: str, |
| 61 | + path: Optional[Path], |
| 62 | +) -> List[dict]: |
| 63 | + results: List[dict] = [] |
| 64 | + lines = text.splitlines() |
| 65 | + for line_idx, line in enumerate(lines): |
| 66 | + for pat in patterns: |
| 67 | + m = pat.search(line) |
| 68 | + if m: |
| 69 | + # Spalte des Symbols ermitteln |
| 70 | + col_idx = line.find(symbol) |
| 71 | + if col_idx < 0: |
| 72 | + col_idx = m.start() |
| 73 | + results.append({ |
| 74 | + "path": path, |
| 75 | + "line": line_idx + 1, |
| 76 | + "col": col_idx + 1, |
| 77 | + "length": len(symbol), |
| 78 | + "preview": line.strip(), |
| 79 | + "source": "Definition (Fallback)", |
| 80 | + }) |
| 81 | + break |
| 82 | + return results |
| 83 | + |
| 84 | + |
| 85 | +def find_definition_fallback( |
| 86 | + symbol: str, |
| 87 | + current_path: Optional[Path] = None, |
| 88 | + current_text: Optional[str] = None, |
| 89 | + workspace_folders: Optional[List[Path]] = None, |
| 90 | +) -> List[dict]: |
| 91 | + """Sucht nach Definitionen eines Symbols im aktuellen Dokument und Workspace.""" |
| 92 | + if not symbol or not symbol.strip(): |
| 93 | + return [] |
| 94 | + symbol = symbol.strip() |
| 95 | + patterns = get_definition_patterns(symbol) |
| 96 | + results: List[dict] = [] |
| 97 | + |
| 98 | + # 1. Zuerst das aktuelle Dokument durchsuchen |
| 99 | + if current_text: |
| 100 | + doc_matches = _scan_text_for_definitions(current_text, patterns, symbol, current_path) |
| 101 | + results.extend(doc_matches) |
| 102 | + if results: |
| 103 | + return results |
| 104 | + |
| 105 | + # 2. Falls im aktiven Dokument nichts gefunden wurde: Workspace durchsuchen |
| 106 | + if workspace_folders: |
| 107 | + current_resolved = current_path.resolve() if current_path and current_path.exists() else None |
| 108 | + for folder in workspace_folders: |
| 109 | + folder_path = Path(folder).resolve() |
| 110 | + if not folder_path.is_dir(): |
| 111 | + continue |
| 112 | + for root, dirs, files in folder_path.walk(): |
| 113 | + dirs[:] = [d for d in dirs if d not in IGNORED_DIRS and not d.startswith(".")] |
| 114 | + for fname in files: |
| 115 | + if fname.startswith("."): |
| 116 | + continue |
| 117 | + file_path = root / fname |
| 118 | + if current_resolved and file_path == current_resolved: |
| 119 | + continue |
| 120 | + try: |
| 121 | + if file_path.stat().st_size > MAX_FILE_SIZE_BYTES: |
| 122 | + continue |
| 123 | + content = file_path.read_text(encoding="utf-8", errors="replace") |
| 124 | + except (OSError, UnicodeError): |
| 125 | + continue |
| 126 | + |
| 127 | + matches = _scan_text_for_definitions(content, patterns, symbol, file_path) |
| 128 | + if matches: |
| 129 | + results.extend(matches) |
| 130 | + # Sobald wir eine konkrete Definition finden, zurückgeben |
| 131 | + if len(results) >= 10: |
| 132 | + return results |
| 133 | + |
| 134 | + return results |
| 135 | + |
| 136 | + |
| 137 | +def find_references_fallback( |
| 138 | + symbol: str, |
| 139 | + current_path: Optional[Path] = None, |
| 140 | + current_text: Optional[str] = None, |
| 141 | + workspace_folders: Optional[List[Path]] = None, |
| 142 | + max_results: int = 250, |
| 143 | +) -> List[dict]: |
| 144 | + """Sucht nach allen Vorkommen (Ganzwort) des Symbols im aktuellen Dokument und Workspace.""" |
| 145 | + if not symbol or not symbol.strip(): |
| 146 | + return [] |
| 147 | + symbol = symbol.strip() |
| 148 | + pattern = re.compile(rf"\b{re.escape(symbol)}\b") |
| 149 | + results: List[dict] = [] |
| 150 | + |
| 151 | + # 1. Aktives Dokument |
| 152 | + if current_text: |
| 153 | + for line_idx, line in enumerate(current_text.splitlines()): |
| 154 | + for match in pattern.finditer(line): |
| 155 | + results.append({ |
| 156 | + "path": current_path, |
| 157 | + "line": line_idx + 1, |
| 158 | + "col": match.start() + 1, |
| 159 | + "length": len(symbol), |
| 160 | + "preview": line.strip(), |
| 161 | + "source": "Referenz (Text)", |
| 162 | + }) |
| 163 | + if len(results) >= max_results: |
| 164 | + return results |
| 165 | + |
| 166 | + # 2. Workspace |
| 167 | + if workspace_folders: |
| 168 | + current_resolved = current_path.resolve() if current_path and current_path.exists() else None |
| 169 | + for folder in workspace_folders: |
| 170 | + folder_path = Path(folder).resolve() |
| 171 | + if not folder_path.is_dir(): |
| 172 | + continue |
| 173 | + for root, dirs, files in folder_path.walk(): |
| 174 | + dirs[:] = [d for d in dirs if d not in IGNORED_DIRS and not d.startswith(".")] |
| 175 | + for fname in files: |
| 176 | + if fname.startswith("."): |
| 177 | + continue |
| 178 | + file_path = root / fname |
| 179 | + if current_resolved and file_path == current_resolved: |
| 180 | + continue |
| 181 | + try: |
| 182 | + if file_path.stat().st_size > MAX_FILE_SIZE_BYTES: |
| 183 | + continue |
| 184 | + content = file_path.read_text(encoding="utf-8", errors="replace") |
| 185 | + except (OSError, UnicodeError): |
| 186 | + continue |
| 187 | + |
| 188 | + for line_idx, line in enumerate(content.splitlines()): |
| 189 | + for match in pattern.finditer(line): |
| 190 | + results.append({ |
| 191 | + "path": file_path, |
| 192 | + "line": line_idx + 1, |
| 193 | + "col": match.start() + 1, |
| 194 | + "length": len(symbol), |
| 195 | + "preview": line.strip(), |
| 196 | + "source": "Referenz (Text)", |
| 197 | + }) |
| 198 | + if len(results) >= max_results: |
| 199 | + return results |
| 200 | + |
| 201 | + return results |
0 commit comments