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