lsp.rs

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