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//!
8//! The transport itself lives in [`protocol`]: framing, bounded reads, message
9//! dispatch, and response parsing. [`text_model`] holds the per-document mirror
10//! used for UTF-16 position translation, and [`pending`] tracks in-flight
11//! requests. What remains here is the process lifecycle and the [`LspClient`]
12//! implementation the editor talks to.
13
14pub mod config;
15pub mod overlay;
16
17mod pending;
18mod protocol;
19mod text_model;
20
21use self::config::{
22    LspCommand, ensure_rust_analyzer_config, lsp_server_config,
23    resolve_lsp_command,
24};
25use self::pending::{LspRequestKind, PendingRequest, evict_expired_requests};
26use self::protocol::{
27    frame_message, handle_client_response, handle_server_notification,
28    handle_server_request, read_log_line, read_message,
29};
30use self::text_model::{DocumentState, TextModel, apply_changes_to_document};
31use crate::canvas_editor::lsp::{
32    LspClient, LspDocument, LspFormattingOptions, LspPosition, LspRange,
33    LspTextChange,
34};
35use serde_json::json;
36use std::collections::HashMap;
37use std::io::{BufReader, Write};
38use std::process::{Child, Command, Stdio};
39use std::sync::atomic::{AtomicU64, Ordering};
40use std::sync::{Arc, Mutex, mpsc};
41use std::thread;
42use std::time::Instant;
43// =============================================================================
44// LSP Events - Events sent back to the main application
45// =============================================================================
46
47/// Recommended capacity for the [`LspEvent`] channel.
48///
49/// The channel has to be bounded: it is fed by a language server this
50/// application does not control, and `rust-analyzer` on a large workspace
51/// emits a great deal. An unbounded queue turns that into unbounded memory
52/// whenever the host drains more slowly than the server produces.
53///
54/// Sized well above what a host draining on a timer can fall behind by, so the
55/// bound never bites in normal use -- draining
56/// `MAX_LSP_EVENTS_PER_TICK`-sized batches at 60 Hz clears far more than this
57/// per second. Its job is to put a ceiling on a pathological server, not to
58/// shape ordinary traffic.
59pub const LSP_EVENT_QUEUE_CAPACITY: usize = 4_096;
60
61/// Hands an event to the application, dropping it if the queue is full.
62///
63/// Dropping rather than blocking, because the sender is the reader thread: it
64/// is what drains the server's stdout, so blocking it would stall that pipe
65/// and back-pressure the server for as long as the host took to catch up.
66///
67/// Dropping is safe for every [`LspEvent`] variant. None of them carries state
68/// the client must not lose: `Hover`, `Completion`, `Definition` and
69/// `Formatting` are each one UI update that the user's next gesture
70/// re-requests, `Progress` is superseded by the next notification for the same
71/// token, and `Log` is advisory. In particular a dropped response strands nothing --
72/// `handle_client_response` removes the entry from `pending_requests` *before*
73/// emitting, so the request is already accounted for.
74///
75/// # Arguments
76///
77/// * `events` - Channel to the application
78/// * `event` - The event to hand over
79pub(super) fn emit(events: &mpsc::SyncSender<LspEvent>, event: LspEvent) {
80    let _ = events.try_send(event);
81}
82
83/// Events that can be sent from the LSP client to the application.
84///
85/// Receive these by polling the `mpsc::Receiver` you pass to
86/// [`LspProcessClient::new_with_server`]. Requests are fire-and-forget, so
87/// every server reply arrives here rather than as a return value — drain the
88/// receiver on a timer and fold the results into the application state.
89///
90/// # Examples
91///
92/// ```
93/// use std::sync::mpsc;
94///
95/// use iced_code_editor::{LspEvent, LSP_EVENT_QUEUE_CAPACITY};
96///
97/// // Bounded: the queue is fed by a language server, so it needs a ceiling.
98/// let (tx, rx) = mpsc::sync_channel::<LspEvent>(LSP_EVENT_QUEUE_CAPACITY);
99/// tx.send(LspEvent::Hover { text: "fn main()".to_string() })
100///     .expect("the receiver is still alive");
101///
102/// // Drain everything queued since the last tick.
103/// while let Ok(event) = rx.try_recv() {
104///     match event {
105///         LspEvent::Hover { text } => assert_eq!(text, "fn main()"),
106///         LspEvent::Completion { items } => drop(items),
107///         LspEvent::Definition { uri, .. } => drop(uri),
108///         LspEvent::Formatting { edits, .. } => drop(edits),
109///         LspEvent::Progress { done, .. } => drop(done),
110///         LspEvent::Log { message, .. } => drop(message),
111///     }
112/// }
113/// ```
114pub enum LspEvent {
115    /// Hover information received from the LSP server.
116    Hover {
117        /// Markdown or plain-text hover content.
118        text: String,
119    },
120    /// Completion items received from the LSP server.
121    Completion {
122        /// List of completion label strings.
123        items: Vec<String>,
124    },
125    /// Definition location received from the LSP server.
126    Definition {
127        /// Target document URI.
128        uri: String,
129        /// Target range within that document.
130        range: crate::canvas_editor::lsp::LspRange,
131    },
132    /// Formatting edits received from the LSP server.
133    Formatting {
134        /// URI of the document the edits apply to.
135        uri: String,
136        /// Edits to apply, in the document's own character coordinates.
137        ///
138        /// Apply them with [`CodeEditor::apply_lsp_text_edits`], which takes
139        /// care of ordering and of landing them as a single undo step.
140        ///
141        /// [`CodeEditor::apply_lsp_text_edits`]: crate::CodeEditor::apply_lsp_text_edits
142        edits: Vec<LspTextChange>,
143    },
144    /// Progress notification from the LSP server.
145    Progress {
146        /// Progress token identifier.
147        token: String,
148        /// Key of the server that sent this notification.
149        server_key: String,
150        /// Human-readable title for the progress operation.
151        title: String,
152        /// Optional status message.
153        message: Option<String>,
154        /// Optional percentage complete (0–100).
155        percentage: Option<u32>,
156        /// `true` when this is the final progress notification.
157        done: bool,
158    },
159    /// Log message from the LSP server's stderr.
160    Log {
161        /// Key of the server that sent this message.
162        server_key: String,
163        /// The log line.
164        message: String,
165    },
166}
167
168// =============================================================================
169// LSP Process Client - Main client implementation
170// =============================================================================
171
172/// Client for communicating with an LSP server process.
173///
174/// Manages the lifecycle of the server process and handles all communication.
175/// Implements [`LspClient`] so it can be plugged directly into a [`CodeEditor`].
176///
177/// # Examples
178///
179/// ```no_run
180/// use std::sync::mpsc;
181/// use iced_code_editor::{LspProcessClient, LspEvent, LSP_EVENT_QUEUE_CAPACITY};
182///
183/// let (tx, rx) = mpsc::sync_channel::<LspEvent>(LSP_EVENT_QUEUE_CAPACITY);
184/// let client = LspProcessClient::new_with_server(
185///     "file:///home/user/project",
186///     tx,
187///     "lua-language-server",
188/// );
189/// ```
190///
191/// [`CodeEditor`]: crate::CodeEditor
192pub struct LspProcessClient {
193    /// The child process running the LSP server
194    child: Child,
195    /// Channel for sending messages to the writer thread
196    writer: mpsc::Sender<Vec<u8>>,
197    /// Map of URI to document state for all open documents
198    documents: Arc<Mutex<HashMap<String, DocumentState>>>,
199    /// Channel used to report a document mirror going out of sync (see
200    /// [`Self::apply_change_and_convert`]); the reader/stderr threads carry
201    /// their own clone of the same sender for server-pushed events.
202    events: mpsc::SyncSender<LspEvent>,
203    /// Key identifying the connected server, used to label events emitted
204    /// directly by the client rather than by the reader/stderr threads.
205    server_key: String,
206    /// Counter for generating unique request IDs
207    request_id: AtomicU64,
208    /// Map of pending request IDs to their types and send time (for
209    /// response routing and expiry of abandoned requests)
210    pending_requests: Arc<Mutex<HashMap<u64, PendingRequest>>>,
211    /// Handle to the writer thread (kept alive for the client's lifetime)
212    _writer_thread: thread::JoinHandle<()>,
213    /// Handle to the reader thread (kept alive for the client's lifetime)
214    _reader_thread: thread::JoinHandle<()>,
215    /// Handle to the stderr thread (kept alive for the client's lifetime)
216    _stderr_thread: thread::JoinHandle<()>,
217}
218
219impl LspProcessClient {
220    /// Creates a new LSP client connected to the specified server.
221    ///
222    /// # Arguments
223    ///
224    /// * `root_uri` — the root URI of the workspace (e.g. `"file:///home/user/project"`)
225    /// * `events` — channel to send [`LspEvent`]s back to the application
226    /// * `server_key` — key identifying the LSP server (e.g. `"lua-language-server"`)
227    ///
228    /// # Errors
229    ///
230    /// Returns an error string when the server key is not recognised, when the
231    /// server binary cannot be found, or when the process cannot be spawned.
232    ///
233    /// # Examples
234    ///
235    /// ```no_run
236    /// use std::sync::mpsc;
237    /// use iced_code_editor::{
238    ///     LSP_EVENT_QUEUE_CAPACITY, LspEvent, LspProcessClient,
239    /// };
240    ///
241    /// let (tx, _rx) = mpsc::sync_channel::<LspEvent>(LSP_EVENT_QUEUE_CAPACITY);
242    /// let client = LspProcessClient::new_with_server(
243    ///     "file:///tmp/project",
244    ///     tx,
245    ///     "lua-language-server",
246    /// );
247    /// assert!(client.is_ok());
248    /// ```
249    pub fn new_with_server(
250        root_uri: &str,
251        events: mpsc::SyncSender<LspEvent>,
252        server_key: &str,
253    ) -> Result<Self, String> {
254        let config = lsp_server_config(server_key)
255            .ok_or_else(|| format!("Unsupported LSP server: {}", server_key))?;
256
257        if server_key == "rust-analyzer" {
258            ensure_rust_analyzer_config();
259        }
260
261        let command = resolve_lsp_command(config)?;
262        Self::new_with_command(root_uri, events, &command, server_key)
263    }
264
265    /// Creates a new LSP client with a specific command.
266    ///
267    /// This is the internal implementation that spawns the process.
268    ///
269    /// # Errors
270    ///
271    /// Returns an error string if the process cannot be spawned or if stdio
272    /// handles cannot be acquired.
273    fn new_with_command(
274        root_uri: &str,
275        events: mpsc::SyncSender<LspEvent>,
276        command: &LspCommand,
277        server_key: &str,
278    ) -> Result<Self, String> {
279        let mut child = Command::new(&command.program)
280            .args(&command.args)
281            .stdin(Stdio::piped())
282            .stdout(Stdio::piped())
283            .stderr(Stdio::piped())
284            .spawn()
285            .map_err(|e| {
286                if e.kind() == std::io::ErrorKind::NotFound {
287                    if command.program == "rust-analyzer" {
288                        "LSP server program rust-analyzer not found. Please install rust-analyzer or set RUST_ANALYZER/RUST_ANALYZER_PATH environment variable".to_string()
289                    } else {
290                        format!("LSP server program {} not found", command.program)
291                    }
292                } else {
293                    e.to_string()
294                }
295            })?;
296
297        let stdin = child.stdin.take().ok_or("stdin unavailable")?;
298        let stdout = child.stdout.take().ok_or("stdout unavailable")?;
299        let stderr = child.stderr.take().ok_or("stderr unavailable")?;
300
301        let (tx, rx) = mpsc::channel::<Vec<u8>>();
302        let pending_requests = Arc::new(Mutex::new(HashMap::new()));
303        let pending_reader = pending_requests.clone();
304        let documents: Arc<Mutex<HashMap<String, DocumentState>>> =
305            Arc::new(Mutex::new(HashMap::new()));
306        let documents_reader = documents.clone();
307        let events_reader = events.clone();
308        let events_log = events.clone();
309        let events_field = events;
310        let server_key = server_key.to_string();
311        let server_key_reader = server_key.clone();
312        let server_key_log = server_key.clone();
313        let tx_reader = tx.clone();
314
315        let writer_thread = thread::spawn(move || {
316            let mut input = stdin;
317            for bytes in rx {
318                if input.write_all(&bytes).is_err() {
319                    break;
320                }
321                let _ = input.flush();
322            }
323        });
324
325        let reader_thread = thread::spawn(move || {
326            let mut reader = BufReader::new(stdout);
327            while let Some(buf) = read_message(&mut reader) {
328                if let Ok(value) =
329                    serde_json::from_slice::<serde_json::Value>(&buf)
330                {
331                    if let Some(id) = value.get("id").and_then(|v| v.as_u64()) {
332                        if let Some(method) =
333                            value.get("method").and_then(|m| m.as_str())
334                        {
335                            handle_server_request(id, method, &tx_reader);
336                        } else {
337                            handle_client_response(
338                                id,
339                                &value,
340                                &pending_reader,
341                                &events_reader,
342                                &documents_reader,
343                            );
344                        }
345                    } else if let Some(method) =
346                        value.get("method").and_then(|m| m.as_str())
347                        && let Some(params) = value.get("params")
348                    {
349                        handle_server_notification(
350                            method,
351                            params,
352                            &events_reader,
353                            &server_key_reader,
354                        );
355                    }
356                }
357            }
358        });
359
360        let stderr_thread = thread::spawn(move || {
361            let mut reader = BufReader::new(stderr);
362            while let Some(line) = read_log_line(&mut reader) {
363                let line = line.trim();
364                if line.is_empty() {
365                    continue;
366                }
367                emit(
368                    &events_log,
369                    LspEvent::Log {
370                        server_key: server_key_log.clone(),
371                        message: line.to_string(),
372                    },
373                );
374            }
375        });
376
377        let client = Self {
378            child,
379            writer: tx,
380            documents,
381            events: events_field,
382            server_key,
383            request_id: AtomicU64::new(1),
384            pending_requests,
385            _writer_thread: writer_thread,
386            _reader_thread: reader_thread,
387            _stderr_thread: stderr_thread,
388        };
389
390        let initialize = json!({
391            "jsonrpc": "2.0",
392            "id": client.next_id(),
393            "method": "initialize",
394            "params": {
395                "processId": std::process::id(),
396                "rootUri": root_uri,
397                "capabilities": {
398                    "textDocument": {
399                        "synchronization": {
400                            "dynamicRegistration": false,
401                            "willSave": false,
402                            "didSave": true
403                        },
404                        "formatting": {
405                            "dynamicRegistration": false
406                        }
407                    },
408                    "window": {
409                        "workDoneProgress": true
410                    }
411                },
412                "workspaceFolders": null
413            }
414        });
415        client.send_message(&initialize);
416
417        let initialized = json!({
418            "jsonrpc": "2.0",
419            "method": "initialized",
420            "params": {}
421        });
422        client.send_message(&initialized);
423
424        Ok(client)
425    }
426
427    /// Generates the next unique request ID using atomic operations.
428    fn next_id(&self) -> u64 {
429        self.request_id.fetch_add(1, Ordering::Relaxed)
430    }
431
432    /// Sends a JSON-RPC message to the LSP server.
433    ///
434    /// Formats the message with the required `Content-Length` header.
435    fn send_message(&self, value: &serde_json::Value) {
436        if let Some(bytes) = frame_message(value) {
437            let _ = self.writer.send(bytes);
438        }
439    }
440
441    /// Applies text changes to a document and converts them to JSON format.
442    ///
443    /// Also converts positions to UTF-16 as required by LSP.
444    ///
445    /// If the local document mirror desynchronizes partway through `changes`
446    /// (see [`apply_changes_to_document`]), the document is dropped from
447    /// [`Self::documents`] — so a later `did_open` reseeds it instead of
448    /// this client continuing to serve hover/completion/definition
449    /// positions computed from a copy known to be stale — and an
450    /// [`LspEvent::Log`] is emitted so the desync is diagnosable instead of
451    /// surfacing only as "the language server gives nonsense answers".
452    fn apply_change_and_convert(
453        &self,
454        uri: &str,
455        changes: &[LspTextChange],
456    ) -> Vec<serde_json::Value> {
457        let mut docs = self.documents.lock().unwrap_or_else(|e| e.into_inner());
458        let Some(state) = docs.get_mut(uri) else { return Vec::new() };
459
460        match apply_changes_to_document(state, changes) {
461            Some(out) => out,
462            None => {
463                docs.remove(uri);
464                emit(
465                    &self.events,
466                    LspEvent::Log {
467                        server_key: self.server_key.clone(),
468                        message: format!(
469                            "Local document mirror for {uri} desynchronized \
470                             (a change referenced a line outside the tracked \
471                             document); dropping it until the next open."
472                        ),
473                    },
474                );
475                Vec::new()
476            }
477        }
478    }
479}
480
481// =============================================================================
482// Reader thread helper functions
483// =============================================================================
484
485/// Sends shutdown/exit notifications and kills the process on drop.
486impl Drop for LspProcessClient {
487    fn drop(&mut self) {
488        let shutdown = json!({
489            "jsonrpc": "2.0",
490            "id": self.next_id(),
491            "method": "shutdown",
492            "params": null
493        });
494        self.send_message(&shutdown);
495
496        let exit = json!({
497            "jsonrpc": "2.0",
498            "method": "exit",
499            "params": {}
500        });
501        self.send_message(&exit);
502
503        if self.child.try_wait().ok().flatten().is_none() {
504            let _ = self.child.kill();
505        }
506    }
507}
508// =============================================================================
509// LspClient Trait Implementation
510// =============================================================================
511
512impl LspClient for LspProcessClient {
513    fn did_open(&mut self, document: &LspDocument, text: &str) {
514        let mut docs = self.documents.lock().unwrap_or_else(|e| e.into_inner());
515        docs.insert(
516            document.uri.clone(),
517            DocumentState { text: TextModel::from_text(text) },
518        );
519
520        let msg = json!({
521            "jsonrpc": "2.0",
522            "method": "textDocument/didOpen",
523            "params": {
524                "textDocument": {
525                    "uri": document.uri,
526                    "languageId": document.language_id,
527                    "version": document.version,
528                    "text": text
529                }
530            }
531        });
532        self.send_message(&msg);
533    }
534
535    fn did_change(
536        &mut self,
537        document: &LspDocument,
538        changes: &[LspTextChange],
539    ) {
540        let content_changes =
541            self.apply_change_and_convert(&document.uri, changes);
542        if content_changes.is_empty() {
543            return;
544        }
545
546        let msg = json!({
547            "jsonrpc": "2.0",
548            "method": "textDocument/didChange",
549            "params": {
550                "textDocument": {
551                    "uri": document.uri,
552                    "version": document.version
553                },
554                "contentChanges": content_changes
555            }
556        });
557        self.send_message(&msg);
558    }
559
560    fn did_save(&mut self, document: &LspDocument, text: &str) {
561        let msg = json!({
562            "jsonrpc": "2.0",
563            "method": "textDocument/didSave",
564            "params": {
565                "textDocument": { "uri": document.uri },
566                "text": text
567            }
568        });
569        self.send_message(&msg);
570    }
571
572    fn did_close(&mut self, document: &LspDocument) {
573        let mut docs = self.documents.lock().unwrap_or_else(|e| e.into_inner());
574        docs.remove(&document.uri);
575
576        let msg = json!({
577            "jsonrpc": "2.0",
578            "method": "textDocument/didClose",
579            "params": {
580                "textDocument": { "uri": document.uri }
581            }
582        });
583        self.send_message(&msg);
584    }
585
586    fn request_hover(&mut self, document: &LspDocument, position: LspPosition) {
587        let docs = self.documents.lock().unwrap_or_else(|e| e.into_inner());
588        let Some(state) = docs.get(&document.uri) else { return };
589        let pos = state.text.to_utf16_position(position);
590
591        let id = self.next_id();
592        {
593            let mut pending =
594                self.pending_requests.lock().unwrap_or_else(|e| e.into_inner());
595            evict_expired_requests(&mut pending);
596            pending.insert(
597                id,
598                PendingRequest {
599                    kind: LspRequestKind::Hover,
600                    uri: document.uri.clone(),
601                    requested_at: Instant::now(),
602                },
603            );
604        }
605
606        let msg = json!({
607            "jsonrpc": "2.0",
608            "id": id,
609            "method": "textDocument/hover",
610            "params": {
611                "textDocument": { "uri": document.uri },
612                "position": { "line": pos.line, "character": pos.character }
613            }
614        });
615        self.send_message(&msg);
616    }
617
618    fn request_completion(
619        &mut self,
620        document: &LspDocument,
621        position: LspPosition,
622    ) {
623        let docs = self.documents.lock().unwrap_or_else(|e| e.into_inner());
624        let Some(state) = docs.get(&document.uri) else { return };
625        let pos = state.text.to_utf16_position(position);
626
627        let id = self.next_id();
628        {
629            let mut pending =
630                self.pending_requests.lock().unwrap_or_else(|e| e.into_inner());
631            evict_expired_requests(&mut pending);
632            pending.insert(
633                id,
634                PendingRequest {
635                    kind: LspRequestKind::Completion,
636                    uri: document.uri.clone(),
637                    requested_at: Instant::now(),
638                },
639            );
640        }
641
642        let msg = json!({
643            "jsonrpc": "2.0",
644            "id": id,
645            "method": "textDocument/completion",
646            "params": {
647                "textDocument": { "uri": document.uri },
648                "position": { "line": pos.line, "character": pos.character },
649                "context": { "triggerKind": 1 }
650            }
651        });
652        self.send_message(&msg);
653    }
654
655    fn request_definition(
656        &mut self,
657        document: &LspDocument,
658        position: LspPosition,
659    ) {
660        let docs = self.documents.lock().unwrap_or_else(|e| e.into_inner());
661        let Some(state) = docs.get(&document.uri) else { return };
662        let pos = state.text.to_utf16_position(position);
663
664        let id = self.next_id();
665        {
666            let mut pending =
667                self.pending_requests.lock().unwrap_or_else(|e| e.into_inner());
668            evict_expired_requests(&mut pending);
669            pending.insert(
670                id,
671                PendingRequest {
672                    kind: LspRequestKind::Definition,
673                    uri: document.uri.clone(),
674                    requested_at: Instant::now(),
675                },
676            );
677        }
678
679        let msg = json!({
680            "jsonrpc": "2.0",
681            "id": id,
682            "method": "textDocument/definition",
683            "params": {
684                "textDocument": { "uri": document.uri },
685                "position": { "line": pos.line, "character": pos.character }
686            }
687        });
688        self.send_message(&msg);
689    }
690
691    fn request_formatting(
692        &mut self,
693        document: &LspDocument,
694        options: LspFormattingOptions,
695    ) {
696        // Unlike the position-based requests this one needs nothing from the
697        // mirror to be *sent* — but the reply's edits can only be placed
698        // against it, so a document the client never opened is not worth
699        // asking about.
700        {
701            let docs = self.documents.lock().unwrap_or_else(|e| e.into_inner());
702            if !docs.contains_key(&document.uri) {
703                return;
704            }
705        }
706
707        let id = self.next_id();
708        {
709            let mut pending =
710                self.pending_requests.lock().unwrap_or_else(|e| e.into_inner());
711            evict_expired_requests(&mut pending);
712            pending.insert(
713                id,
714                PendingRequest {
715                    kind: LspRequestKind::Formatting,
716                    uri: document.uri.clone(),
717                    requested_at: Instant::now(),
718                },
719            );
720        }
721
722        let msg = json!({
723            "jsonrpc": "2.0",
724            "id": id,
725            "method": "textDocument/formatting",
726            "params": {
727                "textDocument": { "uri": document.uri },
728                "options": {
729                    "tabSize": options.tab_size,
730                    "insertSpaces": options.insert_spaces
731                }
732            }
733        });
734        self.send_message(&msg);
735    }
736}
737
738// =============================================================================
739// Tests
740// =============================================================================
741
742#[cfg(test)]
743mod tests {
744    // Several helpers and tests below carry an `#[allow]` for `expect_used`,
745    // `unwrap_used`, or `panic`. In test code a panic *is* the failure
746    // report, so these mirror the existing per-test allows in `protocol.rs`.
747    use super::*;
748    use crate::canvas_editor::lsp::{LspPosition, LspRange, LspTextChange};
749
750    /// Builds an `LspProcessClient` without a real LSP server: `child` still
751    /// needs a genuine `Child`, so a process that exits immediately stands in
752    /// for it, and the writer/reader/stderr threads are no-ops since these
753    /// tests exercise the client's own methods directly rather than the wire
754    /// protocol those background threads drive.
755    #[allow(clippy::expect_used)]
756    fn test_client()
757    -> (LspProcessClient, mpsc::Receiver<Vec<u8>>, mpsc::Receiver<LspEvent>)
758    {
759        let child = Command::new("true").spawn().expect("spawn stub process");
760        let (writer_tx, writer_rx) = mpsc::channel::<Vec<u8>>();
761        let (events_tx, events_rx) = mpsc::sync_channel::<LspEvent>(16);
762        let client = LspProcessClient {
763            child,
764            writer: writer_tx,
765            documents: Arc::new(Mutex::new(HashMap::new())),
766            events: events_tx,
767            server_key: "test-server".to_string(),
768            request_id: AtomicU64::new(1),
769            pending_requests: Arc::new(Mutex::new(HashMap::new())),
770            _writer_thread: thread::spawn(|| {}),
771            _reader_thread: thread::spawn(|| {}),
772            _stderr_thread: thread::spawn(|| {}),
773        };
774        (client, writer_rx, events_rx)
775    }
776
777    /// Returns the JSON body of a `Content-Length`-framed message taken from
778    /// the writer channel.
779    #[allow(clippy::expect_used)]
780    fn decode_sent(data: &[u8]) -> serde_json::Value {
781        let header_end = data
782            .windows(4)
783            .position(|w| w == b"\r\n\r\n")
784            .expect("missing header separator");
785        let body = &data[header_end + 4..];
786        serde_json::from_slice(body).expect("invalid JSON body")
787    }
788
789    fn document(uri: &str) -> LspDocument {
790        LspDocument {
791            uri: uri.to_string(),
792            language_id: "rust".to_string(),
793            version: 1,
794        }
795    }
796
797    fn range(sl: u32, sc: u32, el: u32, ec: u32) -> LspRange {
798        LspRange {
799            start: LspPosition { line: sl, character: sc },
800            end: LspPosition { line: el, character: ec },
801        }
802    }
803
804    // -------------------------------------------------------------------------
805    // next_id / send_message
806    // -------------------------------------------------------------------------
807
808    #[test]
809    fn test_emit_drops_events_once_the_queue_is_full() {
810        // The point of the bound: past capacity the queue stops growing. Note
811        // that a blocking `send` here would not fail this test, it would hang
812        // it -- there is no receiver draining, which is exactly the situation
813        // `emit` must never wait on, since the sender is the reader thread
814        // feeding on the server's stdout.
815        let (tx, rx) = mpsc::sync_channel::<LspEvent>(2);
816
817        for index in 0..5 {
818            emit(&tx, LspEvent::Hover { text: index.to_string() });
819        }
820
821        let queued: Vec<String> = std::iter::from_fn(|| rx.try_recv().ok())
822            .map(|event| match event {
823                LspEvent::Hover { text } => text,
824                _ => String::new(),
825            })
826            .collect();
827
828        assert_eq!(
829            queued,
830            ["0", "1"],
831            "the queue keeps what fits and drops the rest"
832        );
833    }
834
835    #[test]
836    fn test_emit_accepts_events_again_once_the_queue_drains() {
837        // Dropping is not a latch: a host that catches up starts receiving
838        // again, so a burst costs the events in it and nothing after.
839        let (tx, rx) = mpsc::sync_channel::<LspEvent>(1);
840        emit(&tx, LspEvent::Hover { text: "dropped-into".to_string() });
841        emit(&tx, LspEvent::Hover { text: "dropped".to_string() });
842
843        let _ = rx.try_recv();
844        emit(&tx, LspEvent::Hover { text: "accepted".to_string() });
845
846        let accepted = rx.try_recv().ok().and_then(|event| match event {
847            LspEvent::Hover { text } => Some(text),
848            _ => None,
849        });
850
851        assert_eq!(
852            accepted.as_deref(),
853            Some("accepted"),
854            "the drained queue must accept a new event"
855        );
856    }
857
858    #[test]
859    fn test_next_id_increments() {
860        let (client, _writer_rx, _events_rx) = test_client();
861        assert_eq!(client.next_id(), 1);
862        assert_eq!(client.next_id(), 2);
863        assert_eq!(client.next_id(), 3);
864    }
865
866    #[test]
867    #[allow(clippy::expect_used)]
868    fn test_send_message_frames_and_forwards() {
869        let (client, writer_rx, _events_rx) = test_client();
870        client.send_message(&json!({"jsonrpc": "2.0", "method": "ping"}));
871
872        let bytes = writer_rx.try_recv().expect("message forwarded to writer");
873        assert_eq!(decode_sent(&bytes)["method"], "ping");
874    }
875
876    // -------------------------------------------------------------------------
877    // did_open / did_change / did_save / did_close
878    // -------------------------------------------------------------------------
879
880    #[test]
881    #[allow(clippy::expect_used, clippy::unwrap_used)]
882    fn test_did_open_registers_document_and_notifies_server() {
883        let (mut client, writer_rx, _events_rx) = test_client();
884        let doc = document("file:///a.rs");
885
886        client.did_open(&doc, "fn main() {}");
887
888        assert!(client.documents.lock().unwrap().contains_key("file:///a.rs"));
889        let bytes = writer_rx.try_recv().expect("didOpen sent");
890        let value = decode_sent(&bytes);
891        assert_eq!(value["method"], "textDocument/didOpen");
892        assert_eq!(value["params"]["textDocument"]["text"], "fn main() {}");
893    }
894
895    #[test]
896    #[allow(clippy::expect_used)]
897    fn test_did_change_converts_and_sends_content_changes() {
898        let (mut client, writer_rx, _events_rx) = test_client();
899        let doc = document("file:///a.rs");
900        client.did_open(&doc, "hello");
901        writer_rx.try_recv().expect("drain didOpen");
902
903        let changes = vec![LspTextChange {
904            range: range(0, 0, 0, 5),
905            text: "hi".to_string(),
906        }];
907        client.did_change(&doc, &changes);
908
909        let bytes = writer_rx.try_recv().expect("didChange sent");
910        let value = decode_sent(&bytes);
911        assert_eq!(value["method"], "textDocument/didChange");
912        assert_eq!(value["params"]["contentChanges"][0]["text"], "hi");
913    }
914
915    #[test]
916    #[allow(clippy::assertions_on_result_states)]
917    fn test_did_change_without_open_document_sends_nothing() {
918        let (mut client, writer_rx, _events_rx) = test_client();
919        let doc = document("file:///missing.rs");
920        let changes = vec![LspTextChange {
921            range: range(0, 0, 0, 0),
922            text: "x".to_string(),
923        }];
924
925        client.did_change(&doc, &changes);
926
927        assert!(writer_rx.try_recv().is_err());
928    }
929
930    #[test]
931    #[allow(
932        clippy::expect_used,
933        clippy::unwrap_used,
934        clippy::panic,
935        clippy::assertions_on_result_states
936    )]
937    fn test_did_change_desync_drops_document_and_logs() {
938        let (mut client, writer_rx, events_rx) = test_client();
939        let doc = document("file:///a.rs");
940        client.did_open(&doc, "hello");
941        writer_rx.try_recv().expect("drain didOpen");
942
943        // Line 5 doesn't exist in a single-line document, forcing a desync.
944        let changes = vec![LspTextChange {
945            range: range(5, 0, 5, 0),
946            text: "x".to_string(),
947        }];
948        client.did_change(&doc, &changes);
949
950        assert!(writer_rx.try_recv().is_err(), "no didChange after desync");
951        assert!(!client.documents.lock().unwrap().contains_key("file:///a.rs"));
952
953        match events_rx.try_recv().expect("desync logged") {
954            LspEvent::Log { message, .. } => {
955                assert!(message.contains("desynchronized"));
956            }
957            _ => panic!("expected LspEvent::Log"),
958        }
959    }
960
961    #[test]
962    #[allow(clippy::expect_used)]
963    fn test_did_save_sends_notification() {
964        let (mut client, writer_rx, _events_rx) = test_client();
965        let doc = document("file:///a.rs");
966
967        client.did_save(&doc, "fn main() {}");
968
969        let bytes = writer_rx.try_recv().expect("didSave sent");
970        let value = decode_sent(&bytes);
971        assert_eq!(value["method"], "textDocument/didSave");
972        assert_eq!(value["params"]["text"], "fn main() {}");
973    }
974
975    #[test]
976    #[allow(clippy::expect_used, clippy::unwrap_used)]
977    fn test_did_close_removes_document_and_notifies_server() {
978        let (mut client, writer_rx, _events_rx) = test_client();
979        let doc = document("file:///a.rs");
980        client.did_open(&doc, "hello");
981        writer_rx.try_recv().expect("drain didOpen");
982
983        client.did_close(&doc);
984
985        assert!(!client.documents.lock().unwrap().contains_key("file:///a.rs"));
986        let bytes = writer_rx.try_recv().expect("didClose sent");
987        assert_eq!(decode_sent(&bytes)["method"], "textDocument/didClose");
988    }
989
990    // -------------------------------------------------------------------------
991    // request_hover / request_completion / request_definition
992    // -------------------------------------------------------------------------
993
994    #[test]
995    #[allow(clippy::expect_used, clippy::unwrap_used, clippy::panic)]
996    fn test_request_hover_registers_pending_and_sends_request() {
997        let (mut client, writer_rx, _events_rx) = test_client();
998        let doc = document("file:///a.rs");
999        client.did_open(&doc, "hello");
1000        writer_rx.try_recv().expect("drain didOpen");
1001
1002        client.request_hover(&doc, LspPosition { line: 0, character: 2 });
1003
1004        let bytes = writer_rx.try_recv().expect("hover request sent");
1005        let value = decode_sent(&bytes);
1006        assert_eq!(value["method"], "textDocument/hover");
1007        let id = value["id"].as_u64().expect("id present");
1008
1009        let pending = client.pending_requests.lock().unwrap();
1010        match pending.get(&id).map(|p| &p.kind) {
1011            Some(LspRequestKind::Hover) => {}
1012            _ => panic!("expected a pending Hover request"),
1013        }
1014    }
1015
1016    #[test]
1017    #[allow(clippy::unwrap_used, clippy::assertions_on_result_states)]
1018    fn test_request_hover_without_open_document_does_nothing() {
1019        let (mut client, writer_rx, _events_rx) = test_client();
1020        let doc = document("file:///missing.rs");
1021
1022        client.request_hover(&doc, LspPosition { line: 0, character: 0 });
1023
1024        assert!(writer_rx.try_recv().is_err());
1025        assert!(client.pending_requests.lock().unwrap().is_empty());
1026    }
1027
1028    #[test]
1029    #[allow(clippy::expect_used, clippy::unwrap_used, clippy::panic)]
1030    fn test_request_completion_registers_pending_and_sends_request() {
1031        let (mut client, writer_rx, _events_rx) = test_client();
1032        let doc = document("file:///a.rs");
1033        client.did_open(&doc, "hello");
1034        writer_rx.try_recv().expect("drain didOpen");
1035
1036        client.request_completion(&doc, LspPosition { line: 0, character: 2 });
1037
1038        let bytes = writer_rx.try_recv().expect("completion request sent");
1039        let value = decode_sent(&bytes);
1040        assert_eq!(value["method"], "textDocument/completion");
1041        let id = value["id"].as_u64().expect("id present");
1042
1043        let pending = client.pending_requests.lock().unwrap();
1044        match pending.get(&id).map(|p| &p.kind) {
1045            Some(LspRequestKind::Completion) => {}
1046            _ => panic!("expected a pending Completion request"),
1047        }
1048    }
1049
1050    #[test]
1051    #[allow(clippy::expect_used, clippy::unwrap_used, clippy::panic)]
1052    fn test_request_definition_registers_pending_and_sends_request() {
1053        let (mut client, writer_rx, _events_rx) = test_client();
1054        let doc = document("file:///a.rs");
1055        client.did_open(&doc, "hello");
1056        writer_rx.try_recv().expect("drain didOpen");
1057
1058        client.request_definition(&doc, LspPosition { line: 0, character: 2 });
1059
1060        let bytes = writer_rx.try_recv().expect("definition request sent");
1061        let value = decode_sent(&bytes);
1062        assert_eq!(value["method"], "textDocument/definition");
1063        let id = value["id"].as_u64().expect("id present");
1064
1065        let pending = client.pending_requests.lock().unwrap();
1066        match pending.get(&id).map(|p| &p.kind) {
1067            Some(LspRequestKind::Definition) => {}
1068            _ => panic!("expected a pending Definition request"),
1069        }
1070    }
1071
1072    #[test]
1073    #[allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)]
1074    fn test_request_formatting_registers_pending_and_sends_options() {
1075        let (mut client, writer_rx, _events_rx) = test_client();
1076        let doc = document("file:///a.rs");
1077        client.did_open(&doc, "hello");
1078        writer_rx.try_recv().expect("drain didOpen");
1079
1080        client.request_formatting(
1081            &doc,
1082            LspFormattingOptions { tab_size: 2, insert_spaces: true },
1083        );
1084
1085        let bytes = writer_rx.try_recv().expect("formatting request sent");
1086        let value = decode_sent(&bytes);
1087        assert_eq!(value["method"], "textDocument/formatting");
1088        assert_eq!(value["params"]["textDocument"]["uri"], "file:///a.rs");
1089        assert_eq!(value["params"]["options"]["tabSize"], 2);
1090        assert_eq!(value["params"]["options"]["insertSpaces"], true);
1091
1092        let id = value["id"].as_u64().expect("id present");
1093        let pending = client.pending_requests.lock().unwrap();
1094        let entry = pending.get(&id).expect("a pending request");
1095        assert!(matches!(entry.kind, LspRequestKind::Formatting));
1096        // The reply's edits are placed against this document's mirror.
1097        assert_eq!(entry.uri, "file:///a.rs");
1098    }
1099
1100    #[test]
1101    #[allow(clippy::expect_used, clippy::unwrap_used)]
1102    fn test_request_formatting_skips_a_document_that_was_never_opened() {
1103        let (mut client, writer_rx, _events_rx) = test_client();
1104
1105        client.request_formatting(
1106            &document("file:///never-opened.rs"),
1107            LspFormattingOptions { tab_size: 4, insert_spaces: true },
1108        );
1109
1110        assert!(writer_rx.try_recv().is_err(), "nothing should be sent");
1111        assert!(client.pending_requests.lock().unwrap().is_empty());
1112    }
1113
1114    // -------------------------------------------------------------------------
1115    // Drop
1116    // -------------------------------------------------------------------------
1117
1118    #[test]
1119    #[allow(clippy::expect_used)]
1120    fn test_drop_sends_shutdown_then_exit() {
1121        let (client, writer_rx, _events_rx) = test_client();
1122        drop(client);
1123
1124        let shutdown = writer_rx.try_recv().expect("shutdown sent");
1125        assert_eq!(decode_sent(&shutdown)["method"], "shutdown");
1126
1127        let exit = writer_rx.try_recv().expect("exit sent");
1128        assert_eq!(decode_sent(&exit)["method"], "exit");
1129    }
1130}