Skip to main content

iced_code_editor/canvas_editor/lsp/process/
mod.rs

1//! LSP (Language Server Protocol) Process Client implementation.
2//!
3//! This module provides a client for communicating with LSP servers via stdio.
4//! It handles document synchronization, hover requests, and completion requests.
5//!
6//! Enable with the `lsp-process` Cargo feature. Not available on WASM targets.
7
8pub mod config;
9pub mod overlay;
10
11/// JSON-RPC method name for server-push progress notifications.
12const METHOD_PROGRESS: &str = "$/progress";
13/// JSON-RPC method name sent by the server when it creates a work-done token.
14const METHOD_WORK_DONE_PROGRESS_CREATE: &str = "window/workDoneProgress/create";
15/// Progress `kind` value that signals the end of a work-done sequence.
16const PROGRESS_KIND_END: &str = "end";
17/// Maximum accepted `Content-Length` for a single LSP frame (64 MiB).
18///
19/// The body length is attacker-controlled input: it comes from the language
20/// server process, whose binary is resolved through `PATH` or an environment
21/// variable. Without a cap, a malformed or hostile server announcing a
22/// multi-gigabyte frame would force an unbounded allocation and take the
23/// editor down. Real LSP payloads stay orders of magnitude below this.
24const MAX_MESSAGE_BYTES: usize = 64 * 1024 * 1024;
25
26use self::config::{
27    LspCommand, ensure_rust_analyzer_config, lsp_server_config,
28    resolve_lsp_command,
29};
30use crate::buffer::text_utils::char_to_byte_index;
31use crate::canvas_editor::lsp::{
32    LspClient, LspDocument, LspPosition, LspRange, LspTextChange,
33};
34use serde_json::json;
35use std::collections::HashMap;
36use std::io::{BufRead, BufReader, Write};
37use std::process::{Child, Command, Stdio};
38use std::sync::atomic::{AtomicU64, Ordering};
39use std::sync::{Arc, Mutex, mpsc};
40use std::thread;
41
42// =============================================================================
43// Text Model - Internal document representation for tracking text changes
44// =============================================================================
45
46/// Internal representation of a text document as a vector of lines.
47///
48/// Used to track document state and convert between character and byte indices.
49struct TextModel {
50    /// The document content stored as a vector of lines (without newline characters)
51    lines: Vec<String>,
52}
53
54impl TextModel {
55    /// Creates a new `TextModel` from a string.
56    ///
57    /// Splits the text into lines for easier manipulation.
58    /// An empty string creates a single empty line.
59    fn from_text(text: &str) -> Self {
60        let lines = if text.is_empty() {
61            vec![String::new()]
62        } else {
63            text.lines().map(String::from).collect()
64        };
65        Self { lines }
66    }
67
68    /// Applies a text change (edit) to the document.
69    ///
70    /// Handles multi-line insertions and deletions by splicing the lines vector.
71    fn apply_change(&mut self, change: &LspTextChange) {
72        let start_line = change.range.start.line as usize;
73        let end_line = change.range.end.line as usize;
74
75        if start_line >= self.lines.len() || end_line >= self.lines.len() {
76            return;
77        }
78
79        let start_col = change.range.start.character as usize;
80        let end_col = change.range.end.character as usize;
81
82        let start_byte = char_to_byte_index(&self.lines[start_line], start_col);
83        let end_byte = char_to_byte_index(&self.lines[end_line], end_col);
84
85        let prefix = self.lines[start_line][..start_byte].to_string();
86        let suffix = self.lines[end_line][end_byte..].to_string();
87
88        let inserted: Vec<&str> = change.text.split('\n').collect();
89        let mut replacement: Vec<String> = Vec::new();
90
91        if inserted.len() == 1 {
92            replacement.push(format!("{}{}{}", prefix, inserted[0], suffix));
93        } else {
94            replacement.push(format!("{}{}", prefix, inserted[0]));
95            for mid in inserted.iter().take(inserted.len() - 1).skip(1) {
96                replacement.push((*mid).to_string());
97            }
98            replacement.push(format!(
99                "{}{}",
100                inserted[inserted.len() - 1],
101                suffix
102            ));
103        }
104
105        self.lines.splice(start_line..=end_line, replacement);
106    }
107
108    /// Converts a UTF-8 character position to a UTF-16 position.
109    ///
110    /// This is necessary because LSP uses UTF-16 for character positions.
111    fn to_utf16_position(&self, position: LspPosition) -> LspPosition {
112        let line_index = position.line as usize;
113        let char_index = position.character as usize;
114        let line = self.lines.get(line_index).map_or("", |l| l.as_str());
115
116        let utf16_col =
117            line.chars().take(char_index).map(|c| c.len_utf16() as u32).sum();
118        LspPosition { line: position.line, character: utf16_col }
119    }
120}
121
122// =============================================================================
123// Document State - Tracks the state of an open document
124// =============================================================================
125
126/// Represents the state of a single open document.
127struct DocumentState {
128    /// The text content of the document
129    text: TextModel,
130}
131
132// =============================================================================
133// LSP Request Types
134// =============================================================================
135
136/// Enumeration of LSP request types that we track for response handling.
137enum LspRequestKind {
138    /// Hover request — shows type information and documentation
139    Hover,
140    /// Completion request — provides auto-complete suggestions
141    Completion,
142    /// Definition request — go to definition
143    Definition,
144}
145
146// =============================================================================
147// LSP Events - Events sent back to the main application
148// =============================================================================
149
150/// Events that can be sent from the LSP client to the application.
151///
152/// Receive these by polling the `mpsc::Receiver` you pass to
153/// [`LspProcessClient::new_with_server`].
154pub enum LspEvent {
155    /// Hover information received from the LSP server.
156    Hover {
157        /// Markdown or plain-text hover content.
158        text: String,
159    },
160    /// Completion items received from the LSP server.
161    Completion {
162        /// List of completion label strings.
163        items: Vec<String>,
164    },
165    /// Definition location received from the LSP server.
166    Definition {
167        /// Target document URI.
168        uri: String,
169        /// Target range within that document.
170        range: crate::canvas_editor::lsp::LspRange,
171    },
172    /// Progress notification from the LSP server.
173    Progress {
174        /// Progress token identifier.
175        token: String,
176        /// Key of the server that sent this notification.
177        server_key: String,
178        /// Human-readable title for the progress operation.
179        title: String,
180        /// Optional status message.
181        message: Option<String>,
182        /// Optional percentage complete (0–100).
183        percentage: Option<u32>,
184        /// `true` when this is the final progress notification.
185        done: bool,
186    },
187    /// Log message from the LSP server's stderr.
188    Log {
189        /// Key of the server that sent this message.
190        server_key: String,
191        /// The log line.
192        message: String,
193    },
194}
195
196// =============================================================================
197// LSP Process Client - Main client implementation
198// =============================================================================
199
200/// Client for communicating with an LSP server process.
201///
202/// Manages the lifecycle of the server process and handles all communication.
203/// Implements [`LspClient`] so it can be plugged directly into a [`CodeEditor`].
204///
205/// # Examples
206///
207/// ```no_run
208/// use std::sync::mpsc;
209/// use iced_code_editor::{LspProcessClient, LspEvent};
210///
211/// let (tx, rx) = mpsc::channel::<LspEvent>();
212/// let client = LspProcessClient::new_with_server(
213///     "file:///home/user/project",
214///     tx,
215///     "lua-language-server",
216/// );
217/// ```
218///
219/// [`CodeEditor`]: crate::CodeEditor
220pub struct LspProcessClient {
221    /// The child process running the LSP server
222    child: Child,
223    /// Channel for sending messages to the writer thread
224    writer: mpsc::Sender<Vec<u8>>,
225    /// Map of URI to document state for all open documents
226    documents: Arc<Mutex<HashMap<String, DocumentState>>>,
227    /// Counter for generating unique request IDs
228    request_id: AtomicU64,
229    /// Map of pending request IDs to their types (for response routing)
230    pending_requests: Arc<Mutex<HashMap<u64, LspRequestKind>>>,
231    /// Handle to the writer thread (kept alive for the client's lifetime)
232    _writer_thread: thread::JoinHandle<()>,
233    /// Handle to the reader thread (kept alive for the client's lifetime)
234    _reader_thread: thread::JoinHandle<()>,
235    /// Handle to the stderr thread (kept alive for the client's lifetime)
236    _stderr_thread: thread::JoinHandle<()>,
237}
238
239impl LspProcessClient {
240    /// Creates a new LSP client connected to the specified server.
241    ///
242    /// # Arguments
243    ///
244    /// * `root_uri` — the root URI of the workspace (e.g. `"file:///home/user/project"`)
245    /// * `events` — channel to send [`LspEvent`]s back to the application
246    /// * `server_key` — key identifying the LSP server (e.g. `"lua-language-server"`)
247    ///
248    /// # Errors
249    ///
250    /// Returns an error string when the server key is not recognised, when the
251    /// server binary cannot be found, or when the process cannot be spawned.
252    ///
253    /// # Examples
254    ///
255    /// ```no_run
256    /// use std::sync::mpsc;
257    /// use iced_code_editor::{LspProcessClient, LspEvent};
258    ///
259    /// let (tx, _rx) = mpsc::channel::<LspEvent>();
260    /// let client = LspProcessClient::new_with_server(
261    ///     "file:///tmp/project",
262    ///     tx,
263    ///     "lua-language-server",
264    /// );
265    /// assert!(client.is_ok());
266    /// ```
267    pub fn new_with_server(
268        root_uri: &str,
269        events: mpsc::Sender<LspEvent>,
270        server_key: &str,
271    ) -> Result<Self, String> {
272        let config = lsp_server_config(server_key)
273            .ok_or_else(|| format!("Unsupported LSP server: {}", server_key))?;
274
275        if server_key == "rust-analyzer" {
276            ensure_rust_analyzer_config();
277        }
278
279        let command = resolve_lsp_command(config)?;
280        Self::new_with_command(root_uri, events, &command, server_key)
281    }
282
283    /// Creates a new LSP client with a specific command.
284    ///
285    /// This is the internal implementation that spawns the process.
286    ///
287    /// # Errors
288    ///
289    /// Returns an error string if the process cannot be spawned or if stdio
290    /// handles cannot be acquired.
291    fn new_with_command(
292        root_uri: &str,
293        events: mpsc::Sender<LspEvent>,
294        command: &LspCommand,
295        server_key: &str,
296    ) -> Result<Self, String> {
297        let mut child = Command::new(&command.program)
298            .args(&command.args)
299            .stdin(Stdio::piped())
300            .stdout(Stdio::piped())
301            .stderr(Stdio::piped())
302            .spawn()
303            .map_err(|e| {
304                if e.kind() == std::io::ErrorKind::NotFound {
305                    if command.program == "rust-analyzer" {
306                        "LSP server program rust-analyzer not found. Please install rust-analyzer or set RUST_ANALYZER/RUST_ANALYZER_PATH environment variable".to_string()
307                    } else {
308                        format!("LSP server program {} not found", command.program)
309                    }
310                } else {
311                    e.to_string()
312                }
313            })?;
314
315        let stdin = child.stdin.take().ok_or("stdin unavailable")?;
316        let stdout = child.stdout.take().ok_or("stdout unavailable")?;
317        let stderr = child.stderr.take().ok_or("stderr unavailable")?;
318
319        let (tx, rx) = mpsc::channel::<Vec<u8>>();
320        let pending_requests = Arc::new(Mutex::new(HashMap::new()));
321        let pending_reader = pending_requests.clone();
322        let events_reader = events.clone();
323        let events_log = events;
324        let server_key = server_key.to_string();
325        let server_key_reader = server_key.clone();
326        let server_key_log = server_key;
327        let tx_reader = tx.clone();
328
329        let writer_thread = thread::spawn(move || {
330            let mut input = stdin;
331            for bytes in rx {
332                if input.write_all(&bytes).is_err() {
333                    break;
334                }
335                let _ = input.flush();
336            }
337        });
338
339        let reader_thread = thread::spawn(move || {
340            let mut reader = BufReader::new(stdout);
341            while let Some(buf) = read_message(&mut reader) {
342                if let Ok(value) =
343                    serde_json::from_slice::<serde_json::Value>(&buf)
344                {
345                    if let Some(id) = value.get("id").and_then(|v| v.as_u64()) {
346                        if let Some(method) =
347                            value.get("method").and_then(|m| m.as_str())
348                        {
349                            handle_server_request(id, method, &tx_reader);
350                        } else {
351                            handle_client_response(
352                                id,
353                                &value,
354                                &pending_reader,
355                                &events_reader,
356                            );
357                        }
358                    } else if let Some(method) =
359                        value.get("method").and_then(|m| m.as_str())
360                        && let Some(params) = value.get("params")
361                    {
362                        handle_server_notification(
363                            method,
364                            params,
365                            &events_reader,
366                            &server_key_reader,
367                        );
368                    }
369                }
370            }
371        });
372
373        let stderr_thread = thread::spawn(move || {
374            let reader = BufReader::new(stderr);
375            for line in reader.lines() {
376                let Ok(line) = line else { break };
377                let line = line.trim();
378                if line.is_empty() {
379                    continue;
380                }
381                let _ = events_log.send(LspEvent::Log {
382                    server_key: server_key_log.clone(),
383                    message: line.to_string(),
384                });
385            }
386        });
387
388        let client = Self {
389            child,
390            writer: tx,
391            documents: Arc::new(Mutex::new(HashMap::new())),
392            request_id: AtomicU64::new(1),
393            pending_requests,
394            _writer_thread: writer_thread,
395            _reader_thread: reader_thread,
396            _stderr_thread: stderr_thread,
397        };
398
399        let initialize = json!({
400            "jsonrpc": "2.0",
401            "id": client.next_id(),
402            "method": "initialize",
403            "params": {
404                "processId": std::process::id(),
405                "rootUri": root_uri,
406                "capabilities": {
407                    "textDocument": {
408                        "synchronization": {
409                            "dynamicRegistration": false,
410                            "willSave": false,
411                            "didSave": true
412                        }
413                    },
414                    "window": {
415                        "workDoneProgress": true
416                    }
417                },
418                "workspaceFolders": null
419            }
420        });
421        client.send_message(&initialize);
422
423        let initialized = json!({
424            "jsonrpc": "2.0",
425            "method": "initialized",
426            "params": {}
427        });
428        client.send_message(&initialized);
429
430        Ok(client)
431    }
432
433    /// Generates the next unique request ID using atomic operations.
434    fn next_id(&self) -> u64 {
435        self.request_id.fetch_add(1, Ordering::Relaxed)
436    }
437
438    /// Sends a JSON-RPC message to the LSP server.
439    ///
440    /// Formats the message with the required `Content-Length` header.
441    fn send_message(&self, value: &serde_json::Value) {
442        if let Some(bytes) = frame_message(value) {
443            let _ = self.writer.send(bytes);
444        }
445    }
446
447    /// Applies text changes to a document and converts them to JSON format.
448    ///
449    /// Also converts positions to UTF-16 as required by LSP.
450    fn apply_change_and_convert(
451        &self,
452        uri: &str,
453        changes: &[LspTextChange],
454    ) -> Vec<serde_json::Value> {
455        let mut out = Vec::new();
456        let mut docs = self.documents.lock().unwrap_or_else(|e| e.into_inner());
457        let Some(state) = docs.get_mut(uri) else { return out };
458
459        for change in changes {
460            let start = state.text.to_utf16_position(change.range.start);
461            let end = state.text.to_utf16_position(change.range.end);
462
463            out.push(json!({
464                "range": {
465                    "start": { "line": start.line, "character": start.character },
466                    "end": { "line": end.line, "character": end.character }
467                },
468                "text": change.text
469            }));
470
471            state.text.apply_change(change);
472        }
473        out
474    }
475}
476
477// =============================================================================
478// Reader thread helper functions
479// =============================================================================
480
481/// Reads one `Content-Length`-framed message body from `reader`.
482///
483/// Returns `None` when the stream ends, when the body cannot be read in full,
484/// or when the announced frame exceeds [`MAX_MESSAGE_BYTES`]. An oversized
485/// frame cannot be skipped reliably — the body length is exactly what is not
486/// trustworthy — so the caller must stop reading the stream rather than try to
487/// resynchronise mid-message.
488///
489/// Header lines other than `Content-Length` are ignored. A header block
490/// carrying no `Content-Length` yields an empty body, which the caller then
491/// discards as invalid JSON.
492fn read_message(reader: &mut impl BufRead) -> Option<Vec<u8>> {
493    let mut content_length: Option<usize> = None;
494    let mut line = String::new();
495
496    loop {
497        line.clear();
498        // A zero-length read means end of stream, not an empty header line.
499        reader.read_line(&mut line).ok().filter(|n| *n > 0)?;
500        let trimmed = line.trim();
501        if trimmed.is_empty() {
502            break;
503        }
504        if let Some(value) = trimmed.strip_prefix("Content-Length:")
505            && let Ok(len) = value.trim().parse::<usize>()
506        {
507            content_length = Some(len);
508        }
509    }
510
511    let len = content_length.unwrap_or(0);
512    if len > MAX_MESSAGE_BYTES {
513        return None;
514    }
515
516    let mut buf = vec![0u8; len];
517    if reader.read_exact(&mut buf).is_err() {
518        return None;
519    }
520    Some(buf)
521}
522
523/// Frames a JSON-RPC value as `Content-Length: N\r\n\r\n<body>` bytes, ready
524/// to be written to an LSP server's stdin.
525///
526/// Returns `None` if `value` cannot be serialized to JSON.
527///
528/// # Examples
529///
530/// ```ignore
531/// let framed = frame_message(&serde_json::json!({"jsonrpc": "2.0"})).unwrap();
532/// assert!(framed.starts_with(b"Content-Length: "));
533/// ```
534fn frame_message(value: &serde_json::Value) -> Option<Vec<u8>> {
535    let data = serde_json::to_vec(value).ok()?;
536    let mut framed =
537        format!("Content-Length: {}\r\n\r\n", data.len()).into_bytes();
538    framed.extend_from_slice(&data);
539    Some(framed)
540}
541
542/// Handles an LSP server request that requires a JSON-RPC response.
543///
544/// Currently handles `window/workDoneProgress/create` by replying with a null
545/// result. Unknown methods are silently ignored.
546fn handle_server_request(id: u64, method: &str, tx: &mpsc::Sender<Vec<u8>>) {
547    if method == METHOD_WORK_DONE_PROGRESS_CREATE {
548        let response = json!({
549            "jsonrpc": "2.0",
550            "id": id,
551            "result": null
552        });
553        if let Some(bytes) = frame_message(&response) {
554            let _ = tx.send(bytes);
555        }
556    }
557}
558
559/// Dispatches a server response to the appropriate pending request handler.
560///
561/// Looks up the request kind by `id`, parses the result, and emits a
562/// [`LspEvent::Hover`], [`LspEvent::Completion`], or [`LspEvent::Definition`].
563fn handle_client_response(
564    id: u64,
565    value: &serde_json::Value,
566    pending: &Arc<Mutex<HashMap<u64, LspRequestKind>>>,
567    events: &mpsc::Sender<LspEvent>,
568) {
569    let kind = {
570        let mut map = pending.lock().unwrap_or_else(|e| e.into_inner());
571        map.remove(&id)
572    };
573
574    let Some(kind) = kind else { return };
575    let result = value.get("result").unwrap_or(&serde_json::Value::Null);
576
577    match kind {
578        LspRequestKind::Hover => {
579            let text = parse_hover_text(result).unwrap_or_default();
580            let _ = events.send(LspEvent::Hover { text });
581        }
582        LspRequestKind::Completion => {
583            let items = parse_completion_items(result);
584            if !items.is_empty() {
585                let _ = events.send(LspEvent::Completion { items });
586            }
587        }
588        LspRequestKind::Definition => {
589            if let Some((uri, range)) = parse_definition_location(result) {
590                let _ = events.send(LspEvent::Definition { uri, range });
591            }
592        }
593    }
594}
595
596/// Handles a server-initiated notification (e.g. `$/progress`).
597///
598/// Parses the progress payload and emits a [`LspEvent::Progress`].
599/// Notifications for unknown methods are silently ignored.
600fn handle_server_notification(
601    method: &str,
602    params: &serde_json::Value,
603    events: &mpsc::Sender<LspEvent>,
604    server_key: &str,
605) {
606    if method != METHOD_PROGRESS {
607        return;
608    }
609
610    let Some(token) = params.get("token").and_then(|t| {
611        t.as_str()
612            .map(String::from)
613            .or_else(|| t.as_i64().map(|i| i.to_string()))
614    }) else {
615        return;
616    };
617
618    let Some(val) = params.get("value") else { return };
619
620    let kind = val.get("kind").and_then(|k| k.as_str()).unwrap_or("");
621    let title = val
622        .get("title")
623        .and_then(|t| t.as_str())
624        .map(String::from)
625        .unwrap_or_default();
626    let message = val.get("message").and_then(|m| m.as_str()).map(String::from);
627    let percentage =
628        val.get("percentage").and_then(|p| p.as_u64()).map(|p| p as u32);
629    let done = kind == PROGRESS_KIND_END;
630
631    let _ = events.send(LspEvent::Progress {
632        token,
633        server_key: server_key.to_string(),
634        title,
635        message,
636        percentage,
637        done,
638    });
639}
640
641/// Sends shutdown/exit notifications and kills the process on drop.
642impl Drop for LspProcessClient {
643    fn drop(&mut self) {
644        let shutdown = json!({
645            "jsonrpc": "2.0",
646            "id": self.next_id(),
647            "method": "shutdown",
648            "params": null
649        });
650        self.send_message(&shutdown);
651
652        let exit = json!({
653            "jsonrpc": "2.0",
654            "method": "exit",
655            "params": {}
656        });
657        self.send_message(&exit);
658
659        if self.child.try_wait().ok().flatten().is_none() {
660            let _ = self.child.kill();
661        }
662    }
663}
664
665// =============================================================================
666// LSP Response Parsing Functions
667// =============================================================================
668
669/// Parses hover text from an LSP hover response.
670fn parse_hover_text(result: &serde_json::Value) -> Option<String> {
671    let contents = result.get("contents")?;
672    hover_text_from_contents(contents)
673}
674
675/// Recursively extracts hover text from various content formats.
676///
677/// Handles strings, arrays, and objects with a `"value"` field.
678fn hover_text_from_contents(value: &serde_json::Value) -> Option<String> {
679    match value {
680        serde_json::Value::String(text) => Some(text.clone()),
681        serde_json::Value::Array(items) => {
682            let parts: Vec<String> =
683                items.iter().filter_map(hover_text_from_contents).collect();
684            if parts.is_empty() { None } else { Some(parts.join("\n")) }
685        }
686        serde_json::Value::Object(map) => {
687            map.get("value").and_then(|v| v.as_str()).map(String::from)
688        }
689        _ => None,
690    }
691}
692
693/// Parses completion items from an LSP completion response.
694///
695/// Handles both array responses and object responses with an `"items"` field.
696fn parse_completion_items(result: &serde_json::Value) -> Vec<String> {
697    let mut items = Vec::new();
698
699    if let Some(array) = result.as_array() {
700        items.extend(array.iter());
701    } else if let Some(array) = result.get("items").and_then(|v| v.as_array()) {
702        items.extend(array.iter());
703    }
704
705    items
706        .iter()
707        .filter_map(|item| item.get("label").and_then(|v| v.as_str()))
708        .map(String::from)
709        .collect()
710}
711
712/// Parses a JSON-RPC `Range` object (`{start: {line, character}, end: {...}}`)
713/// into an [`LspRange`].
714///
715/// Returns `None` if either endpoint is missing or has the wrong shape.
716fn extract_range(range_val: &serde_json::Value) -> Option<LspRange> {
717    let start = range_val.get("start")?;
718    let end = range_val.get("end")?;
719
720    Some(LspRange {
721        start: LspPosition {
722            line: start.get("line")?.as_u64()? as u32,
723            character: start.get("character")?.as_u64()? as u32,
724        },
725        end: LspPosition {
726            line: end.get("line")?.as_u64()? as u32,
727            character: end.get("character")?.as_u64()? as u32,
728        },
729    })
730}
731
732/// Extracts `(uri, range)` from an LSP `Location` object.
733fn extract_location(loc: &serde_json::Value) -> Option<(String, LspRange)> {
734    let uri = loc.get("uri")?.as_str()?.to_string();
735    let range = extract_range(loc.get("range")?)?;
736    Some((uri, range))
737}
738
739/// Extracts `(uri, range)` from an LSP `LocationLink` object.
740///
741/// Prefers `targetSelectionRange` (the precise symbol range) and falls back
742/// to `targetRange` (the enclosing range) when it is absent.
743fn extract_link(link: &serde_json::Value) -> Option<(String, LspRange)> {
744    let uri = link.get("targetUri")?.as_str()?.to_string();
745    let range_val =
746        link.get("targetSelectionRange").or(link.get("targetRange"))?;
747    let range = extract_range(range_val)?;
748    Some((uri, range))
749}
750
751/// Parses definition location from an LSP definition response.
752///
753/// Handles `Location`, `Location[]`, and `LocationLink[]` responses.
754fn parse_definition_location(
755    result: &serde_json::Value,
756) -> Option<(String, LspRange)> {
757    if let Some(array) = result.as_array() {
758        if let Some(first) = array.first() {
759            if first.get("targetUri").is_some() {
760                extract_link(first)
761            } else {
762                extract_location(first)
763            }
764        } else {
765            None
766        }
767    } else if result.is_object() {
768        extract_location(result)
769    } else {
770        None
771    }
772}
773
774// =============================================================================
775// LspClient Trait Implementation
776// =============================================================================
777
778impl LspClient for LspProcessClient {
779    fn did_open(&mut self, document: &LspDocument, text: &str) {
780        let mut docs = self.documents.lock().unwrap_or_else(|e| e.into_inner());
781        docs.insert(
782            document.uri.clone(),
783            DocumentState { text: TextModel::from_text(text) },
784        );
785
786        let msg = json!({
787            "jsonrpc": "2.0",
788            "method": "textDocument/didOpen",
789            "params": {
790                "textDocument": {
791                    "uri": document.uri,
792                    "languageId": document.language_id,
793                    "version": document.version,
794                    "text": text
795                }
796            }
797        });
798        self.send_message(&msg);
799    }
800
801    fn did_change(
802        &mut self,
803        document: &LspDocument,
804        changes: &[LspTextChange],
805    ) {
806        let content_changes =
807            self.apply_change_and_convert(&document.uri, changes);
808        if content_changes.is_empty() {
809            return;
810        }
811
812        let msg = json!({
813            "jsonrpc": "2.0",
814            "method": "textDocument/didChange",
815            "params": {
816                "textDocument": {
817                    "uri": document.uri,
818                    "version": document.version
819                },
820                "contentChanges": content_changes
821            }
822        });
823        self.send_message(&msg);
824    }
825
826    fn did_save(&mut self, document: &LspDocument, text: &str) {
827        let msg = json!({
828            "jsonrpc": "2.0",
829            "method": "textDocument/didSave",
830            "params": {
831                "textDocument": { "uri": document.uri },
832                "text": text
833            }
834        });
835        self.send_message(&msg);
836    }
837
838    fn did_close(&mut self, document: &LspDocument) {
839        let mut docs = self.documents.lock().unwrap_or_else(|e| e.into_inner());
840        docs.remove(&document.uri);
841
842        let msg = json!({
843            "jsonrpc": "2.0",
844            "method": "textDocument/didClose",
845            "params": {
846                "textDocument": { "uri": document.uri }
847            }
848        });
849        self.send_message(&msg);
850    }
851
852    fn request_hover(&mut self, document: &LspDocument, position: LspPosition) {
853        let docs = self.documents.lock().unwrap_or_else(|e| e.into_inner());
854        let Some(state) = docs.get(&document.uri) else { return };
855        let pos = state.text.to_utf16_position(position);
856
857        let id = self.next_id();
858        {
859            let mut pending =
860                self.pending_requests.lock().unwrap_or_else(|e| e.into_inner());
861            pending.insert(id, LspRequestKind::Hover);
862        }
863
864        let msg = json!({
865            "jsonrpc": "2.0",
866            "id": id,
867            "method": "textDocument/hover",
868            "params": {
869                "textDocument": { "uri": document.uri },
870                "position": { "line": pos.line, "character": pos.character }
871            }
872        });
873        self.send_message(&msg);
874    }
875
876    fn request_completion(
877        &mut self,
878        document: &LspDocument,
879        position: LspPosition,
880    ) {
881        let docs = self.documents.lock().unwrap_or_else(|e| e.into_inner());
882        let Some(state) = docs.get(&document.uri) else { return };
883        let pos = state.text.to_utf16_position(position);
884
885        let id = self.next_id();
886        {
887            let mut pending =
888                self.pending_requests.lock().unwrap_or_else(|e| e.into_inner());
889            pending.insert(id, LspRequestKind::Completion);
890        }
891
892        let msg = json!({
893            "jsonrpc": "2.0",
894            "id": id,
895            "method": "textDocument/completion",
896            "params": {
897                "textDocument": { "uri": document.uri },
898                "position": { "line": pos.line, "character": pos.character },
899                "context": { "triggerKind": 1 }
900            }
901        });
902        self.send_message(&msg);
903    }
904
905    fn request_definition(
906        &mut self,
907        document: &LspDocument,
908        position: LspPosition,
909    ) {
910        let docs = self.documents.lock().unwrap_or_else(|e| e.into_inner());
911        let Some(state) = docs.get(&document.uri) else { return };
912        let pos = state.text.to_utf16_position(position);
913
914        let id = self.next_id();
915        {
916            let mut pending =
917                self.pending_requests.lock().unwrap_or_else(|e| e.into_inner());
918            pending.insert(id, LspRequestKind::Definition);
919        }
920
921        let msg = json!({
922            "jsonrpc": "2.0",
923            "id": id,
924            "method": "textDocument/definition",
925            "params": {
926                "textDocument": { "uri": document.uri },
927                "position": { "line": pos.line, "character": pos.character }
928            }
929        });
930        self.send_message(&msg);
931    }
932}
933
934#[cfg(test)]
935mod tests {
936    // Several helpers and tests below carry an `#[allow]` for `expect_used`,
937    // `panic` or `unwrap_used`. In test code a panic *is* the failure report:
938    // `expect("expected a Hover event")` names the broken expectation far more
939    // precisely than an `assert!(false)` workaround would. The workspace denies
940    // these lints to protect production code, not tests — this mirrors the
941    // existing per-test allows in `update.rs` and `selection.rs`.
942    use super::*;
943
944    /// Returns the JSON body of a `Content-Length`-framed message taken from
945    /// the writer channel.
946    #[allow(clippy::expect_used)]
947    fn decode_sent(data: &[u8]) -> serde_json::Value {
948        let header_end = data
949            .windows(4)
950            .position(|w| w == b"\r\n\r\n")
951            .expect("missing header separator");
952        let body = &data[header_end + 4..];
953        serde_json::from_slice(body).expect("invalid JSON body")
954    }
955
956    // -------------------------------------------------------------------------
957    // read_message
958    // -------------------------------------------------------------------------
959
960    #[test]
961    fn test_read_message_reads_framed_body() {
962        let mut stream = std::io::Cursor::new(
963            b"Content-Length: 9\r\n\r\n{\"id\":42}".to_vec(),
964        );
965        assert_eq!(
966            read_message(&mut stream).as_deref(),
967            Some(&b"{\"id\":42}"[..])
968        );
969    }
970
971    #[test]
972    fn test_read_message_ignores_other_headers() {
973        let mut stream = std::io::Cursor::new(
974            b"Content-Type: application/vscode-jsonrpc\r\nContent-Length: 2\r\n\r\n{}"
975                .to_vec(),
976        );
977        assert_eq!(read_message(&mut stream).as_deref(), Some(&b"{}"[..]));
978    }
979
980    #[test]
981    fn test_read_message_reads_consecutive_frames() {
982        let mut stream = std::io::Cursor::new(
983            b"Content-Length: 2\r\n\r\n{}Content-Length: 4\r\n\r\n[1,]"
984                .to_vec(),
985        );
986        assert_eq!(read_message(&mut stream).as_deref(), Some(&b"{}"[..]));
987        assert_eq!(read_message(&mut stream).as_deref(), Some(&b"[1,]"[..]));
988        assert!(read_message(&mut stream).is_none(), "stream is exhausted");
989    }
990
991    #[test]
992    fn test_read_message_rejects_oversized_frame() {
993        // The announced length exceeds MAX_MESSAGE_BYTES: the frame must be
994        // refused without allocating it.
995        let header =
996            format!("Content-Length: {}\r\n\r\n", MAX_MESSAGE_BYTES + 1);
997        let mut stream = std::io::Cursor::new(header.into_bytes());
998        assert!(read_message(&mut stream).is_none());
999    }
1000
1001    #[test]
1002    fn test_read_message_rejects_truncated_body() {
1003        let mut stream =
1004            std::io::Cursor::new(b"Content-Length: 10\r\n\r\nabc".to_vec());
1005        assert!(read_message(&mut stream).is_none());
1006    }
1007
1008    #[test]
1009    fn test_read_message_ends_on_empty_stream() {
1010        let mut stream = std::io::Cursor::new(Vec::new());
1011        assert!(read_message(&mut stream).is_none());
1012    }
1013
1014    #[test]
1015    fn test_read_message_without_content_length_yields_empty_body() {
1016        // No Content-Length: the caller gets an empty body and discards it as
1017        // invalid JSON, then keeps reading.
1018        let mut stream = std::io::Cursor::new(b"X-Unknown: 1\r\n\r\n".to_vec());
1019        assert_eq!(read_message(&mut stream).as_deref(), Some(&b""[..]));
1020    }
1021
1022    // -------------------------------------------------------------------------
1023    // frame_message
1024    // -------------------------------------------------------------------------
1025
1026    #[test]
1027    #[allow(clippy::unwrap_used)]
1028    fn test_frame_message_builds_content_length_header() {
1029        let value = serde_json::json!({"jsonrpc": "2.0", "id": 1});
1030        let data = serde_json::to_vec(&value).unwrap();
1031        let framed = frame_message(&value).unwrap();
1032
1033        let expected_header = format!("Content-Length: {}\r\n\r\n", data.len());
1034        assert!(framed.starts_with(expected_header.as_bytes()));
1035        assert_eq!(&framed[expected_header.len()..], data.as_slice());
1036    }
1037
1038    // -------------------------------------------------------------------------
1039    // extract_range / extract_location / extract_link
1040    // -------------------------------------------------------------------------
1041
1042    #[test]
1043    #[allow(clippy::unwrap_used)]
1044    fn test_extract_range_parses_start_and_end() {
1045        let range_val = serde_json::json!({
1046            "start": { "line": 1, "character": 2 },
1047            "end": { "line": 3, "character": 4 }
1048        });
1049        let range = extract_range(&range_val).unwrap();
1050        assert_eq!(range.start, LspPosition { line: 1, character: 2 });
1051        assert_eq!(range.end, LspPosition { line: 3, character: 4 });
1052    }
1053
1054    #[test]
1055    fn test_extract_range_missing_end_returns_none() {
1056        let range_val = serde_json::json!({
1057            "start": { "line": 1, "character": 2 }
1058        });
1059        assert!(extract_range(&range_val).is_none());
1060    }
1061
1062    #[test]
1063    #[allow(clippy::unwrap_used)]
1064    fn test_extract_location_reads_uri_and_range() {
1065        let loc = serde_json::json!({
1066            "uri": "file:///a.rs",
1067            "range": {
1068                "start": { "line": 0, "character": 0 },
1069                "end": { "line": 0, "character": 1 }
1070            }
1071        });
1072        let (uri, range) = extract_location(&loc).unwrap();
1073        assert_eq!(uri, "file:///a.rs");
1074        assert_eq!(range.start, LspPosition { line: 0, character: 0 });
1075    }
1076
1077    #[test]
1078    #[allow(clippy::unwrap_used)]
1079    fn test_extract_link_prefers_target_selection_range() {
1080        let link = serde_json::json!({
1081            "targetUri": "file:///b.rs",
1082            "targetRange": {
1083                "start": { "line": 10, "character": 0 },
1084                "end": { "line": 20, "character": 0 }
1085            },
1086            "targetSelectionRange": {
1087                "start": { "line": 12, "character": 4 },
1088                "end": { "line": 12, "character": 8 }
1089            }
1090        });
1091        let (uri, range) = extract_link(&link).unwrap();
1092        assert_eq!(uri, "file:///b.rs");
1093        assert_eq!(range.start, LspPosition { line: 12, character: 4 });
1094    }
1095
1096    #[test]
1097    #[allow(clippy::unwrap_used)]
1098    fn test_extract_link_falls_back_to_target_range() {
1099        let link = serde_json::json!({
1100            "targetUri": "file:///c.rs",
1101            "targetRange": {
1102                "start": { "line": 5, "character": 0 },
1103                "end": { "line": 6, "character": 0 }
1104            }
1105        });
1106        let (uri, range) = extract_link(&link).unwrap();
1107        assert_eq!(uri, "file:///c.rs");
1108        assert_eq!(range.start, LspPosition { line: 5, character: 0 });
1109    }
1110
1111    // -------------------------------------------------------------------------
1112    // handle_server_request
1113    // -------------------------------------------------------------------------
1114
1115    #[test]
1116    #[allow(clippy::expect_used)]
1117    fn test_handle_server_request_work_done_progress_create() {
1118        let (tx, rx) = mpsc::channel::<Vec<u8>>();
1119        handle_server_request(42, METHOD_WORK_DONE_PROGRESS_CREATE, &tx);
1120
1121        let bytes = rx.try_recv().expect("expected a response on the channel");
1122        let value = decode_sent(&bytes);
1123        assert_eq!(value["id"], 42);
1124        assert_eq!(value["jsonrpc"], "2.0");
1125        assert!(value["result"].is_null());
1126    }
1127
1128    #[test]
1129    fn test_handle_server_request_unknown_method_ignored() {
1130        let (tx, rx) = mpsc::channel::<Vec<u8>>();
1131        handle_server_request(1, "unknown/method", &tx);
1132        assert!(
1133            rx.try_recv().is_err(),
1134            "unknown methods must not send a reply"
1135        );
1136    }
1137
1138    // -------------------------------------------------------------------------
1139    // handle_client_response
1140    // -------------------------------------------------------------------------
1141
1142    #[test]
1143    #[allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)]
1144    fn test_handle_client_response_hover() {
1145        let (events_tx, events_rx) = mpsc::channel::<LspEvent>();
1146        let pending = Arc::new(Mutex::new(HashMap::new()));
1147        pending.lock().unwrap().insert(1u64, LspRequestKind::Hover);
1148
1149        let value = serde_json::json!({
1150            "id": 1,
1151            "result": { "contents": { "value": "hover info" } }
1152        });
1153        handle_client_response(1, &value, &pending, &events_tx);
1154
1155        match events_rx.try_recv().expect("expected a Hover event") {
1156            LspEvent::Hover { text } => assert_eq!(text, "hover info"),
1157            _ => panic!("expected LspEvent::Hover"),
1158        }
1159        assert!(pending.lock().unwrap().is_empty());
1160    }
1161
1162    #[test]
1163    #[allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)]
1164    fn test_handle_client_response_completion() {
1165        let (events_tx, events_rx) = mpsc::channel::<LspEvent>();
1166        let pending = Arc::new(Mutex::new(HashMap::new()));
1167        pending.lock().unwrap().insert(2u64, LspRequestKind::Completion);
1168
1169        let value = serde_json::json!({
1170            "id": 2,
1171            "result": { "items": [{ "label": "foo" }, { "label": "bar" }] }
1172        });
1173        handle_client_response(2, &value, &pending, &events_tx);
1174
1175        match events_rx.try_recv().expect("expected a Completion event") {
1176            LspEvent::Completion { items } => {
1177                assert_eq!(items, vec!["foo", "bar"]);
1178            }
1179            _ => panic!("expected LspEvent::Completion"),
1180        }
1181    }
1182
1183    #[test]
1184    #[allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)]
1185    fn test_handle_client_response_definition() {
1186        let (events_tx, events_rx) = mpsc::channel::<LspEvent>();
1187        let pending = Arc::new(Mutex::new(HashMap::new()));
1188        pending.lock().unwrap().insert(3u64, LspRequestKind::Definition);
1189
1190        let value = serde_json::json!({
1191            "id": 3,
1192            "result": {
1193                "uri": "file:///foo/bar.rs",
1194                "range": {
1195                    "start": { "line": 0, "character": 0 },
1196                    "end": { "line": 0, "character": 5 }
1197                }
1198            }
1199        });
1200        handle_client_response(3, &value, &pending, &events_tx);
1201
1202        match events_rx.try_recv().expect("expected a Definition event") {
1203            LspEvent::Definition { uri, .. } => {
1204                assert_eq!(uri, "file:///foo/bar.rs");
1205            }
1206            _ => panic!("expected LspEvent::Definition"),
1207        }
1208    }
1209
1210    #[test]
1211    fn test_handle_client_response_unknown_id_ignored() {
1212        let (events_tx, events_rx) = mpsc::channel::<LspEvent>();
1213        let pending = Arc::new(Mutex::new(HashMap::new()));
1214
1215        let value = serde_json::json!({ "id": 99, "result": null });
1216        handle_client_response(99, &value, &pending, &events_tx);
1217        assert!(
1218            events_rx.try_recv().is_err(),
1219            "unknown IDs must not emit events"
1220        );
1221    }
1222
1223    // -------------------------------------------------------------------------
1224    // handle_server_notification
1225    // -------------------------------------------------------------------------
1226
1227    #[test]
1228    #[allow(clippy::expect_used, clippy::panic)]
1229    fn test_handle_server_notification_progress_done() {
1230        let (events_tx, events_rx) = mpsc::channel::<LspEvent>();
1231        let params = serde_json::json!({
1232            "token": "my-token",
1233            "value": {
1234                "kind": "end",
1235                "title": "Indexing",
1236                "message": "done"
1237            }
1238        });
1239
1240        handle_server_notification(
1241            METHOD_PROGRESS,
1242            &params,
1243            &events_tx,
1244            "lua-ls",
1245        );
1246
1247        match events_rx.try_recv().expect("expected a Progress event") {
1248            LspEvent::Progress { token, done, server_key, .. } => {
1249                assert_eq!(token, "my-token");
1250                assert!(done);
1251                assert_eq!(server_key, "lua-ls");
1252            }
1253            _ => panic!("expected LspEvent::Progress"),
1254        }
1255    }
1256
1257    #[test]
1258    #[allow(clippy::expect_used, clippy::panic)]
1259    fn test_handle_server_notification_progress_not_done() {
1260        let (events_tx, events_rx) = mpsc::channel::<LspEvent>();
1261        let params = serde_json::json!({
1262            "token": "tok",
1263            "value": { "kind": "report", "title": "Building" }
1264        });
1265
1266        handle_server_notification(
1267            METHOD_PROGRESS,
1268            &params,
1269            &events_tx,
1270            "rust-analyzer",
1271        );
1272
1273        match events_rx.try_recv().expect("expected a Progress event") {
1274            LspEvent::Progress { done, .. } => assert!(!done),
1275            _ => panic!("expected LspEvent::Progress"),
1276        }
1277    }
1278
1279    #[test]
1280    fn test_handle_server_notification_unknown_method_ignored() {
1281        let (events_tx, events_rx) = mpsc::channel::<LspEvent>();
1282        let params = serde_json::json!({});
1283        handle_server_notification(
1284            "$/somethingElse",
1285            &params,
1286            &events_tx,
1287            "server",
1288        );
1289        assert!(events_rx.try_recv().is_err());
1290    }
1291}