Loading...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 | # SPDX-License-Identifier: GPL-2.0 # # Copyright 2025 Canonical Ltd # """Minimal LSP (Language Server Protocol) client for clangd. This module provides a simple JSON-RPC 2.0 client for communicating with LSP servers like clangd. It focuses on the specific functionality needed for analyzing inactive preprocessor regions. """ import json import subprocess import threading from typing import Any, Dict, Optional class LspClient: """Minimal LSP client for JSON-RPC 2.0 communication. This client handles the basic LSP protocol communication over stdin/stdout with a language server process. Attributes: process: The language server subprocess next_id: Counter for JSON-RPC request IDs responses: Dict mapping request IDs to response data lock: Thread lock for response dictionary reader_thread: Background thread reading server responses """ def __init__(self, server_command): """Init the LSP client and start the server. Args: server_command (list): Command to start the LSP server (e.g., ['clangd', '--log=error']) """ self.process = subprocess.Popen( server_command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=0 ) self.next_id = 1 self.responses = {} self.notifications = [] self.lock = threading.Lock() self.running = True # Start background thread to read responses self.reader_thread = threading.Thread(target=self._read_responses) self.reader_thread.daemon = True self.reader_thread.start() def _read_responses(self): """Background thread to read responses from the server""" while self.running and self.process.poll() is None: try: # Read headers headers = {} while True: line = self.process.stdout.readline() if not line or line == '\r\n' or line == '\n': break if ':' in line: key, value = line.split(':', 1) headers[key.strip()] = value.strip() if 'Content-Length' not in headers: continue # Read content content_length = int(headers['Content-Length']) content = self.process.stdout.read(content_length) if not content: break # Parse JSON message = json.loads(content) # Store response or notification with self.lock: if 'id' in message: # Response to a request self.responses[message['id']] = message else: # Notification from server self.notifications.append(message) except (json.JSONDecodeError, ValueError): continue except Exception: break def _send_message(self, message: Dict[str, Any]): """Send a JSON-RPC message to the server. Args: message: JSON-RPC message dictionary """ content = json.dumps(message) headers = f'Content-Length: {len(content)}\r\n\r\n' self.process.stdin.write(headers + content) self.process.stdin.flush() def request(self, method: str, params: Optional[Dict] = None, timeout: int = 30) -> Optional[Dict]: """Send a JSON-RPC request and wait for response. Args: method: LSP method name (e.g., 'initialize') params: Method parameters dictionary timeout: Timeout in seconds (default: 30) Returns: Response dictionary, or None on timeout/error """ request_id = self.next_id self.next_id += 1 message = { 'jsonrpc': '2.0', 'id': request_id, 'method': method, } if params: message['params'] = params self._send_message(message) # Wait for response import time start_time = time.time() while time.time() - start_time < timeout: with self.lock: if request_id in self.responses: response = self.responses.pop(request_id) if 'result' in response: return response['result'] if 'error' in response: raise RuntimeError( f"LSP error: {response['error']}") return response time.sleep(0.01) return None def notify(self, method: str, params: Optional[Dict] = None): """Send a JSON-RPC notification (no response expected). Args: method: LSP method name params: Method parameters dictionary """ message = { 'jsonrpc': '2.0', 'method': method, } if params: message['params'] = params self._send_message(message) def init(self, root_uri: str, capabilities: Optional[Dict] = None) -> Dict: """Send initialize request to the server. Args: root_uri: Workspace root URI (e.g., 'file:///path/to/workspace') capabilities: Client capabilities dict Returns: Server capabilities from initialize response """ if capabilities is None: capabilities = { 'textDocument': { 'semanticTokens': { 'requests': { 'full': True } }, 'publishDiagnostics': {}, 'inactiveRegions': { 'refreshSupport': False } } } result = self.request('initialize', { 'processId': None, 'rootUri': root_uri, 'capabilities': capabilities }) # Send initialized notification self.notify('initialized', {}) return result def shutdown(self): """Shutdown the language server""" self.request('shutdown') self.notify('exit') self.running = False if self.process: self.process.wait(timeout=5) # Close file descriptors to avoid ResourceWarnings if self.process.stdin: self.process.stdin.close() if self.process.stdout: self.process.stdout.close() if self.process.stderr: self.process.stderr.close() def __enter__(self): """Context manager entry""" return self def __exit__(self, exc_type, exc_val, exc_tb): """Context manager exit - ensure cleanup""" self.shutdown() |