lsp.rs

  1use log::warn;
  2pub use lsp_types::request::*;
  3pub use lsp_types::*;
  4
  5use anyhow::{anyhow, Context, Result};
  6use collections::HashMap;
  7use futures::{channel::oneshot, io::BufWriter, AsyncRead, AsyncWrite};
  8use gpui::{executor, AsyncAppContext, Task};
  9use parking_lot::Mutex;
 10use postage::{barrier, prelude::Stream};
 11use serde::{de::DeserializeOwned, Deserialize, Serialize};
 12use serde_json::{json, value::RawValue, Value};
 13use smol::{
 14    channel,
 15    io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader},
 16    process::{self, Child},
 17};
 18use std::{
 19    future::Future,
 20    io::Write,
 21    path::PathBuf,
 22    str::FromStr,
 23    sync::{
 24        atomic::{AtomicUsize, Ordering::SeqCst},
 25        Arc,
 26    },
 27};
 28use std::{path::Path, process::Stdio};
 29use util::{ResultExt, TryFutureExt};
 30
 31const JSON_RPC_VERSION: &str = "2.0";
 32const CONTENT_LEN_HEADER: &str = "Content-Length: ";
 33
 34type NotificationHandler = Box<dyn Send + FnMut(Option<usize>, &str, AsyncAppContext)>;
 35type ResponseHandler = Box<dyn Send + FnOnce(Result<&str, Error>)>;
 36
 37pub struct LanguageServer {
 38    server_id: usize,
 39    next_id: AtomicUsize,
 40    outbound_tx: channel::Sender<Vec<u8>>,
 41    name: String,
 42    capabilities: ServerCapabilities,
 43    code_action_kinds: Option<Vec<CodeActionKind>>,
 44    notification_handlers: Arc<Mutex<HashMap<&'static str, NotificationHandler>>>,
 45    response_handlers: Arc<Mutex<Option<HashMap<usize, ResponseHandler>>>>,
 46    executor: Arc<executor::Background>,
 47    #[allow(clippy::type_complexity)]
 48    io_tasks: Mutex<Option<(Task<Option<()>>, Task<Option<()>>)>>,
 49    output_done_rx: Mutex<Option<barrier::Receiver>>,
 50    root_path: PathBuf,
 51    _server: Option<Child>,
 52}
 53
 54pub struct Subscription {
 55    method: &'static str,
 56    notification_handlers: Arc<Mutex<HashMap<&'static str, NotificationHandler>>>,
 57}
 58
 59#[derive(Serialize, Deserialize)]
 60struct Request<'a, T> {
 61    jsonrpc: &'static str,
 62    id: usize,
 63    method: &'a str,
 64    params: T,
 65}
 66
 67#[derive(Serialize, Deserialize)]
 68struct AnyResponse<'a> {
 69    jsonrpc: &'a str,
 70    id: usize,
 71    #[serde(default)]
 72    error: Option<Error>,
 73    #[serde(borrow)]
 74    result: Option<&'a RawValue>,
 75}
 76
 77#[derive(Serialize)]
 78struct Response<T> {
 79    jsonrpc: &'static str,
 80    id: usize,
 81    result: Option<T>,
 82    error: Option<Error>,
 83}
 84
 85#[derive(Serialize, Deserialize)]
 86struct Notification<'a, T> {
 87    jsonrpc: &'static str,
 88    #[serde(borrow)]
 89    method: &'a str,
 90    params: T,
 91}
 92
 93#[derive(Deserialize)]
 94struct AnyNotification<'a> {
 95    #[serde(default)]
 96    id: Option<usize>,
 97    #[serde(borrow)]
 98    method: &'a str,
 99    #[serde(borrow)]
100    params: &'a RawValue,
101}
102
103#[derive(Debug, Serialize, Deserialize)]
104struct Error {
105    message: String,
106}
107
108impl LanguageServer {
109    pub fn new<T: AsRef<std::ffi::OsStr>>(
110        server_id: usize,
111        binary_path: &Path,
112        arguments: &[T],
113        root_path: &Path,
114        code_action_kinds: Option<Vec<CodeActionKind>>,
115        cx: AsyncAppContext,
116    ) -> Result<Self> {
117        let working_dir = if root_path.is_dir() {
118            root_path
119        } else {
120            root_path.parent().unwrap_or_else(|| Path::new("/"))
121        };
122
123        let mut server = process::Command::new(binary_path)
124            .current_dir(working_dir)
125            .args(arguments)
126            .stdin(Stdio::piped())
127            .stdout(Stdio::piped())
128            .stderr(Stdio::inherit())
129            .kill_on_drop(true)
130            .spawn()?;
131
132        let stdin = server.stdin.take().unwrap();
133        let stout = server.stdout.take().unwrap();
134        let mut server = Self::new_internal(
135            server_id,
136            stdin,
137            stout,
138            Some(server),
139            root_path,
140            code_action_kinds,
141            cx,
142            |notification| {
143                log::info!(
144                    "unhandled notification {}:\n{}",
145                    notification.method,
146                    serde_json::to_string_pretty(
147                        &Value::from_str(notification.params.get()).unwrap()
148                    )
149                    .unwrap()
150                );
151            },
152        );
153
154        if let Some(name) = binary_path.file_name() {
155            server.name = name.to_string_lossy().to_string();
156        }
157        Ok(server)
158    }
159
160    fn new_internal<Stdin, Stdout, F>(
161        server_id: usize,
162        stdin: Stdin,
163        stdout: Stdout,
164        server: Option<Child>,
165        root_path: &Path,
166        code_action_kinds: Option<Vec<CodeActionKind>>,
167        cx: AsyncAppContext,
168        on_unhandled_notification: F,
169    ) -> Self
170    where
171        Stdin: AsyncWrite + Unpin + Send + 'static,
172        Stdout: AsyncRead + Unpin + Send + 'static,
173        F: FnMut(AnyNotification) + 'static + Send,
174    {
175        let (outbound_tx, outbound_rx) = channel::unbounded::<Vec<u8>>();
176        let notification_handlers =
177            Arc::new(Mutex::new(HashMap::<_, NotificationHandler>::default()));
178        let response_handlers =
179            Arc::new(Mutex::new(Some(HashMap::<_, ResponseHandler>::default())));
180        let input_task = cx.spawn(|cx| {
181            let notification_handlers = notification_handlers.clone();
182            let response_handlers = response_handlers.clone();
183            Self::handle_input(
184                stdout,
185                on_unhandled_notification,
186                notification_handlers,
187                response_handlers,
188                cx,
189            )
190            .log_err()
191        });
192        let (output_done_tx, output_done_rx) = barrier::channel();
193        let output_task = cx.background().spawn({
194            let response_handlers = response_handlers.clone();
195            Self::handle_output(stdin, outbound_rx, output_done_tx, response_handlers).log_err()
196        });
197
198        Self {
199            server_id,
200            notification_handlers,
201            response_handlers,
202            name: Default::default(),
203            capabilities: Default::default(),
204            code_action_kinds,
205            next_id: Default::default(),
206            outbound_tx,
207            executor: cx.background(),
208            io_tasks: Mutex::new(Some((input_task, output_task))),
209            output_done_rx: Mutex::new(Some(output_done_rx)),
210            root_path: root_path.to_path_buf(),
211            _server: server,
212        }
213    }
214
215    pub fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
216        self.code_action_kinds.clone()
217    }
218
219    async fn handle_input<Stdout, F>(
220        stdout: Stdout,
221        mut on_unhandled_notification: F,
222        notification_handlers: Arc<Mutex<HashMap<&'static str, NotificationHandler>>>,
223        response_handlers: Arc<Mutex<Option<HashMap<usize, ResponseHandler>>>>,
224        cx: AsyncAppContext,
225    ) -> anyhow::Result<()>
226    where
227        Stdout: AsyncRead + Unpin + Send + 'static,
228        F: FnMut(AnyNotification) + 'static + Send,
229    {
230        let mut stdout = BufReader::new(stdout);
231        let _clear_response_handlers = util::defer({
232            let response_handlers = response_handlers.clone();
233            move || {
234                response_handlers.lock().take();
235            }
236        });
237        let mut buffer = Vec::new();
238        loop {
239            buffer.clear();
240            stdout.read_until(b'\n', &mut buffer).await?;
241            stdout.read_until(b'\n', &mut buffer).await?;
242            let message_len: usize = std::str::from_utf8(&buffer)?
243                .strip_prefix(CONTENT_LEN_HEADER)
244                .ok_or_else(|| anyhow!("invalid header"))?
245                .trim_end()
246                .parse()?;
247
248            buffer.resize(message_len, 0);
249            stdout.read_exact(&mut buffer).await?;
250            log::trace!("incoming message:{}", String::from_utf8_lossy(&buffer));
251
252            if let Ok(msg) = serde_json::from_slice::<AnyNotification>(&buffer) {
253                if let Some(handler) = notification_handlers.lock().get_mut(msg.method) {
254                    handler(msg.id, msg.params.get(), cx.clone());
255                } else {
256                    on_unhandled_notification(msg);
257                }
258            } else if let Ok(AnyResponse {
259                id, error, result, ..
260            }) = serde_json::from_slice(&buffer)
261            {
262                if let Some(handler) = response_handlers
263                    .lock()
264                    .as_mut()
265                    .and_then(|handlers| handlers.remove(&id))
266                {
267                    if let Some(error) = error {
268                        handler(Err(error));
269                    } else if let Some(result) = result {
270                        handler(Ok(result.get()));
271                    } else {
272                        handler(Ok("null"));
273                    }
274                }
275            } else {
276                warn!(
277                    "Failed to deserialize message:\n{}",
278                    std::str::from_utf8(&buffer)?
279                );
280            }
281
282            // Don't starve the main thread when receiving lots of messages at once.
283            smol::future::yield_now().await;
284        }
285    }
286
287    async fn handle_output<Stdin>(
288        stdin: Stdin,
289        outbound_rx: channel::Receiver<Vec<u8>>,
290        output_done_tx: barrier::Sender,
291        response_handlers: Arc<Mutex<Option<HashMap<usize, ResponseHandler>>>>,
292    ) -> anyhow::Result<()>
293    where
294        Stdin: AsyncWrite + Unpin + Send + 'static,
295    {
296        let mut stdin = BufWriter::new(stdin);
297        let _clear_response_handlers = util::defer({
298            let response_handlers = response_handlers.clone();
299            move || {
300                response_handlers.lock().take();
301            }
302        });
303        let mut content_len_buffer = Vec::new();
304        while let Ok(message) = outbound_rx.recv().await {
305            log::trace!("outgoing message:{}", String::from_utf8_lossy(&message));
306            content_len_buffer.clear();
307            write!(content_len_buffer, "{}", message.len()).unwrap();
308            stdin.write_all(CONTENT_LEN_HEADER.as_bytes()).await?;
309            stdin.write_all(&content_len_buffer).await?;
310            stdin.write_all("\r\n\r\n".as_bytes()).await?;
311            stdin.write_all(&message).await?;
312            stdin.flush().await?;
313        }
314        drop(output_done_tx);
315        Ok(())
316    }
317
318    /// Initializes a language server.
319    /// Note that `options` is used directly to construct [`InitializeParams`],
320    /// which is why it is owned.
321    pub async fn initialize(mut self, options: Option<Value>) -> Result<Arc<Self>> {
322        let root_uri = Url::from_file_path(&self.root_path).unwrap();
323        #[allow(deprecated)]
324        let params = InitializeParams {
325            process_id: Default::default(),
326            root_path: Default::default(),
327            root_uri: Some(root_uri.clone()),
328            initialization_options: options,
329            capabilities: ClientCapabilities {
330                workspace: Some(WorkspaceClientCapabilities {
331                    configuration: Some(true),
332                    did_change_watched_files: Some(DynamicRegistrationClientCapabilities {
333                        dynamic_registration: Some(true),
334                    }),
335                    did_change_configuration: Some(DynamicRegistrationClientCapabilities {
336                        dynamic_registration: Some(true),
337                    }),
338                    workspace_folders: Some(true),
339                    ..Default::default()
340                }),
341                text_document: Some(TextDocumentClientCapabilities {
342                    definition: Some(GotoCapability {
343                        link_support: Some(true),
344                        ..Default::default()
345                    }),
346                    code_action: Some(CodeActionClientCapabilities {
347                        code_action_literal_support: Some(CodeActionLiteralSupport {
348                            code_action_kind: CodeActionKindLiteralSupport {
349                                value_set: vec![
350                                    CodeActionKind::REFACTOR.as_str().into(),
351                                    CodeActionKind::QUICKFIX.as_str().into(),
352                                    CodeActionKind::SOURCE.as_str().into(),
353                                ],
354                            },
355                        }),
356                        data_support: Some(true),
357                        resolve_support: Some(CodeActionCapabilityResolveSupport {
358                            properties: vec!["edit".to_string(), "command".to_string()],
359                        }),
360                        ..Default::default()
361                    }),
362                    completion: Some(CompletionClientCapabilities {
363                        completion_item: Some(CompletionItemCapability {
364                            snippet_support: Some(true),
365                            resolve_support: Some(CompletionItemCapabilityResolveSupport {
366                                properties: vec!["additionalTextEdits".to_string()],
367                            }),
368                            ..Default::default()
369                        }),
370                        ..Default::default()
371                    }),
372                    rename: Some(RenameClientCapabilities {
373                        prepare_support: Some(true),
374                        ..Default::default()
375                    }),
376                    hover: Some(HoverClientCapabilities {
377                        content_format: Some(vec![MarkupKind::Markdown]),
378                        ..Default::default()
379                    }),
380                    ..Default::default()
381                }),
382                experimental: Some(json!({
383                    "serverStatusNotification": true,
384                })),
385                window: Some(WindowClientCapabilities {
386                    work_done_progress: Some(true),
387                    ..Default::default()
388                }),
389                ..Default::default()
390            },
391            trace: Default::default(),
392            workspace_folders: Some(vec![WorkspaceFolder {
393                uri: root_uri,
394                name: Default::default(),
395            }]),
396            client_info: Default::default(),
397            locale: Default::default(),
398        };
399
400        let response = self.request::<request::Initialize>(params).await?;
401        if let Some(info) = response.server_info {
402            self.name = info.name;
403        }
404        self.capabilities = response.capabilities;
405
406        self.notify::<notification::Initialized>(InitializedParams {})?;
407        Ok(Arc::new(self))
408    }
409
410    pub fn shutdown(&self) -> Option<impl 'static + Send + Future<Output = Option<()>>> {
411        if let Some(tasks) = self.io_tasks.lock().take() {
412            let response_handlers = self.response_handlers.clone();
413            let next_id = AtomicUsize::new(self.next_id.load(SeqCst));
414            let outbound_tx = self.outbound_tx.clone();
415            let mut output_done = self.output_done_rx.lock().take().unwrap();
416            let shutdown_request = Self::request_internal::<request::Shutdown>(
417                &next_id,
418                &response_handlers,
419                &outbound_tx,
420                (),
421            );
422            let exit = Self::notify_internal::<notification::Exit>(&outbound_tx, ());
423            outbound_tx.close();
424            Some(
425                async move {
426                    log::debug!("language server shutdown started");
427                    shutdown_request.await?;
428                    response_handlers.lock().take();
429                    exit?;
430                    output_done.recv().await;
431                    log::debug!("language server shutdown finished");
432                    drop(tasks);
433                    anyhow::Ok(())
434                }
435                .log_err(),
436            )
437        } else {
438            None
439        }
440    }
441
442    #[must_use]
443    pub fn on_notification<T, F>(&self, f: F) -> Subscription
444    where
445        T: notification::Notification,
446        F: 'static + Send + FnMut(T::Params, AsyncAppContext),
447    {
448        self.on_custom_notification(T::METHOD, f)
449    }
450
451    #[must_use]
452    pub fn on_request<T, F, Fut>(&self, f: F) -> Subscription
453    where
454        T: request::Request,
455        T::Params: 'static + Send,
456        F: 'static + Send + FnMut(T::Params, AsyncAppContext) -> Fut,
457        Fut: 'static + Future<Output = Result<T::Result>>,
458    {
459        self.on_custom_request(T::METHOD, f)
460    }
461
462    pub fn remove_request_handler<T: request::Request>(&self) {
463        self.notification_handlers.lock().remove(T::METHOD);
464    }
465
466    pub fn remove_notification_handler<T: notification::Notification>(&self) {
467        self.notification_handlers.lock().remove(T::METHOD);
468    }
469
470    #[must_use]
471    pub fn on_custom_notification<Params, F>(&self, method: &'static str, mut f: F) -> Subscription
472    where
473        F: 'static + Send + FnMut(Params, AsyncAppContext),
474        Params: DeserializeOwned,
475    {
476        let prev_handler = self.notification_handlers.lock().insert(
477            method,
478            Box::new(move |_, params, cx| {
479                if let Some(params) = serde_json::from_str(params).log_err() {
480                    f(params, cx);
481                }
482            }),
483        );
484        assert!(
485            prev_handler.is_none(),
486            "registered multiple handlers for the same LSP method"
487        );
488        Subscription {
489            method,
490            notification_handlers: self.notification_handlers.clone(),
491        }
492    }
493
494    #[must_use]
495    pub fn on_custom_request<Params, Res, Fut, F>(
496        &self,
497        method: &'static str,
498        mut f: F,
499    ) -> Subscription
500    where
501        F: 'static + Send + FnMut(Params, AsyncAppContext) -> Fut,
502        Fut: 'static + Future<Output = Result<Res>>,
503        Params: DeserializeOwned + Send + 'static,
504        Res: Serialize,
505    {
506        let outbound_tx = self.outbound_tx.clone();
507        let prev_handler = self.notification_handlers.lock().insert(
508            method,
509            Box::new(move |id, params, cx| {
510                if let Some(id) = id {
511                    match serde_json::from_str(params) {
512                        Ok(params) => {
513                            let response = f(params, cx.clone());
514                            cx.foreground()
515                                .spawn({
516                                    let outbound_tx = outbound_tx.clone();
517                                    async move {
518                                        let response = match response.await {
519                                            Ok(result) => Response {
520                                                jsonrpc: JSON_RPC_VERSION,
521                                                id,
522                                                result: Some(result),
523                                                error: None,
524                                            },
525                                            Err(error) => Response {
526                                                jsonrpc: JSON_RPC_VERSION,
527                                                id,
528                                                result: None,
529                                                error: Some(Error {
530                                                    message: error.to_string(),
531                                                }),
532                                            },
533                                        };
534                                        if let Some(response) =
535                                            serde_json::to_vec(&response).log_err()
536                                        {
537                                            outbound_tx.try_send(response).ok();
538                                        }
539                                    }
540                                })
541                                .detach();
542                        }
543                        Err(error) => {
544                            log::error!(
545                                "error deserializing {} request: {:?}, message: {:?}",
546                                method,
547                                error,
548                                params
549                            );
550                            let response = AnyResponse {
551                                jsonrpc: JSON_RPC_VERSION,
552                                id,
553                                result: None,
554                                error: Some(Error {
555                                    message: error.to_string(),
556                                }),
557                            };
558                            if let Some(response) = serde_json::to_vec(&response).log_err() {
559                                outbound_tx.try_send(response).ok();
560                            }
561                        }
562                    }
563                }
564            }),
565        );
566        assert!(
567            prev_handler.is_none(),
568            "registered multiple handlers for the same LSP method"
569        );
570        Subscription {
571            method,
572            notification_handlers: self.notification_handlers.clone(),
573        }
574    }
575
576    pub fn name<'a>(self: &'a Arc<Self>) -> &'a str {
577        &self.name
578    }
579
580    pub fn capabilities<'a>(self: &'a Arc<Self>) -> &'a ServerCapabilities {
581        &self.capabilities
582    }
583
584    pub fn server_id(&self) -> usize {
585        self.server_id
586    }
587
588    pub fn root_path(&self) -> &PathBuf {
589        &self.root_path
590    }
591
592    pub fn request<T: request::Request>(
593        &self,
594        params: T::Params,
595    ) -> impl Future<Output = Result<T::Result>>
596    where
597        T::Result: 'static + Send,
598    {
599        Self::request_internal::<T>(
600            &self.next_id,
601            &self.response_handlers,
602            &self.outbound_tx,
603            params,
604        )
605    }
606
607    fn request_internal<T: request::Request>(
608        next_id: &AtomicUsize,
609        response_handlers: &Mutex<Option<HashMap<usize, ResponseHandler>>>,
610        outbound_tx: &channel::Sender<Vec<u8>>,
611        params: T::Params,
612    ) -> impl 'static + Future<Output = Result<T::Result>>
613    where
614        T::Result: 'static + Send,
615    {
616        let id = next_id.fetch_add(1, SeqCst);
617        let message = serde_json::to_vec(&Request {
618            jsonrpc: JSON_RPC_VERSION,
619            id,
620            method: T::METHOD,
621            params,
622        })
623        .unwrap();
624
625        let (tx, rx) = oneshot::channel();
626        let handle_response = response_handlers
627            .lock()
628            .as_mut()
629            .ok_or_else(|| anyhow!("server shut down"))
630            .map(|handlers| {
631                handlers.insert(
632                    id,
633                    Box::new(move |result| {
634                        let response = match result {
635                            Ok(response) => serde_json::from_str(response)
636                                .context("failed to deserialize response"),
637                            Err(error) => Err(anyhow!("{}", error.message)),
638                        };
639                        let _ = tx.send(response);
640                    }),
641                );
642            });
643
644        let send = outbound_tx
645            .try_send(message)
646            .context("failed to write to language server's stdin");
647
648        async move {
649            handle_response?;
650            send?;
651            rx.await?
652        }
653    }
654
655    pub fn notify<T: notification::Notification>(&self, params: T::Params) -> Result<()> {
656        Self::notify_internal::<T>(&self.outbound_tx, params)
657    }
658
659    fn notify_internal<T: notification::Notification>(
660        outbound_tx: &channel::Sender<Vec<u8>>,
661        params: T::Params,
662    ) -> Result<()> {
663        let message = serde_json::to_vec(&Notification {
664            jsonrpc: JSON_RPC_VERSION,
665            method: T::METHOD,
666            params,
667        })
668        .unwrap();
669        outbound_tx.try_send(message)?;
670        Ok(())
671    }
672}
673
674impl Drop for LanguageServer {
675    fn drop(&mut self) {
676        if let Some(shutdown) = self.shutdown() {
677            self.executor.spawn(shutdown).detach();
678        }
679    }
680}
681
682impl Subscription {
683    pub fn detach(mut self) {
684        self.method = "";
685    }
686}
687
688impl Drop for Subscription {
689    fn drop(&mut self) {
690        self.notification_handlers.lock().remove(self.method);
691    }
692}
693
694#[cfg(any(test, feature = "test-support"))]
695#[derive(Clone)]
696pub struct FakeLanguageServer {
697    pub server: Arc<LanguageServer>,
698    notifications_rx: channel::Receiver<(String, String)>,
699}
700
701#[cfg(any(test, feature = "test-support"))]
702impl LanguageServer {
703    pub fn full_capabilities() -> ServerCapabilities {
704        ServerCapabilities {
705            document_highlight_provider: Some(OneOf::Left(true)),
706            code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
707            document_formatting_provider: Some(OneOf::Left(true)),
708            document_range_formatting_provider: Some(OneOf::Left(true)),
709            ..Default::default()
710        }
711    }
712
713    pub fn fake(
714        name: String,
715        capabilities: ServerCapabilities,
716        cx: AsyncAppContext,
717    ) -> (Self, FakeLanguageServer) {
718        let (stdin_writer, stdin_reader) = async_pipe::pipe();
719        let (stdout_writer, stdout_reader) = async_pipe::pipe();
720        let (notifications_tx, notifications_rx) = channel::unbounded();
721
722        let server = Self::new_internal(
723            0,
724            stdin_writer,
725            stdout_reader,
726            None,
727            Path::new("/"),
728            None,
729            cx.clone(),
730            |_| {},
731        );
732        let fake = FakeLanguageServer {
733            server: Arc::new(Self::new_internal(
734                0,
735                stdout_writer,
736                stdin_reader,
737                None,
738                Path::new("/"),
739                None,
740                cx,
741                move |msg| {
742                    notifications_tx
743                        .try_send((msg.method.to_string(), msg.params.get().to_string()))
744                        .ok();
745                },
746            )),
747            notifications_rx,
748        };
749        fake.handle_request::<request::Initialize, _, _>({
750            let capabilities = capabilities;
751            move |_, _| {
752                let capabilities = capabilities.clone();
753                let name = name.clone();
754                async move {
755                    Ok(InitializeResult {
756                        capabilities,
757                        server_info: Some(ServerInfo {
758                            name,
759                            ..Default::default()
760                        }),
761                    })
762                }
763            }
764        });
765
766        (server, fake)
767    }
768}
769
770#[cfg(any(test, feature = "test-support"))]
771impl FakeLanguageServer {
772    pub fn notify<T: notification::Notification>(&self, params: T::Params) {
773        self.server.notify::<T>(params).ok();
774    }
775
776    pub async fn request<T>(&self, params: T::Params) -> Result<T::Result>
777    where
778        T: request::Request,
779        T::Result: 'static + Send,
780    {
781        self.server.request::<T>(params).await
782    }
783
784    pub async fn receive_notification<T: notification::Notification>(&mut self) -> T::Params {
785        self.try_receive_notification::<T>().await.unwrap()
786    }
787
788    pub async fn try_receive_notification<T: notification::Notification>(
789        &mut self,
790    ) -> Option<T::Params> {
791        use futures::StreamExt as _;
792
793        loop {
794            let (method, params) = self.notifications_rx.next().await?;
795            if method == T::METHOD {
796                return Some(serde_json::from_str::<T::Params>(&params).unwrap());
797            } else {
798                log::info!("skipping message in fake language server {:?}", params);
799            }
800        }
801    }
802
803    pub fn handle_request<T, F, Fut>(
804        &self,
805        mut handler: F,
806    ) -> futures::channel::mpsc::UnboundedReceiver<()>
807    where
808        T: 'static + request::Request,
809        T::Params: 'static + Send,
810        F: 'static + Send + FnMut(T::Params, gpui::AsyncAppContext) -> Fut,
811        Fut: 'static + Send + Future<Output = Result<T::Result>>,
812    {
813        let (responded_tx, responded_rx) = futures::channel::mpsc::unbounded();
814        self.server.remove_request_handler::<T>();
815        self.server
816            .on_request::<T, _, _>(move |params, cx| {
817                let result = handler(params, cx.clone());
818                let responded_tx = responded_tx.clone();
819                async move {
820                    cx.background().simulate_random_delay().await;
821                    let result = result.await;
822                    responded_tx.unbounded_send(()).ok();
823                    result
824                }
825            })
826            .detach();
827        responded_rx
828    }
829
830    pub fn handle_notification<T, F>(
831        &self,
832        mut handler: F,
833    ) -> futures::channel::mpsc::UnboundedReceiver<()>
834    where
835        T: 'static + notification::Notification,
836        T::Params: 'static + Send,
837        F: 'static + Send + FnMut(T::Params, gpui::AsyncAppContext),
838    {
839        let (handled_tx, handled_rx) = futures::channel::mpsc::unbounded();
840        self.server.remove_notification_handler::<T>();
841        self.server
842            .on_notification::<T, _>(move |params, cx| {
843                handler(params, cx.clone());
844                handled_tx.unbounded_send(()).ok();
845            })
846            .detach();
847        handled_rx
848    }
849
850    pub fn remove_request_handler<T>(&mut self)
851    where
852        T: 'static + request::Request,
853    {
854        self.server.remove_request_handler::<T>();
855    }
856
857    pub async fn start_progress(&self, token: impl Into<String>) {
858        let token = token.into();
859        self.request::<request::WorkDoneProgressCreate>(WorkDoneProgressCreateParams {
860            token: NumberOrString::String(token.clone()),
861        })
862        .await
863        .unwrap();
864        self.notify::<notification::Progress>(ProgressParams {
865            token: NumberOrString::String(token),
866            value: ProgressParamsValue::WorkDone(WorkDoneProgress::Begin(Default::default())),
867        });
868    }
869
870    pub fn end_progress(&self, token: impl Into<String>) {
871        self.notify::<notification::Progress>(ProgressParams {
872            token: NumberOrString::String(token.into()),
873            value: ProgressParamsValue::WorkDone(WorkDoneProgress::End(Default::default())),
874        });
875    }
876}
877
878#[cfg(test)]
879mod tests {
880    use super::*;
881    use gpui::TestAppContext;
882
883    #[ctor::ctor]
884    fn init_logger() {
885        if std::env::var("RUST_LOG").is_ok() {
886            env_logger::init();
887        }
888    }
889
890    #[gpui::test]
891    async fn test_fake(cx: &mut TestAppContext) {
892        let (server, mut fake) =
893            LanguageServer::fake("the-lsp".to_string(), Default::default(), cx.to_async());
894
895        let (message_tx, message_rx) = channel::unbounded();
896        let (diagnostics_tx, diagnostics_rx) = channel::unbounded();
897        server
898            .on_notification::<notification::ShowMessage, _>(move |params, _| {
899                message_tx.try_send(params).unwrap()
900            })
901            .detach();
902        server
903            .on_notification::<notification::PublishDiagnostics, _>(move |params, _| {
904                diagnostics_tx.try_send(params).unwrap()
905            })
906            .detach();
907
908        let server = server.initialize(None).await.unwrap();
909        server
910            .notify::<notification::DidOpenTextDocument>(DidOpenTextDocumentParams {
911                text_document: TextDocumentItem::new(
912                    Url::from_str("file://a/b").unwrap(),
913                    "rust".to_string(),
914                    0,
915                    "".to_string(),
916                ),
917            })
918            .unwrap();
919        assert_eq!(
920            fake.receive_notification::<notification::DidOpenTextDocument>()
921                .await
922                .text_document
923                .uri
924                .as_str(),
925            "file://a/b"
926        );
927
928        fake.notify::<notification::ShowMessage>(ShowMessageParams {
929            typ: MessageType::ERROR,
930            message: "ok".to_string(),
931        });
932        fake.notify::<notification::PublishDiagnostics>(PublishDiagnosticsParams {
933            uri: Url::from_str("file://b/c").unwrap(),
934            version: Some(5),
935            diagnostics: vec![],
936        });
937        assert_eq!(message_rx.recv().await.unwrap().message, "ok");
938        assert_eq!(
939            diagnostics_rx.recv().await.unwrap().uri.as_str(),
940            "file://b/c"
941        );
942
943        fake.handle_request::<request::Shutdown, _, _>(|_, _| async move { Ok(()) });
944
945        drop(server);
946        fake.receive_notification::<notification::Exit>().await;
947    }
948}