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