lsp.rs

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