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