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