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