"""LSP 服务:本地语言服务器进程池(pyright/clangd 常驻、jdt.ls 按需),JSON-RPC over stdio。 对外接口(请求-响应模式,适配"代码片段提交"教学场景): - diagnostics(lang, code) -> 报错/警告列表(LSP publishDiagnostics) - complete(lang, code, line, char) -> 补全项 - hover(lang, code, line, char) -> 悬停提示 """ from __future__ import annotations import json import logging import queue import re import subprocess import threading import time import uuid logger = logging.getLogger("fluent.services.lsp") LANG_IDS = {"python": "python", "java": "java", "cpp": "cpp", "c": "c"} EXT = {"python": ".py", "java": ".java", "cpp": ".cpp", "c": ".c"} # 语言服务器命令(可按部署环境覆盖) LSP_COMMANDS: dict[str, list[str]] = { "python": ["pyright-langserver", "--stdio"], "cpp": ["clangd", "--background-index=false"], # jdt.ls 按需:需 eclipse.jdt.ls 包(约 200MB,Java 17+);未装时返回提示 "java": ["java", "-jar", "/opt/jdtls/plugins/org.eclipse.equinox.launcher_*.jar"], } class LspError(Exception): pass class LspProcess: """单个语言服务器进程:JSON-RPC 帧封装 + 请求/响应 + 诊断收集。""" def __init__(self, lang: str, cmd: list[str], uri_prefix: str = "file:///tmp/fl"): self.lang = lang self.cmd = cmd self.uri_prefix = uri_prefix self.proc: subprocess.Popen | None = None self._lock = threading.Lock() self._pending: dict[int, queue.Queue] = {} self._diags: dict[str, list[dict]] = {} self._diag_event: dict[str, threading.Event] = {} self._msg_id = 0 self._ready = threading.Event() self._closed = False self._warmed = False def start(self) -> None: try: self.proc = subprocess.Popen( self.cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, ) except FileNotFoundError: raise LspError(f"{self.lang} 语言服务器未安装({self.cmd[0]} 不存在)") threading.Thread(target=self._read_loop, daemon=True, name=f"lsp-{self.lang}").start() self._initialize() # ---------- 帧读写 ---------- def _send(self, payload: dict) -> None: body = json.dumps(payload, ensure_ascii=False).encode("utf-8") frame = b"Content-Length: " + str(len(body)).encode() + b"\r\n\r\n" + body with self._lock: if not self.proc or self.proc.stdin is None: raise LspError("LSP 进程未启动") self.proc.stdin.write(frame) self.proc.stdin.flush() def _read_exact(self, n: int) -> bytes: """管道 read(n) 不保证读满 n 字节(帧错位根因),循环读满。""" buf = b"" while len(buf) < n and self.proc and self.proc.stdout: chunk = self.proc.stdout.read(n - len(buf)) if not chunk: break buf += chunk return buf def _read_loop(self) -> None: try: while not self._closed and self.proc and self.proc.stdout: line = self.proc.stdout.readline() if not line: break if not line.startswith(b"Content-Length:"): continue n = int(line.split(b":")[1]) self.proc.stdout.readline() # 空行 raw = self._read_exact(n) if len(raw) < n: break try: msg = json.loads(raw) except json.JSONDecodeError: continue self._dispatch(msg) except Exception as e: # noqa: BLE001 logger.warning("LSP %s 读线程退出: %s", self.lang, e) def _dispatch(self, msg: dict) -> None: logger.debug("LSP %s 收到帧: method=%s id=%s", self.lang, msg.get("method"), msg.get("id")) if "id" in msg and "method" not in msg: q = self._pending.pop(msg.get("id"), None) if q: q.put(msg) elif msg.get("method") == "publishDiagnostics": uri = msg["params"].get("uri", "") logger.debug("LSP %s publishDiagnostics uri=%s (期望在 _diags=%s)", self.lang, uri, bool(self._diag_event.get(uri))) self._diags[uri] = msg["params"].get("diagnostics", []) ev = self._diag_event.get(uri) if ev: ev.set() elif msg.get("method") == "window/logMessage": logger.debug("LSP %s: %s", self.lang, msg["params"].get("message", "")) # 其他 notification 忽略 # ---------- RPC ---------- def request(self, method: str, params: dict, timeout: float = 15.0) -> dict: self._msg_id += 1 mid = self._msg_id q: queue.Queue = queue.Queue() self._pending[mid] = q self._send({"jsonrpc": "2.0", "id": mid, "method": method, "params": params}) try: resp = q.get(timeout=timeout) except queue.Empty: self._pending.pop(mid, None) raise LspError(f"{self.lang} LSP 请求超时({method})") if "error" in resp: raise LspError(f"{self.lang} LSP 错误: {resp['error'].get('message', resp['error'])}") return resp.get("result", {}) def notify(self, method: str, params: dict) -> None: self._send({"jsonrpc": "2.0", "method": method, "params": params}) # ---------- 生命周期 ---------- def _initialize(self) -> None: self.request("initialize", { "processId": None, "rootUri": None, "capabilities": { "textDocument": {"completion": {"completionItem": {"snippetSupport": True}}, "hover": {"contentFormat": ["markdown", "plaintext"]}}, }, "workspaceFolders": None, }, timeout=30) self.notify("initialized", {}) self._ready.set() def close(self) -> None: self._closed = True try: self.proc and self.proc.terminate() except Exception: # noqa: BLE001 pass # ---------- 文档操作 ---------- def _uri(self) -> str: return f"{self.uri_prefix}/{self.lang}/{uuid.uuid4().hex}{EXT[self.lang]}" def open_doc(self, uri: str, code: str) -> None: self.notify("textDocument/didOpen", { "textDocument": {"uri": uri, "languageId": LANG_IDS[self.lang], "version": 1, "text": code}, }) def diagnostics(self, code: str, timeout: float = 15.0) -> list[dict]: """主动拉取诊断(LSP 3.17 textDocument/diagnostic;不依赖异步 publishDiagnostics)。 首帧前留初始化间隔,拉取为空时小间隔重试(服务器异步分析)。 """ if not self._warmed: time.sleep(2) self._warmed = True uri = self._uri() self.open_doc(uri, code) t0 = time.time() while time.time() - t0 < timeout: try: result = self.request("textDocument/diagnostic", {"textDocument": {"uri": uri}}, timeout=min(10, timeout)) except LspError as e: # 服务器不支持拉取诊断 → 回退等 publishDiagnostics logger.warning("LSP %s 拉取诊断失败,回退异步推送: %s", self.lang, e) ev = threading.Event() self._diag_event[uri] = ev if ev.wait(timeout): self._diag_event.pop(uri, None) return self._diags.pop(uri, []) self._diag_event.pop(uri, None) raise items = result.get("items", []) if items: return items time.sleep(1.0) raise LspError(f"{self.lang} 诊断超时(服务器无响应)") def completion(self, code: str, line: int, character: int) -> list[dict]: uri = self._uri() self.open_doc(uri, code) result = self.request("textDocument/completion", { "textDocument": {"uri": uri}, "position": {"line": line, "character": character}, "context": {"triggerKind": 1}, }) items = result.get("items", []) if isinstance(result, dict) else result or [] return [{ "label": it.get("label", ""), "kind": it.get("kind"), "detail": it.get("detail", ""), "insertText": it.get("insertText") or it.get("label", ""), "sortText": it.get("sortText"), } for it in items] def hover(self, code: str, line: int, character: int) -> str: uri = self._uri() self.open_doc(uri, code) result = self.request("textDocument/hover", { "textDocument": {"uri": uri}, "position": {"line": line, "character": character}, }) contents = result.get("contents") if isinstance(result, dict) else None if isinstance(contents, str): return contents if isinstance(contents, dict): return contents.get("value", "") if isinstance(contents, list): parts = [] for c in contents: if isinstance(c, str): parts.append(c) elif isinstance(c, dict): parts.append(c.get("value", "")) return "\n".join(parts) return "" class LspManager: """语言实例注册表:pyright/clangd 常驻,jdt.ls 按需。""" def __init__(self): self._procs: dict[str, LspProcess] = {} self._lock = threading.Lock() def get(self, lang: str) -> LspProcess: if lang not in LANG_IDS: raise LspError(f"暂不支持的 LSP 语言: {lang}(支持 python/java/cpp)") with self._lock: proc = self._procs.get(lang) if proc is None or proc.proc is None or proc.proc.poll() is not None: cmd = LSP_COMMANDS[lang] if lang == "java" and not __import__("glob").glob("/opt/jdtls/**/org.eclipse.equinox.launcher_*.jar", recursive=True): raise LspError("Java LSP(jdt.ls)未安装:需部署 eclipse.jdt.ls 到 /opt/jdtls(约 200MB),安装后自动启用") proc = LspProcess(lang, cmd) proc.start() self._procs[lang] = proc logger.info("LSP %s 已启动: %s", lang, cmd[0]) return proc def status(self) -> dict: out = {} for lang, cmd in LSP_COMMANDS.items(): proc = self._procs.get(lang) alive = bool(proc and proc.proc and proc.proc.poll() is None) out[lang] = {"configured": True, "running": alive} return out def shutdown(self) -> None: for proc in self._procs.values(): proc.close() manager = LspManager()