lsp_command.rs

   1pub mod signature_help;
   2
   3use crate::{
   4    CodeAction, CompletionSource, CoreCompletion, CoreCompletionResponse, DocumentColor,
   5    DocumentHighlight, DocumentSymbol, Hover, HoverBlock, HoverBlockKind, InlayHint,
   6    InlayHintLabel, InlayHintLabelPart, InlayHintLabelPartTooltip, InlayHintTooltip, Location,
   7    LocationLink, LspAction, LspPullDiagnostics, MarkupContent, PrepareRenameResponse,
   8    ProjectTransaction, PulledDiagnostics, ResolveState,
   9    lsp_store::{LocalLspStore, LspFoldingRange, LspStore},
  10};
  11use anyhow::{Context as _, Result};
  12use async_trait::async_trait;
  13use client::proto::{self, PeerId};
  14use clock::Global;
  15use collections::HashMap;
  16use futures::future;
  17use gpui::{App, AsyncApp, Entity, SharedString, Task, prelude::FluentBuilder};
  18use language::{
  19    Anchor, Bias, Buffer, BufferSnapshot, CachedLspAdapter, CharKind, CharScopeContext,
  20    OffsetRangeExt, PointUtf16, ToOffset, ToPointUtf16, Transaction, Unclipped,
  21    language_settings::{InlayHintKind, LanguageSettings},
  22    point_from_lsp, point_to_lsp,
  23    proto::{
  24        deserialize_anchor, deserialize_anchor_range, deserialize_version, serialize_anchor,
  25        serialize_anchor_range, serialize_version,
  26    },
  27    range_from_lsp, range_to_lsp,
  28};
  29use lsp::{
  30    AdapterServerCapabilities, CodeActionKind, CodeActionOptions, CodeDescription,
  31    CompletionContext, CompletionListItemDefaultsEditRange, CompletionTriggerKind,
  32    DocumentHighlightKind, LanguageServer, LanguageServerId, LinkedEditingRangeServerCapabilities,
  33    OneOf, RenameOptions, ServerCapabilities,
  34};
  35use serde_json::Value;
  36use signature_help::{lsp_to_proto_signature, proto_to_lsp_signature};
  37use std::{
  38    cmp::Reverse, collections::hash_map, mem, ops::Range, path::Path, str::FromStr, sync::Arc,
  39};
  40use text::{BufferId, LineEnding};
  41use util::{ResultExt as _, debug_panic};
  42
  43pub use signature_help::SignatureHelp;
  44
  45fn code_action_kind_matches(requested: &lsp::CodeActionKind, actual: &lsp::CodeActionKind) -> bool {
  46    let requested_str = requested.as_str();
  47    let actual_str = actual.as_str();
  48
  49    // Exact match or hierarchical match
  50    actual_str == requested_str
  51        || actual_str
  52            .strip_prefix(requested_str)
  53            .is_some_and(|suffix| suffix.starts_with('.'))
  54}
  55
  56pub fn lsp_formatting_options(settings: &LanguageSettings) -> lsp::FormattingOptions {
  57    lsp::FormattingOptions {
  58        tab_size: settings.tab_size.into(),
  59        insert_spaces: !settings.hard_tabs,
  60        trim_trailing_whitespace: Some(settings.remove_trailing_whitespace_on_save),
  61        trim_final_newlines: Some(settings.ensure_final_newline_on_save),
  62        insert_final_newline: Some(settings.ensure_final_newline_on_save),
  63        ..lsp::FormattingOptions::default()
  64    }
  65}
  66
  67pub fn file_path_to_lsp_url(path: &Path) -> Result<lsp::Uri> {
  68    match lsp::Uri::from_file_path(path) {
  69        Ok(url) => Ok(url),
  70        Err(()) => anyhow::bail!("Invalid file path provided to LSP request: {path:?}"),
  71    }
  72}
  73
  74pub(crate) fn make_text_document_identifier(path: &Path) -> Result<lsp::TextDocumentIdentifier> {
  75    Ok(lsp::TextDocumentIdentifier {
  76        uri: file_path_to_lsp_url(path)?,
  77    })
  78}
  79
  80pub(crate) fn make_lsp_text_document_position(
  81    path: &Path,
  82    position: PointUtf16,
  83) -> Result<lsp::TextDocumentPositionParams> {
  84    Ok(lsp::TextDocumentPositionParams {
  85        text_document: make_text_document_identifier(path)?,
  86        position: point_to_lsp(position),
  87    })
  88}
  89
  90#[async_trait(?Send)]
  91pub trait LspCommand: 'static + Sized + Send + std::fmt::Debug {
  92    type Response: 'static + Default + Send + std::fmt::Debug;
  93    type LspRequest: 'static + Send + lsp::request::Request;
  94    type ProtoRequest: 'static + Send + proto::RequestMessage;
  95
  96    fn display_name(&self) -> &str;
  97
  98    fn status(&self) -> Option<String> {
  99        None
 100    }
 101
 102    fn to_lsp_params_or_response(
 103        &self,
 104        path: &Path,
 105        buffer: &Buffer,
 106        language_server: &Arc<LanguageServer>,
 107        cx: &App,
 108    ) -> Result<
 109        LspParamsOrResponse<<Self::LspRequest as lsp::request::Request>::Params, Self::Response>,
 110    > {
 111        if self.check_capabilities(language_server.adapter_server_capabilities()) {
 112            Ok(LspParamsOrResponse::Params(self.to_lsp(
 113                path,
 114                buffer,
 115                language_server,
 116                cx,
 117            )?))
 118        } else {
 119            Ok(LspParamsOrResponse::Response(Default::default()))
 120        }
 121    }
 122
 123    /// When false, `to_lsp_params_or_response` default implementation will return the default response.
 124    fn check_capabilities(&self, _: AdapterServerCapabilities) -> bool;
 125
 126    fn to_lsp(
 127        &self,
 128        path: &Path,
 129        buffer: &Buffer,
 130        language_server: &Arc<LanguageServer>,
 131        cx: &App,
 132    ) -> Result<<Self::LspRequest as lsp::request::Request>::Params>;
 133
 134    async fn response_from_lsp(
 135        self,
 136        message: <Self::LspRequest as lsp::request::Request>::Result,
 137        lsp_store: Entity<LspStore>,
 138        buffer: Entity<Buffer>,
 139        server_id: LanguageServerId,
 140        cx: AsyncApp,
 141    ) -> Result<Self::Response>;
 142
 143    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> Self::ProtoRequest;
 144
 145    async fn from_proto(
 146        message: Self::ProtoRequest,
 147        lsp_store: Entity<LspStore>,
 148        buffer: Entity<Buffer>,
 149        cx: AsyncApp,
 150    ) -> Result<Self>;
 151
 152    fn response_to_proto(
 153        response: Self::Response,
 154        lsp_store: &mut LspStore,
 155        peer_id: PeerId,
 156        buffer_version: &clock::Global,
 157        cx: &mut App,
 158    ) -> <Self::ProtoRequest as proto::RequestMessage>::Response;
 159
 160    async fn response_from_proto(
 161        self,
 162        message: <Self::ProtoRequest as proto::RequestMessage>::Response,
 163        lsp_store: Entity<LspStore>,
 164        buffer: Entity<Buffer>,
 165        cx: AsyncApp,
 166    ) -> Result<Self::Response>;
 167
 168    fn buffer_id_from_proto(message: &Self::ProtoRequest) -> Result<BufferId>;
 169}
 170
 171pub enum LspParamsOrResponse<P, R> {
 172    Params(P),
 173    Response(R),
 174}
 175
 176#[derive(Debug)]
 177pub(crate) struct PrepareRename {
 178    pub position: PointUtf16,
 179}
 180
 181#[derive(Debug)]
 182pub(crate) struct PerformRename {
 183    pub position: PointUtf16,
 184    pub new_name: String,
 185    pub push_to_history: bool,
 186}
 187
 188#[derive(Debug, Clone, Copy)]
 189pub struct GetDefinitions {
 190    pub position: PointUtf16,
 191}
 192
 193#[derive(Debug, Clone, Copy)]
 194pub(crate) struct GetDeclarations {
 195    pub position: PointUtf16,
 196}
 197
 198#[derive(Debug, Clone, Copy)]
 199pub(crate) struct GetTypeDefinitions {
 200    pub position: PointUtf16,
 201}
 202
 203#[derive(Debug, Clone, Copy)]
 204pub(crate) struct GetImplementations {
 205    pub position: PointUtf16,
 206}
 207
 208#[derive(Debug, Clone, Copy)]
 209pub(crate) struct GetReferences {
 210    pub position: PointUtf16,
 211}
 212
 213#[derive(Debug)]
 214pub(crate) struct GetDocumentHighlights {
 215    pub position: PointUtf16,
 216}
 217
 218#[derive(Debug, Copy, Clone)]
 219pub(crate) struct GetDocumentSymbols;
 220
 221#[derive(Clone, Debug)]
 222pub(crate) struct GetSignatureHelp {
 223    pub position: PointUtf16,
 224}
 225
 226#[derive(Clone, Debug)]
 227pub(crate) struct GetHover {
 228    pub position: PointUtf16,
 229}
 230
 231#[derive(Debug)]
 232pub(crate) struct GetCompletions {
 233    pub position: PointUtf16,
 234    pub context: CompletionContext,
 235    pub server_id: Option<lsp::LanguageServerId>,
 236}
 237
 238#[derive(Clone, Debug)]
 239pub(crate) struct GetCodeActions {
 240    pub range: Range<Anchor>,
 241    pub kinds: Option<Vec<lsp::CodeActionKind>>,
 242}
 243
 244#[derive(Debug)]
 245pub(crate) struct OnTypeFormatting {
 246    pub position: PointUtf16,
 247    pub trigger: String,
 248    pub options: lsp::FormattingOptions,
 249    pub push_to_history: bool,
 250}
 251
 252#[derive(Clone, Debug)]
 253pub(crate) struct InlayHints {
 254    pub range: Range<Anchor>,
 255}
 256
 257#[derive(Debug, Clone, Copy)]
 258pub(crate) struct SemanticTokensFull {
 259    pub for_server: Option<LanguageServerId>,
 260}
 261
 262#[derive(Debug, Clone)]
 263pub(crate) struct SemanticTokensDelta {
 264    pub previous_result_id: SharedString,
 265}
 266
 267#[derive(Debug)]
 268pub(crate) enum SemanticTokensResponse {
 269    Full {
 270        data: Vec<u32>,
 271        result_id: Option<SharedString>,
 272    },
 273    Delta {
 274        edits: Vec<SemanticTokensEdit>,
 275        result_id: Option<SharedString>,
 276    },
 277}
 278
 279impl Default for SemanticTokensResponse {
 280    fn default() -> Self {
 281        Self::Delta {
 282            edits: Vec::new(),
 283            result_id: None,
 284        }
 285    }
 286}
 287
 288#[derive(Debug)]
 289pub(crate) struct SemanticTokensEdit {
 290    pub start: u32,
 291    pub delete_count: u32,
 292    pub data: Vec<u32>,
 293}
 294
 295#[derive(Debug, Copy, Clone)]
 296pub(crate) struct GetCodeLens;
 297
 298#[derive(Debug, Copy, Clone)]
 299pub(crate) struct GetDocumentColor;
 300
 301#[derive(Debug, Copy, Clone)]
 302pub(crate) struct GetFoldingRanges;
 303
 304impl GetCodeLens {
 305    pub(crate) fn can_resolve_lens(capabilities: &ServerCapabilities) -> bool {
 306        capabilities
 307            .code_lens_provider
 308            .as_ref()
 309            .and_then(|code_lens_options| code_lens_options.resolve_provider)
 310            .unwrap_or(false)
 311    }
 312}
 313
 314#[derive(Debug)]
 315pub(crate) struct LinkedEditingRange {
 316    pub position: Anchor,
 317}
 318
 319#[derive(Clone, Debug)]
 320pub struct GetDocumentDiagnostics {
 321    /// We cannot blindly rely on server's capabilities.diagnostic_provider, as they're a singular field, whereas
 322    /// a server can register multiple diagnostic providers post-mortem.
 323    pub registration_id: Option<SharedString>,
 324    pub identifier: Option<SharedString>,
 325    pub previous_result_id: Option<SharedString>,
 326}
 327
 328#[async_trait(?Send)]
 329impl LspCommand for PrepareRename {
 330    type Response = PrepareRenameResponse;
 331    type LspRequest = lsp::request::PrepareRenameRequest;
 332    type ProtoRequest = proto::PrepareRename;
 333
 334    fn display_name(&self) -> &str {
 335        "Prepare rename"
 336    }
 337
 338    fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
 339        capabilities
 340            .server_capabilities
 341            .rename_provider
 342            .is_some_and(|capability| match capability {
 343                OneOf::Left(enabled) => enabled,
 344                OneOf::Right(options) => options.prepare_provider.unwrap_or(false),
 345            })
 346    }
 347
 348    fn to_lsp_params_or_response(
 349        &self,
 350        path: &Path,
 351        buffer: &Buffer,
 352        language_server: &Arc<LanguageServer>,
 353        cx: &App,
 354    ) -> Result<LspParamsOrResponse<lsp::TextDocumentPositionParams, PrepareRenameResponse>> {
 355        let rename_provider = language_server
 356            .adapter_server_capabilities()
 357            .server_capabilities
 358            .rename_provider;
 359        match rename_provider {
 360            Some(lsp::OneOf::Right(RenameOptions {
 361                prepare_provider: Some(true),
 362                ..
 363            })) => Ok(LspParamsOrResponse::Params(self.to_lsp(
 364                path,
 365                buffer,
 366                language_server,
 367                cx,
 368            )?)),
 369            Some(lsp::OneOf::Right(_)) => Ok(LspParamsOrResponse::Response(
 370                PrepareRenameResponse::OnlyUnpreparedRenameSupported,
 371            )),
 372            Some(lsp::OneOf::Left(true)) => Ok(LspParamsOrResponse::Response(
 373                PrepareRenameResponse::OnlyUnpreparedRenameSupported,
 374            )),
 375            _ => anyhow::bail!("Rename not supported"),
 376        }
 377    }
 378
 379    fn to_lsp(
 380        &self,
 381        path: &Path,
 382        _: &Buffer,
 383        _: &Arc<LanguageServer>,
 384        _: &App,
 385    ) -> Result<lsp::TextDocumentPositionParams> {
 386        make_lsp_text_document_position(path, self.position)
 387    }
 388
 389    async fn response_from_lsp(
 390        self,
 391        message: Option<lsp::PrepareRenameResponse>,
 392        _: Entity<LspStore>,
 393        buffer: Entity<Buffer>,
 394        _: LanguageServerId,
 395        cx: AsyncApp,
 396    ) -> Result<PrepareRenameResponse> {
 397        buffer.read_with(&cx, |buffer, _| match message {
 398            Some(lsp::PrepareRenameResponse::Range(range))
 399            | Some(lsp::PrepareRenameResponse::RangeWithPlaceholder { range, .. }) => {
 400                let Range { start, end } = range_from_lsp(range);
 401                if buffer.clip_point_utf16(start, Bias::Left) == start.0
 402                    && buffer.clip_point_utf16(end, Bias::Left) == end.0
 403                {
 404                    Ok(PrepareRenameResponse::Success(
 405                        buffer.anchor_after(start)..buffer.anchor_before(end),
 406                    ))
 407                } else {
 408                    Ok(PrepareRenameResponse::InvalidPosition)
 409                }
 410            }
 411            Some(lsp::PrepareRenameResponse::DefaultBehavior { .. }) => {
 412                let snapshot = buffer.snapshot();
 413                let (range, _) = snapshot.surrounding_word(self.position, None);
 414                let range = snapshot.anchor_after(range.start)..snapshot.anchor_before(range.end);
 415                Ok(PrepareRenameResponse::Success(range))
 416            }
 417            None => Ok(PrepareRenameResponse::InvalidPosition),
 418        })
 419    }
 420
 421    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> proto::PrepareRename {
 422        proto::PrepareRename {
 423            project_id,
 424            buffer_id: buffer.remote_id().into(),
 425            position: Some(language::proto::serialize_anchor(
 426                &buffer.anchor_before(self.position),
 427            )),
 428            version: serialize_version(&buffer.version()),
 429        }
 430    }
 431
 432    async fn from_proto(
 433        message: proto::PrepareRename,
 434        _: Entity<LspStore>,
 435        buffer: Entity<Buffer>,
 436        mut cx: AsyncApp,
 437    ) -> Result<Self> {
 438        let position = message
 439            .position
 440            .and_then(deserialize_anchor)
 441            .context("invalid position")?;
 442        buffer
 443            .update(&mut cx, |buffer, _| {
 444                buffer.wait_for_version(deserialize_version(&message.version))
 445            })
 446            .await?;
 447
 448        Ok(Self {
 449            position: buffer.read_with(&cx, |buffer, _| position.to_point_utf16(buffer)),
 450        })
 451    }
 452
 453    fn response_to_proto(
 454        response: PrepareRenameResponse,
 455        _: &mut LspStore,
 456        _: PeerId,
 457        buffer_version: &clock::Global,
 458        _: &mut App,
 459    ) -> proto::PrepareRenameResponse {
 460        match response {
 461            PrepareRenameResponse::Success(range) => proto::PrepareRenameResponse {
 462                can_rename: true,
 463                only_unprepared_rename_supported: false,
 464                start: Some(language::proto::serialize_anchor(&range.start)),
 465                end: Some(language::proto::serialize_anchor(&range.end)),
 466                version: serialize_version(buffer_version),
 467            },
 468            PrepareRenameResponse::OnlyUnpreparedRenameSupported => proto::PrepareRenameResponse {
 469                can_rename: false,
 470                only_unprepared_rename_supported: true,
 471                start: None,
 472                end: None,
 473                version: vec![],
 474            },
 475            PrepareRenameResponse::InvalidPosition => proto::PrepareRenameResponse {
 476                can_rename: false,
 477                only_unprepared_rename_supported: false,
 478                start: None,
 479                end: None,
 480                version: vec![],
 481            },
 482        }
 483    }
 484
 485    async fn response_from_proto(
 486        self,
 487        message: proto::PrepareRenameResponse,
 488        _: Entity<LspStore>,
 489        buffer: Entity<Buffer>,
 490        mut cx: AsyncApp,
 491    ) -> Result<PrepareRenameResponse> {
 492        if message.can_rename {
 493            buffer
 494                .update(&mut cx, |buffer, _| {
 495                    buffer.wait_for_version(deserialize_version(&message.version))
 496                })
 497                .await?;
 498            if let (Some(start), Some(end)) = (
 499                message.start.and_then(deserialize_anchor),
 500                message.end.and_then(deserialize_anchor),
 501            ) {
 502                Ok(PrepareRenameResponse::Success(start..end))
 503            } else {
 504                anyhow::bail!(
 505                    "Missing start or end position in remote project PrepareRenameResponse"
 506                );
 507            }
 508        } else if message.only_unprepared_rename_supported {
 509            Ok(PrepareRenameResponse::OnlyUnpreparedRenameSupported)
 510        } else {
 511            Ok(PrepareRenameResponse::InvalidPosition)
 512        }
 513    }
 514
 515    fn buffer_id_from_proto(message: &proto::PrepareRename) -> Result<BufferId> {
 516        BufferId::new(message.buffer_id)
 517    }
 518}
 519
 520#[async_trait(?Send)]
 521impl LspCommand for PerformRename {
 522    type Response = ProjectTransaction;
 523    type LspRequest = lsp::request::Rename;
 524    type ProtoRequest = proto::PerformRename;
 525
 526    fn display_name(&self) -> &str {
 527        "Rename"
 528    }
 529
 530    fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
 531        capabilities
 532            .server_capabilities
 533            .rename_provider
 534            .is_some_and(|capability| match capability {
 535                OneOf::Left(enabled) => enabled,
 536                OneOf::Right(_) => true,
 537            })
 538    }
 539
 540    fn to_lsp(
 541        &self,
 542        path: &Path,
 543        _: &Buffer,
 544        _: &Arc<LanguageServer>,
 545        _: &App,
 546    ) -> Result<lsp::RenameParams> {
 547        Ok(lsp::RenameParams {
 548            text_document_position: make_lsp_text_document_position(path, self.position)?,
 549            new_name: self.new_name.clone(),
 550            work_done_progress_params: Default::default(),
 551        })
 552    }
 553
 554    async fn response_from_lsp(
 555        self,
 556        message: Option<lsp::WorkspaceEdit>,
 557        lsp_store: Entity<LspStore>,
 558        buffer: Entity<Buffer>,
 559        server_id: LanguageServerId,
 560        mut cx: AsyncApp,
 561    ) -> Result<ProjectTransaction> {
 562        if let Some(edit) = message {
 563            let (_, lsp_server) =
 564                language_server_for_buffer(&lsp_store, &buffer, server_id, &mut cx)?;
 565            LocalLspStore::deserialize_workspace_edit(
 566                lsp_store,
 567                edit,
 568                self.push_to_history,
 569                lsp_server,
 570                &mut cx,
 571            )
 572            .await
 573        } else {
 574            Ok(ProjectTransaction::default())
 575        }
 576    }
 577
 578    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> proto::PerformRename {
 579        proto::PerformRename {
 580            project_id,
 581            buffer_id: buffer.remote_id().into(),
 582            position: Some(language::proto::serialize_anchor(
 583                &buffer.anchor_before(self.position),
 584            )),
 585            new_name: self.new_name.clone(),
 586            version: serialize_version(&buffer.version()),
 587        }
 588    }
 589
 590    async fn from_proto(
 591        message: proto::PerformRename,
 592        _: Entity<LspStore>,
 593        buffer: Entity<Buffer>,
 594        mut cx: AsyncApp,
 595    ) -> Result<Self> {
 596        let position = message
 597            .position
 598            .and_then(deserialize_anchor)
 599            .context("invalid position")?;
 600        buffer
 601            .update(&mut cx, |buffer, _| {
 602                buffer.wait_for_version(deserialize_version(&message.version))
 603            })
 604            .await?;
 605        Ok(Self {
 606            position: buffer.read_with(&cx, |buffer, _| position.to_point_utf16(buffer)),
 607            new_name: message.new_name,
 608            push_to_history: false,
 609        })
 610    }
 611
 612    fn response_to_proto(
 613        response: ProjectTransaction,
 614        lsp_store: &mut LspStore,
 615        peer_id: PeerId,
 616        _: &clock::Global,
 617        cx: &mut App,
 618    ) -> proto::PerformRenameResponse {
 619        let transaction = lsp_store.buffer_store().update(cx, |buffer_store, cx| {
 620            buffer_store.serialize_project_transaction_for_peer(response, peer_id, cx)
 621        });
 622        proto::PerformRenameResponse {
 623            transaction: Some(transaction),
 624        }
 625    }
 626
 627    async fn response_from_proto(
 628        self,
 629        message: proto::PerformRenameResponse,
 630        lsp_store: Entity<LspStore>,
 631        _: Entity<Buffer>,
 632        mut cx: AsyncApp,
 633    ) -> Result<ProjectTransaction> {
 634        let message = message.transaction.context("missing transaction")?;
 635        lsp_store
 636            .update(&mut cx, |lsp_store, cx| {
 637                lsp_store.buffer_store().update(cx, |buffer_store, cx| {
 638                    buffer_store.deserialize_project_transaction(message, self.push_to_history, cx)
 639                })
 640            })
 641            .await
 642    }
 643
 644    fn buffer_id_from_proto(message: &proto::PerformRename) -> Result<BufferId> {
 645        BufferId::new(message.buffer_id)
 646    }
 647}
 648
 649#[async_trait(?Send)]
 650impl LspCommand for GetDefinitions {
 651    type Response = Vec<LocationLink>;
 652    type LspRequest = lsp::request::GotoDefinition;
 653    type ProtoRequest = proto::GetDefinition;
 654
 655    fn display_name(&self) -> &str {
 656        "Get definition"
 657    }
 658
 659    fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
 660        capabilities
 661            .server_capabilities
 662            .definition_provider
 663            .is_some_and(|capability| match capability {
 664                OneOf::Left(supported) => supported,
 665                OneOf::Right(_options) => true,
 666            })
 667    }
 668
 669    fn to_lsp(
 670        &self,
 671        path: &Path,
 672        _: &Buffer,
 673        _: &Arc<LanguageServer>,
 674        _: &App,
 675    ) -> Result<lsp::GotoDefinitionParams> {
 676        Ok(lsp::GotoDefinitionParams {
 677            text_document_position_params: make_lsp_text_document_position(path, self.position)?,
 678            work_done_progress_params: Default::default(),
 679            partial_result_params: Default::default(),
 680        })
 681    }
 682
 683    async fn response_from_lsp(
 684        self,
 685        message: Option<lsp::GotoDefinitionResponse>,
 686        lsp_store: Entity<LspStore>,
 687        buffer: Entity<Buffer>,
 688        server_id: LanguageServerId,
 689        cx: AsyncApp,
 690    ) -> Result<Vec<LocationLink>> {
 691        location_links_from_lsp(message, lsp_store, buffer, server_id, cx).await
 692    }
 693
 694    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> proto::GetDefinition {
 695        proto::GetDefinition {
 696            project_id,
 697            buffer_id: buffer.remote_id().into(),
 698            position: Some(language::proto::serialize_anchor(
 699                &buffer.anchor_before(self.position),
 700            )),
 701            version: serialize_version(&buffer.version()),
 702        }
 703    }
 704
 705    async fn from_proto(
 706        message: proto::GetDefinition,
 707        _: Entity<LspStore>,
 708        buffer: Entity<Buffer>,
 709        mut cx: AsyncApp,
 710    ) -> Result<Self> {
 711        let position = message
 712            .position
 713            .and_then(deserialize_anchor)
 714            .context("invalid position")?;
 715        buffer
 716            .update(&mut cx, |buffer, _| {
 717                buffer.wait_for_version(deserialize_version(&message.version))
 718            })
 719            .await?;
 720        Ok(Self {
 721            position: buffer.read_with(&cx, |buffer, _| position.to_point_utf16(buffer)),
 722        })
 723    }
 724
 725    fn response_to_proto(
 726        response: Vec<LocationLink>,
 727        lsp_store: &mut LspStore,
 728        peer_id: PeerId,
 729        _: &clock::Global,
 730        cx: &mut App,
 731    ) -> proto::GetDefinitionResponse {
 732        let links = location_links_to_proto(response, lsp_store, peer_id, cx);
 733        proto::GetDefinitionResponse { links }
 734    }
 735
 736    async fn response_from_proto(
 737        self,
 738        message: proto::GetDefinitionResponse,
 739        lsp_store: Entity<LspStore>,
 740        _: Entity<Buffer>,
 741        cx: AsyncApp,
 742    ) -> Result<Vec<LocationLink>> {
 743        location_links_from_proto(message.links, lsp_store, cx).await
 744    }
 745
 746    fn buffer_id_from_proto(message: &proto::GetDefinition) -> Result<BufferId> {
 747        BufferId::new(message.buffer_id)
 748    }
 749}
 750
 751#[async_trait(?Send)]
 752impl LspCommand for GetDeclarations {
 753    type Response = Vec<LocationLink>;
 754    type LspRequest = lsp::request::GotoDeclaration;
 755    type ProtoRequest = proto::GetDeclaration;
 756
 757    fn display_name(&self) -> &str {
 758        "Get declaration"
 759    }
 760
 761    fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
 762        capabilities
 763            .server_capabilities
 764            .declaration_provider
 765            .is_some_and(|capability| match capability {
 766                lsp::DeclarationCapability::Simple(supported) => supported,
 767                lsp::DeclarationCapability::RegistrationOptions(..) => true,
 768                lsp::DeclarationCapability::Options(..) => true,
 769            })
 770    }
 771
 772    fn to_lsp(
 773        &self,
 774        path: &Path,
 775        _: &Buffer,
 776        _: &Arc<LanguageServer>,
 777        _: &App,
 778    ) -> Result<lsp::GotoDeclarationParams> {
 779        Ok(lsp::GotoDeclarationParams {
 780            text_document_position_params: make_lsp_text_document_position(path, self.position)?,
 781            work_done_progress_params: Default::default(),
 782            partial_result_params: Default::default(),
 783        })
 784    }
 785
 786    async fn response_from_lsp(
 787        self,
 788        message: Option<lsp::GotoDeclarationResponse>,
 789        lsp_store: Entity<LspStore>,
 790        buffer: Entity<Buffer>,
 791        server_id: LanguageServerId,
 792        cx: AsyncApp,
 793    ) -> Result<Vec<LocationLink>> {
 794        location_links_from_lsp(message, lsp_store, buffer, server_id, cx).await
 795    }
 796
 797    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> proto::GetDeclaration {
 798        proto::GetDeclaration {
 799            project_id,
 800            buffer_id: buffer.remote_id().into(),
 801            position: Some(language::proto::serialize_anchor(
 802                &buffer.anchor_before(self.position),
 803            )),
 804            version: serialize_version(&buffer.version()),
 805        }
 806    }
 807
 808    async fn from_proto(
 809        message: proto::GetDeclaration,
 810        _: Entity<LspStore>,
 811        buffer: Entity<Buffer>,
 812        mut cx: AsyncApp,
 813    ) -> Result<Self> {
 814        let position = message
 815            .position
 816            .and_then(deserialize_anchor)
 817            .context("invalid position")?;
 818        buffer
 819            .update(&mut cx, |buffer, _| {
 820                buffer.wait_for_version(deserialize_version(&message.version))
 821            })
 822            .await?;
 823        Ok(Self {
 824            position: buffer.read_with(&cx, |buffer, _| position.to_point_utf16(buffer)),
 825        })
 826    }
 827
 828    fn response_to_proto(
 829        response: Vec<LocationLink>,
 830        lsp_store: &mut LspStore,
 831        peer_id: PeerId,
 832        _: &clock::Global,
 833        cx: &mut App,
 834    ) -> proto::GetDeclarationResponse {
 835        let links = location_links_to_proto(response, lsp_store, peer_id, cx);
 836        proto::GetDeclarationResponse { links }
 837    }
 838
 839    async fn response_from_proto(
 840        self,
 841        message: proto::GetDeclarationResponse,
 842        lsp_store: Entity<LspStore>,
 843        _: Entity<Buffer>,
 844        cx: AsyncApp,
 845    ) -> Result<Vec<LocationLink>> {
 846        location_links_from_proto(message.links, lsp_store, cx).await
 847    }
 848
 849    fn buffer_id_from_proto(message: &proto::GetDeclaration) -> Result<BufferId> {
 850        BufferId::new(message.buffer_id)
 851    }
 852}
 853
 854#[async_trait(?Send)]
 855impl LspCommand for GetImplementations {
 856    type Response = Vec<LocationLink>;
 857    type LspRequest = lsp::request::GotoImplementation;
 858    type ProtoRequest = proto::GetImplementation;
 859
 860    fn display_name(&self) -> &str {
 861        "Get implementation"
 862    }
 863
 864    fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
 865        capabilities
 866            .server_capabilities
 867            .implementation_provider
 868            .is_some_and(|capability| match capability {
 869                lsp::ImplementationProviderCapability::Simple(enabled) => enabled,
 870                lsp::ImplementationProviderCapability::Options(_options) => true,
 871            })
 872    }
 873
 874    fn to_lsp(
 875        &self,
 876        path: &Path,
 877        _: &Buffer,
 878        _: &Arc<LanguageServer>,
 879        _: &App,
 880    ) -> Result<lsp::GotoImplementationParams> {
 881        Ok(lsp::GotoImplementationParams {
 882            text_document_position_params: make_lsp_text_document_position(path, self.position)?,
 883            work_done_progress_params: Default::default(),
 884            partial_result_params: Default::default(),
 885        })
 886    }
 887
 888    async fn response_from_lsp(
 889        self,
 890        message: Option<lsp::GotoImplementationResponse>,
 891        lsp_store: Entity<LspStore>,
 892        buffer: Entity<Buffer>,
 893        server_id: LanguageServerId,
 894        cx: AsyncApp,
 895    ) -> Result<Vec<LocationLink>> {
 896        location_links_from_lsp(message, lsp_store, buffer, server_id, cx).await
 897    }
 898
 899    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> proto::GetImplementation {
 900        proto::GetImplementation {
 901            project_id,
 902            buffer_id: buffer.remote_id().into(),
 903            position: Some(language::proto::serialize_anchor(
 904                &buffer.anchor_before(self.position),
 905            )),
 906            version: serialize_version(&buffer.version()),
 907        }
 908    }
 909
 910    async fn from_proto(
 911        message: proto::GetImplementation,
 912        _: Entity<LspStore>,
 913        buffer: Entity<Buffer>,
 914        mut cx: AsyncApp,
 915    ) -> Result<Self> {
 916        let position = message
 917            .position
 918            .and_then(deserialize_anchor)
 919            .context("invalid position")?;
 920        buffer
 921            .update(&mut cx, |buffer, _| {
 922                buffer.wait_for_version(deserialize_version(&message.version))
 923            })
 924            .await?;
 925        Ok(Self {
 926            position: buffer.read_with(&cx, |buffer, _| position.to_point_utf16(buffer)),
 927        })
 928    }
 929
 930    fn response_to_proto(
 931        response: Vec<LocationLink>,
 932        lsp_store: &mut LspStore,
 933        peer_id: PeerId,
 934        _: &clock::Global,
 935        cx: &mut App,
 936    ) -> proto::GetImplementationResponse {
 937        let links = location_links_to_proto(response, lsp_store, peer_id, cx);
 938        proto::GetImplementationResponse { links }
 939    }
 940
 941    async fn response_from_proto(
 942        self,
 943        message: proto::GetImplementationResponse,
 944        project: Entity<LspStore>,
 945        _: Entity<Buffer>,
 946        cx: AsyncApp,
 947    ) -> Result<Vec<LocationLink>> {
 948        location_links_from_proto(message.links, project, cx).await
 949    }
 950
 951    fn buffer_id_from_proto(message: &proto::GetImplementation) -> Result<BufferId> {
 952        BufferId::new(message.buffer_id)
 953    }
 954}
 955
 956#[async_trait(?Send)]
 957impl LspCommand for GetTypeDefinitions {
 958    type Response = Vec<LocationLink>;
 959    type LspRequest = lsp::request::GotoTypeDefinition;
 960    type ProtoRequest = proto::GetTypeDefinition;
 961
 962    fn display_name(&self) -> &str {
 963        "Get type definition"
 964    }
 965
 966    fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
 967        !matches!(
 968            &capabilities.server_capabilities.type_definition_provider,
 969            None | Some(lsp::TypeDefinitionProviderCapability::Simple(false))
 970        )
 971    }
 972
 973    fn to_lsp(
 974        &self,
 975        path: &Path,
 976        _: &Buffer,
 977        _: &Arc<LanguageServer>,
 978        _: &App,
 979    ) -> Result<lsp::GotoTypeDefinitionParams> {
 980        Ok(lsp::GotoTypeDefinitionParams {
 981            text_document_position_params: make_lsp_text_document_position(path, self.position)?,
 982            work_done_progress_params: Default::default(),
 983            partial_result_params: Default::default(),
 984        })
 985    }
 986
 987    async fn response_from_lsp(
 988        self,
 989        message: Option<lsp::GotoTypeDefinitionResponse>,
 990        project: Entity<LspStore>,
 991        buffer: Entity<Buffer>,
 992        server_id: LanguageServerId,
 993        cx: AsyncApp,
 994    ) -> Result<Vec<LocationLink>> {
 995        location_links_from_lsp(message, project, buffer, server_id, cx).await
 996    }
 997
 998    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> proto::GetTypeDefinition {
 999        proto::GetTypeDefinition {
1000            project_id,
1001            buffer_id: buffer.remote_id().into(),
1002            position: Some(language::proto::serialize_anchor(
1003                &buffer.anchor_before(self.position),
1004            )),
1005            version: serialize_version(&buffer.version()),
1006        }
1007    }
1008
1009    async fn from_proto(
1010        message: proto::GetTypeDefinition,
1011        _: Entity<LspStore>,
1012        buffer: Entity<Buffer>,
1013        mut cx: AsyncApp,
1014    ) -> Result<Self> {
1015        let position = message
1016            .position
1017            .and_then(deserialize_anchor)
1018            .context("invalid position")?;
1019        buffer
1020            .update(&mut cx, |buffer, _| {
1021                buffer.wait_for_version(deserialize_version(&message.version))
1022            })
1023            .await?;
1024        Ok(Self {
1025            position: buffer.read_with(&cx, |buffer, _| position.to_point_utf16(buffer)),
1026        })
1027    }
1028
1029    fn response_to_proto(
1030        response: Vec<LocationLink>,
1031        lsp_store: &mut LspStore,
1032        peer_id: PeerId,
1033        _: &clock::Global,
1034        cx: &mut App,
1035    ) -> proto::GetTypeDefinitionResponse {
1036        let links = location_links_to_proto(response, lsp_store, peer_id, cx);
1037        proto::GetTypeDefinitionResponse { links }
1038    }
1039
1040    async fn response_from_proto(
1041        self,
1042        message: proto::GetTypeDefinitionResponse,
1043        project: Entity<LspStore>,
1044        _: Entity<Buffer>,
1045        cx: AsyncApp,
1046    ) -> Result<Vec<LocationLink>> {
1047        location_links_from_proto(message.links, project, cx).await
1048    }
1049
1050    fn buffer_id_from_proto(message: &proto::GetTypeDefinition) -> Result<BufferId> {
1051        BufferId::new(message.buffer_id)
1052    }
1053}
1054
1055fn language_server_for_buffer(
1056    lsp_store: &Entity<LspStore>,
1057    buffer: &Entity<Buffer>,
1058    server_id: LanguageServerId,
1059    cx: &mut AsyncApp,
1060) -> Result<(Arc<CachedLspAdapter>, Arc<LanguageServer>)> {
1061    lsp_store
1062        .update(cx, |lsp_store, cx| {
1063            buffer.update(cx, |buffer, cx| {
1064                lsp_store
1065                    .language_server_for_local_buffer(buffer, server_id, cx)
1066                    .map(|(adapter, server)| (adapter.clone(), server.clone()))
1067            })
1068        })
1069        .context("no language server found for buffer")
1070}
1071
1072pub async fn location_links_from_proto(
1073    proto_links: Vec<proto::LocationLink>,
1074    lsp_store: Entity<LspStore>,
1075    mut cx: AsyncApp,
1076) -> Result<Vec<LocationLink>> {
1077    let mut links = Vec::new();
1078
1079    for link in proto_links {
1080        links.push(location_link_from_proto(link, lsp_store.clone(), &mut cx).await?)
1081    }
1082
1083    Ok(links)
1084}
1085
1086pub fn location_link_from_proto(
1087    link: proto::LocationLink,
1088    lsp_store: Entity<LspStore>,
1089    cx: &mut AsyncApp,
1090) -> Task<Result<LocationLink>> {
1091    cx.spawn(async move |cx| {
1092        let origin = match link.origin {
1093            Some(origin) => {
1094                let buffer_id = BufferId::new(origin.buffer_id)?;
1095                let buffer = lsp_store
1096                    .update(cx, |lsp_store, cx| {
1097                        lsp_store.wait_for_remote_buffer(buffer_id, cx)
1098                    })
1099                    .await?;
1100                let start = origin
1101                    .start
1102                    .and_then(deserialize_anchor)
1103                    .context("missing origin start")?;
1104                let end = origin
1105                    .end
1106                    .and_then(deserialize_anchor)
1107                    .context("missing origin end")?;
1108                buffer
1109                    .update(cx, |buffer, _| buffer.wait_for_anchors([start, end]))
1110                    .await?;
1111                Some(Location {
1112                    buffer,
1113                    range: start..end,
1114                })
1115            }
1116            None => None,
1117        };
1118
1119        let target = link.target.context("missing target")?;
1120        let buffer_id = BufferId::new(target.buffer_id)?;
1121        let buffer = lsp_store
1122            .update(cx, |lsp_store, cx| {
1123                lsp_store.wait_for_remote_buffer(buffer_id, cx)
1124            })
1125            .await?;
1126        let start = target
1127            .start
1128            .and_then(deserialize_anchor)
1129            .context("missing target start")?;
1130        let end = target
1131            .end
1132            .and_then(deserialize_anchor)
1133            .context("missing target end")?;
1134        buffer
1135            .update(cx, |buffer, _| buffer.wait_for_anchors([start, end]))
1136            .await?;
1137        let target = Location {
1138            buffer,
1139            range: start..end,
1140        };
1141        Ok(LocationLink { origin, target })
1142    })
1143}
1144
1145pub async fn location_links_from_lsp(
1146    message: Option<lsp::GotoDefinitionResponse>,
1147    lsp_store: Entity<LspStore>,
1148    buffer: Entity<Buffer>,
1149    server_id: LanguageServerId,
1150    mut cx: AsyncApp,
1151) -> Result<Vec<LocationLink>> {
1152    let message = match message {
1153        Some(message) => message,
1154        None => return Ok(Vec::new()),
1155    };
1156
1157    let mut unresolved_links = Vec::new();
1158    match message {
1159        lsp::GotoDefinitionResponse::Scalar(loc) => {
1160            unresolved_links.push((None, loc.uri, loc.range));
1161        }
1162
1163        lsp::GotoDefinitionResponse::Array(locs) => {
1164            unresolved_links.extend(locs.into_iter().map(|l| (None, l.uri, l.range)));
1165        }
1166
1167        lsp::GotoDefinitionResponse::Link(links) => {
1168            unresolved_links.extend(links.into_iter().map(|l| {
1169                (
1170                    l.origin_selection_range,
1171                    l.target_uri,
1172                    l.target_selection_range,
1173                )
1174            }));
1175        }
1176    }
1177
1178    let (_, language_server) = language_server_for_buffer(&lsp_store, &buffer, server_id, &mut cx)?;
1179    let mut definitions = Vec::new();
1180    for (origin_range, target_uri, target_range) in unresolved_links {
1181        let target_buffer_handle = lsp_store
1182            .update(&mut cx, |this, cx| {
1183                this.open_local_buffer_via_lsp(target_uri, language_server.server_id(), cx)
1184            })
1185            .await?;
1186
1187        cx.update(|cx| {
1188            let origin_location = origin_range.map(|origin_range| {
1189                let origin_buffer = buffer.read(cx);
1190                let origin_start =
1191                    origin_buffer.clip_point_utf16(point_from_lsp(origin_range.start), Bias::Left);
1192                let origin_end =
1193                    origin_buffer.clip_point_utf16(point_from_lsp(origin_range.end), Bias::Left);
1194                Location {
1195                    buffer: buffer.clone(),
1196                    range: origin_buffer.anchor_after(origin_start)
1197                        ..origin_buffer.anchor_before(origin_end),
1198                }
1199            });
1200
1201            let target_buffer = target_buffer_handle.read(cx);
1202            let target_start =
1203                target_buffer.clip_point_utf16(point_from_lsp(target_range.start), Bias::Left);
1204            let target_end =
1205                target_buffer.clip_point_utf16(point_from_lsp(target_range.end), Bias::Left);
1206            let target_location = Location {
1207                buffer: target_buffer_handle,
1208                range: target_buffer.anchor_after(target_start)
1209                    ..target_buffer.anchor_before(target_end),
1210            };
1211
1212            definitions.push(LocationLink {
1213                origin: origin_location,
1214                target: target_location,
1215            })
1216        });
1217    }
1218    Ok(definitions)
1219}
1220
1221pub async fn location_link_from_lsp(
1222    link: lsp::LocationLink,
1223    lsp_store: &Entity<LspStore>,
1224    buffer: &Entity<Buffer>,
1225    server_id: LanguageServerId,
1226    cx: &mut AsyncApp,
1227) -> Result<LocationLink> {
1228    let (_, language_server) = language_server_for_buffer(lsp_store, buffer, server_id, cx)?;
1229
1230    let (origin_range, target_uri, target_range) = (
1231        link.origin_selection_range,
1232        link.target_uri,
1233        link.target_selection_range,
1234    );
1235
1236    let target_buffer_handle = lsp_store
1237        .update(cx, |lsp_store, cx| {
1238            lsp_store.open_local_buffer_via_lsp(target_uri, language_server.server_id(), cx)
1239        })
1240        .await?;
1241
1242    Ok(cx.update(|cx| {
1243        let origin_location = origin_range.map(|origin_range| {
1244            let origin_buffer = buffer.read(cx);
1245            let origin_start =
1246                origin_buffer.clip_point_utf16(point_from_lsp(origin_range.start), Bias::Left);
1247            let origin_end =
1248                origin_buffer.clip_point_utf16(point_from_lsp(origin_range.end), Bias::Left);
1249            Location {
1250                buffer: buffer.clone(),
1251                range: origin_buffer.anchor_after(origin_start)
1252                    ..origin_buffer.anchor_before(origin_end),
1253            }
1254        });
1255
1256        let target_buffer = target_buffer_handle.read(cx);
1257        let target_start =
1258            target_buffer.clip_point_utf16(point_from_lsp(target_range.start), Bias::Left);
1259        let target_end =
1260            target_buffer.clip_point_utf16(point_from_lsp(target_range.end), Bias::Left);
1261        let target_location = Location {
1262            buffer: target_buffer_handle,
1263            range: target_buffer.anchor_after(target_start)
1264                ..target_buffer.anchor_before(target_end),
1265        };
1266
1267        LocationLink {
1268            origin: origin_location,
1269            target: target_location,
1270        }
1271    }))
1272}
1273
1274pub fn location_links_to_proto(
1275    links: Vec<LocationLink>,
1276    lsp_store: &mut LspStore,
1277    peer_id: PeerId,
1278    cx: &mut App,
1279) -> Vec<proto::LocationLink> {
1280    links
1281        .into_iter()
1282        .map(|definition| location_link_to_proto(definition, lsp_store, peer_id, cx))
1283        .collect()
1284}
1285
1286pub fn location_link_to_proto(
1287    location: LocationLink,
1288    lsp_store: &mut LspStore,
1289    peer_id: PeerId,
1290    cx: &mut App,
1291) -> proto::LocationLink {
1292    let origin = location.origin.map(|origin| {
1293        lsp_store
1294            .buffer_store()
1295            .update(cx, |buffer_store, cx| {
1296                buffer_store.create_buffer_for_peer(&origin.buffer, peer_id, cx)
1297            })
1298            .detach_and_log_err(cx);
1299
1300        let buffer_id = origin.buffer.read(cx).remote_id().into();
1301        proto::Location {
1302            start: Some(serialize_anchor(&origin.range.start)),
1303            end: Some(serialize_anchor(&origin.range.end)),
1304            buffer_id,
1305        }
1306    });
1307
1308    lsp_store
1309        .buffer_store()
1310        .update(cx, |buffer_store, cx| {
1311            buffer_store.create_buffer_for_peer(&location.target.buffer, peer_id, cx)
1312        })
1313        .detach_and_log_err(cx);
1314
1315    let buffer_id = location.target.buffer.read(cx).remote_id().into();
1316    let target = proto::Location {
1317        start: Some(serialize_anchor(&location.target.range.start)),
1318        end: Some(serialize_anchor(&location.target.range.end)),
1319        buffer_id,
1320    };
1321
1322    proto::LocationLink {
1323        origin,
1324        target: Some(target),
1325    }
1326}
1327
1328#[async_trait(?Send)]
1329impl LspCommand for GetReferences {
1330    type Response = Vec<Location>;
1331    type LspRequest = lsp::request::References;
1332    type ProtoRequest = proto::GetReferences;
1333
1334    fn display_name(&self) -> &str {
1335        "Find all references"
1336    }
1337
1338    fn status(&self) -> Option<String> {
1339        Some("Finding references...".to_owned())
1340    }
1341
1342    fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
1343        match &capabilities.server_capabilities.references_provider {
1344            Some(OneOf::Left(has_support)) => *has_support,
1345            Some(OneOf::Right(_)) => true,
1346            None => false,
1347        }
1348    }
1349
1350    fn to_lsp(
1351        &self,
1352        path: &Path,
1353        _: &Buffer,
1354        _: &Arc<LanguageServer>,
1355        _: &App,
1356    ) -> Result<lsp::ReferenceParams> {
1357        Ok(lsp::ReferenceParams {
1358            text_document_position: make_lsp_text_document_position(path, self.position)?,
1359            work_done_progress_params: Default::default(),
1360            partial_result_params: Default::default(),
1361            context: lsp::ReferenceContext {
1362                include_declaration: true,
1363            },
1364        })
1365    }
1366
1367    async fn response_from_lsp(
1368        self,
1369        locations: Option<Vec<lsp::Location>>,
1370        lsp_store: Entity<LspStore>,
1371        buffer: Entity<Buffer>,
1372        server_id: LanguageServerId,
1373        mut cx: AsyncApp,
1374    ) -> Result<Vec<Location>> {
1375        let mut references = Vec::new();
1376        let (_, language_server) =
1377            language_server_for_buffer(&lsp_store, &buffer, server_id, &mut cx)?;
1378
1379        if let Some(locations) = locations {
1380            for lsp_location in locations {
1381                let target_buffer_handle = lsp_store
1382                    .update(&mut cx, |lsp_store, cx| {
1383                        lsp_store.open_local_buffer_via_lsp(
1384                            lsp_location.uri,
1385                            language_server.server_id(),
1386                            cx,
1387                        )
1388                    })
1389                    .await?;
1390
1391                target_buffer_handle
1392                    .clone()
1393                    .read_with(&cx, |target_buffer, _| {
1394                        let target_start = target_buffer
1395                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
1396                        let target_end = target_buffer
1397                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
1398                        references.push(Location {
1399                            buffer: target_buffer_handle,
1400                            range: target_buffer.anchor_after(target_start)
1401                                ..target_buffer.anchor_before(target_end),
1402                        });
1403                    });
1404            }
1405        }
1406
1407        Ok(references)
1408    }
1409
1410    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> proto::GetReferences {
1411        proto::GetReferences {
1412            project_id,
1413            buffer_id: buffer.remote_id().into(),
1414            position: Some(language::proto::serialize_anchor(
1415                &buffer.anchor_before(self.position),
1416            )),
1417            version: serialize_version(&buffer.version()),
1418        }
1419    }
1420
1421    async fn from_proto(
1422        message: proto::GetReferences,
1423        _: Entity<LspStore>,
1424        buffer: Entity<Buffer>,
1425        mut cx: AsyncApp,
1426    ) -> Result<Self> {
1427        let position = message
1428            .position
1429            .and_then(deserialize_anchor)
1430            .context("invalid position")?;
1431        buffer
1432            .update(&mut cx, |buffer, _| {
1433                buffer.wait_for_version(deserialize_version(&message.version))
1434            })
1435            .await?;
1436        Ok(Self {
1437            position: buffer.read_with(&cx, |buffer, _| position.to_point_utf16(buffer)),
1438        })
1439    }
1440
1441    fn response_to_proto(
1442        response: Vec<Location>,
1443        lsp_store: &mut LspStore,
1444        peer_id: PeerId,
1445        _: &clock::Global,
1446        cx: &mut App,
1447    ) -> proto::GetReferencesResponse {
1448        let locations = response
1449            .into_iter()
1450            .map(|definition| {
1451                lsp_store
1452                    .buffer_store()
1453                    .update(cx, |buffer_store, cx| {
1454                        buffer_store.create_buffer_for_peer(&definition.buffer, peer_id, cx)
1455                    })
1456                    .detach_and_log_err(cx);
1457                let buffer_id = definition.buffer.read(cx).remote_id();
1458                proto::Location {
1459                    start: Some(serialize_anchor(&definition.range.start)),
1460                    end: Some(serialize_anchor(&definition.range.end)),
1461                    buffer_id: buffer_id.into(),
1462                }
1463            })
1464            .collect();
1465        proto::GetReferencesResponse { locations }
1466    }
1467
1468    async fn response_from_proto(
1469        self,
1470        message: proto::GetReferencesResponse,
1471        project: Entity<LspStore>,
1472        _: Entity<Buffer>,
1473        mut cx: AsyncApp,
1474    ) -> Result<Vec<Location>> {
1475        let mut locations = Vec::new();
1476        for location in message.locations {
1477            let buffer_id = BufferId::new(location.buffer_id)?;
1478            let target_buffer = project
1479                .update(&mut cx, |this, cx| {
1480                    this.wait_for_remote_buffer(buffer_id, cx)
1481                })
1482                .await?;
1483            let start = location
1484                .start
1485                .and_then(deserialize_anchor)
1486                .context("missing target start")?;
1487            let end = location
1488                .end
1489                .and_then(deserialize_anchor)
1490                .context("missing target end")?;
1491            target_buffer
1492                .update(&mut cx, |buffer, _| buffer.wait_for_anchors([start, end]))
1493                .await?;
1494            locations.push(Location {
1495                buffer: target_buffer,
1496                range: start..end,
1497            })
1498        }
1499        Ok(locations)
1500    }
1501
1502    fn buffer_id_from_proto(message: &proto::GetReferences) -> Result<BufferId> {
1503        BufferId::new(message.buffer_id)
1504    }
1505}
1506
1507#[async_trait(?Send)]
1508impl LspCommand for GetDocumentHighlights {
1509    type Response = Vec<DocumentHighlight>;
1510    type LspRequest = lsp::request::DocumentHighlightRequest;
1511    type ProtoRequest = proto::GetDocumentHighlights;
1512
1513    fn display_name(&self) -> &str {
1514        "Get document highlights"
1515    }
1516
1517    fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
1518        capabilities
1519            .server_capabilities
1520            .document_highlight_provider
1521            .is_some_and(|capability| match capability {
1522                OneOf::Left(supported) => supported,
1523                OneOf::Right(_options) => true,
1524            })
1525    }
1526
1527    fn to_lsp(
1528        &self,
1529        path: &Path,
1530        _: &Buffer,
1531        _: &Arc<LanguageServer>,
1532        _: &App,
1533    ) -> Result<lsp::DocumentHighlightParams> {
1534        Ok(lsp::DocumentHighlightParams {
1535            text_document_position_params: make_lsp_text_document_position(path, self.position)?,
1536            work_done_progress_params: Default::default(),
1537            partial_result_params: Default::default(),
1538        })
1539    }
1540
1541    async fn response_from_lsp(
1542        self,
1543        lsp_highlights: Option<Vec<lsp::DocumentHighlight>>,
1544        _: Entity<LspStore>,
1545        buffer: Entity<Buffer>,
1546        _: LanguageServerId,
1547        cx: AsyncApp,
1548    ) -> Result<Vec<DocumentHighlight>> {
1549        Ok(buffer.read_with(&cx, |buffer, _| {
1550            let mut lsp_highlights = lsp_highlights.unwrap_or_default();
1551            lsp_highlights.sort_unstable_by_key(|h| (h.range.start, Reverse(h.range.end)));
1552            lsp_highlights
1553                .into_iter()
1554                .map(|lsp_highlight| {
1555                    let start = buffer
1556                        .clip_point_utf16(point_from_lsp(lsp_highlight.range.start), Bias::Left);
1557                    let end = buffer
1558                        .clip_point_utf16(point_from_lsp(lsp_highlight.range.end), Bias::Left);
1559                    DocumentHighlight {
1560                        range: buffer.anchor_after(start)..buffer.anchor_before(end),
1561                        kind: lsp_highlight
1562                            .kind
1563                            .unwrap_or(lsp::DocumentHighlightKind::READ),
1564                    }
1565                })
1566                .collect()
1567        }))
1568    }
1569
1570    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> proto::GetDocumentHighlights {
1571        proto::GetDocumentHighlights {
1572            project_id,
1573            buffer_id: buffer.remote_id().into(),
1574            position: Some(language::proto::serialize_anchor(
1575                &buffer.anchor_before(self.position),
1576            )),
1577            version: serialize_version(&buffer.version()),
1578        }
1579    }
1580
1581    async fn from_proto(
1582        message: proto::GetDocumentHighlights,
1583        _: Entity<LspStore>,
1584        buffer: Entity<Buffer>,
1585        mut cx: AsyncApp,
1586    ) -> Result<Self> {
1587        let position = message
1588            .position
1589            .and_then(deserialize_anchor)
1590            .context("invalid position")?;
1591        buffer
1592            .update(&mut cx, |buffer, _| {
1593                buffer.wait_for_version(deserialize_version(&message.version))
1594            })
1595            .await?;
1596        Ok(Self {
1597            position: buffer.read_with(&cx, |buffer, _| position.to_point_utf16(buffer)),
1598        })
1599    }
1600
1601    fn response_to_proto(
1602        response: Vec<DocumentHighlight>,
1603        _: &mut LspStore,
1604        _: PeerId,
1605        _: &clock::Global,
1606        _: &mut App,
1607    ) -> proto::GetDocumentHighlightsResponse {
1608        let highlights = response
1609            .into_iter()
1610            .map(|highlight| proto::DocumentHighlight {
1611                start: Some(serialize_anchor(&highlight.range.start)),
1612                end: Some(serialize_anchor(&highlight.range.end)),
1613                kind: match highlight.kind {
1614                    DocumentHighlightKind::TEXT => proto::document_highlight::Kind::Text.into(),
1615                    DocumentHighlightKind::WRITE => proto::document_highlight::Kind::Write.into(),
1616                    DocumentHighlightKind::READ => proto::document_highlight::Kind::Read.into(),
1617                    _ => proto::document_highlight::Kind::Text.into(),
1618                },
1619            })
1620            .collect();
1621        proto::GetDocumentHighlightsResponse { highlights }
1622    }
1623
1624    async fn response_from_proto(
1625        self,
1626        message: proto::GetDocumentHighlightsResponse,
1627        _: Entity<LspStore>,
1628        buffer: Entity<Buffer>,
1629        mut cx: AsyncApp,
1630    ) -> Result<Vec<DocumentHighlight>> {
1631        let mut highlights = Vec::new();
1632        for highlight in message.highlights {
1633            let start = highlight
1634                .start
1635                .and_then(deserialize_anchor)
1636                .context("missing target start")?;
1637            let end = highlight
1638                .end
1639                .and_then(deserialize_anchor)
1640                .context("missing target end")?;
1641            buffer
1642                .update(&mut cx, |buffer, _| buffer.wait_for_anchors([start, end]))
1643                .await?;
1644            let kind = match proto::document_highlight::Kind::from_i32(highlight.kind) {
1645                Some(proto::document_highlight::Kind::Text) => DocumentHighlightKind::TEXT,
1646                Some(proto::document_highlight::Kind::Read) => DocumentHighlightKind::READ,
1647                Some(proto::document_highlight::Kind::Write) => DocumentHighlightKind::WRITE,
1648                None => DocumentHighlightKind::TEXT,
1649            };
1650            highlights.push(DocumentHighlight {
1651                range: start..end,
1652                kind,
1653            });
1654        }
1655        Ok(highlights)
1656    }
1657
1658    fn buffer_id_from_proto(message: &proto::GetDocumentHighlights) -> Result<BufferId> {
1659        BufferId::new(message.buffer_id)
1660    }
1661}
1662
1663#[async_trait(?Send)]
1664impl LspCommand for GetDocumentSymbols {
1665    type Response = Vec<DocumentSymbol>;
1666    type LspRequest = lsp::request::DocumentSymbolRequest;
1667    type ProtoRequest = proto::GetDocumentSymbols;
1668
1669    fn display_name(&self) -> &str {
1670        "Get document symbols"
1671    }
1672
1673    fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
1674        capabilities
1675            .server_capabilities
1676            .document_symbol_provider
1677            .is_some_and(|capability| match capability {
1678                OneOf::Left(supported) => supported,
1679                OneOf::Right(_options) => true,
1680            })
1681    }
1682
1683    fn to_lsp(
1684        &self,
1685        path: &Path,
1686        _: &Buffer,
1687        _: &Arc<LanguageServer>,
1688        _: &App,
1689    ) -> Result<lsp::DocumentSymbolParams> {
1690        Ok(lsp::DocumentSymbolParams {
1691            text_document: make_text_document_identifier(path)?,
1692            work_done_progress_params: Default::default(),
1693            partial_result_params: Default::default(),
1694        })
1695    }
1696
1697    async fn response_from_lsp(
1698        self,
1699        lsp_symbols: Option<lsp::DocumentSymbolResponse>,
1700        _: Entity<LspStore>,
1701        _: Entity<Buffer>,
1702        _: LanguageServerId,
1703        _: AsyncApp,
1704    ) -> Result<Vec<DocumentSymbol>> {
1705        let Some(lsp_symbols) = lsp_symbols else {
1706            return Ok(Vec::new());
1707        };
1708
1709        let symbols = match lsp_symbols {
1710            lsp::DocumentSymbolResponse::Flat(symbol_information) => symbol_information
1711                .into_iter()
1712                .map(|lsp_symbol| DocumentSymbol {
1713                    name: lsp_symbol.name,
1714                    kind: lsp_symbol.kind,
1715                    range: range_from_lsp(lsp_symbol.location.range),
1716                    selection_range: range_from_lsp(lsp_symbol.location.range),
1717                    children: Vec::new(),
1718                })
1719                .collect(),
1720            lsp::DocumentSymbolResponse::Nested(nested_responses) => {
1721                fn convert_symbol(lsp_symbol: lsp::DocumentSymbol) -> DocumentSymbol {
1722                    DocumentSymbol {
1723                        name: lsp_symbol.name,
1724                        kind: lsp_symbol.kind,
1725                        range: range_from_lsp(lsp_symbol.range),
1726                        selection_range: range_from_lsp(lsp_symbol.selection_range),
1727                        children: lsp_symbol
1728                            .children
1729                            .map(|children| {
1730                                children.into_iter().map(convert_symbol).collect::<Vec<_>>()
1731                            })
1732                            .unwrap_or_default(),
1733                    }
1734                }
1735                nested_responses.into_iter().map(convert_symbol).collect()
1736            }
1737        };
1738        Ok(symbols)
1739    }
1740
1741    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> proto::GetDocumentSymbols {
1742        proto::GetDocumentSymbols {
1743            project_id,
1744            buffer_id: buffer.remote_id().into(),
1745            version: serialize_version(&buffer.version()),
1746        }
1747    }
1748
1749    async fn from_proto(
1750        message: proto::GetDocumentSymbols,
1751        _: Entity<LspStore>,
1752        buffer: Entity<Buffer>,
1753        mut cx: AsyncApp,
1754    ) -> Result<Self> {
1755        buffer
1756            .update(&mut cx, |buffer, _| {
1757                buffer.wait_for_version(deserialize_version(&message.version))
1758            })
1759            .await?;
1760        Ok(Self)
1761    }
1762
1763    fn response_to_proto(
1764        response: Vec<DocumentSymbol>,
1765        _: &mut LspStore,
1766        _: PeerId,
1767        _: &clock::Global,
1768        _: &mut App,
1769    ) -> proto::GetDocumentSymbolsResponse {
1770        let symbols = response
1771            .into_iter()
1772            .map(|symbol| {
1773                fn convert_symbol_to_proto(symbol: DocumentSymbol) -> proto::DocumentSymbol {
1774                    proto::DocumentSymbol {
1775                        name: symbol.name.clone(),
1776                        kind: unsafe { mem::transmute::<lsp::SymbolKind, i32>(symbol.kind) },
1777                        start: Some(proto::PointUtf16 {
1778                            row: symbol.range.start.0.row,
1779                            column: symbol.range.start.0.column,
1780                        }),
1781                        end: Some(proto::PointUtf16 {
1782                            row: symbol.range.end.0.row,
1783                            column: symbol.range.end.0.column,
1784                        }),
1785                        selection_start: Some(proto::PointUtf16 {
1786                            row: symbol.selection_range.start.0.row,
1787                            column: symbol.selection_range.start.0.column,
1788                        }),
1789                        selection_end: Some(proto::PointUtf16 {
1790                            row: symbol.selection_range.end.0.row,
1791                            column: symbol.selection_range.end.0.column,
1792                        }),
1793                        children: symbol
1794                            .children
1795                            .into_iter()
1796                            .map(convert_symbol_to_proto)
1797                            .collect(),
1798                    }
1799                }
1800                convert_symbol_to_proto(symbol)
1801            })
1802            .collect::<Vec<_>>();
1803
1804        proto::GetDocumentSymbolsResponse { symbols }
1805    }
1806
1807    async fn response_from_proto(
1808        self,
1809        message: proto::GetDocumentSymbolsResponse,
1810        _: Entity<LspStore>,
1811        _: Entity<Buffer>,
1812        _: AsyncApp,
1813    ) -> Result<Vec<DocumentSymbol>> {
1814        let mut symbols = Vec::with_capacity(message.symbols.len());
1815        for serialized_symbol in message.symbols {
1816            fn deserialize_symbol_with_children(
1817                serialized_symbol: proto::DocumentSymbol,
1818            ) -> Result<DocumentSymbol> {
1819                let kind =
1820                    unsafe { mem::transmute::<i32, lsp::SymbolKind>(serialized_symbol.kind) };
1821
1822                let start = serialized_symbol.start.context("invalid start")?;
1823                let end = serialized_symbol.end.context("invalid end")?;
1824
1825                let selection_start = serialized_symbol
1826                    .selection_start
1827                    .context("invalid selection start")?;
1828                let selection_end = serialized_symbol
1829                    .selection_end
1830                    .context("invalid selection end")?;
1831
1832                Ok(DocumentSymbol {
1833                    name: serialized_symbol.name,
1834                    kind,
1835                    range: Unclipped(PointUtf16::new(start.row, start.column))
1836                        ..Unclipped(PointUtf16::new(end.row, end.column)),
1837                    selection_range: Unclipped(PointUtf16::new(
1838                        selection_start.row,
1839                        selection_start.column,
1840                    ))
1841                        ..Unclipped(PointUtf16::new(selection_end.row, selection_end.column)),
1842                    children: serialized_symbol
1843                        .children
1844                        .into_iter()
1845                        .filter_map(|symbol| deserialize_symbol_with_children(symbol).ok())
1846                        .collect::<Vec<_>>(),
1847                })
1848            }
1849
1850            symbols.push(deserialize_symbol_with_children(serialized_symbol)?);
1851        }
1852
1853        Ok(symbols)
1854    }
1855
1856    fn buffer_id_from_proto(message: &proto::GetDocumentSymbols) -> Result<BufferId> {
1857        BufferId::new(message.buffer_id)
1858    }
1859}
1860
1861#[async_trait(?Send)]
1862impl LspCommand for GetSignatureHelp {
1863    type Response = Option<SignatureHelp>;
1864    type LspRequest = lsp::SignatureHelpRequest;
1865    type ProtoRequest = proto::GetSignatureHelp;
1866
1867    fn display_name(&self) -> &str {
1868        "Get signature help"
1869    }
1870
1871    fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
1872        capabilities
1873            .server_capabilities
1874            .signature_help_provider
1875            .is_some()
1876    }
1877
1878    fn to_lsp(
1879        &self,
1880        path: &Path,
1881        _: &Buffer,
1882        _: &Arc<LanguageServer>,
1883        _cx: &App,
1884    ) -> Result<lsp::SignatureHelpParams> {
1885        Ok(lsp::SignatureHelpParams {
1886            text_document_position_params: make_lsp_text_document_position(path, self.position)?,
1887            context: None,
1888            work_done_progress_params: Default::default(),
1889        })
1890    }
1891
1892    async fn response_from_lsp(
1893        self,
1894        message: Option<lsp::SignatureHelp>,
1895        lsp_store: Entity<LspStore>,
1896        _: Entity<Buffer>,
1897        id: LanguageServerId,
1898        cx: AsyncApp,
1899    ) -> Result<Self::Response> {
1900        let Some(message) = message else {
1901            return Ok(None);
1902        };
1903        Ok(cx.update(|cx| {
1904            SignatureHelp::new(
1905                message,
1906                Some(lsp_store.read(cx).languages.clone()),
1907                Some(id),
1908                cx,
1909            )
1910        }))
1911    }
1912
1913    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> Self::ProtoRequest {
1914        let offset = buffer.point_utf16_to_offset(self.position);
1915        proto::GetSignatureHelp {
1916            project_id,
1917            buffer_id: buffer.remote_id().to_proto(),
1918            position: Some(serialize_anchor(&buffer.anchor_after(offset))),
1919            version: serialize_version(&buffer.version()),
1920        }
1921    }
1922
1923    async fn from_proto(
1924        payload: Self::ProtoRequest,
1925        _: Entity<LspStore>,
1926        buffer: Entity<Buffer>,
1927        mut cx: AsyncApp,
1928    ) -> Result<Self> {
1929        buffer
1930            .update(&mut cx, |buffer, _| {
1931                buffer.wait_for_version(deserialize_version(&payload.version))
1932            })
1933            .await
1934            .with_context(|| format!("waiting for version for buffer {}", buffer.entity_id()))?;
1935        let buffer_snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
1936        Ok(Self {
1937            position: payload
1938                .position
1939                .and_then(deserialize_anchor)
1940                .context("invalid position")?
1941                .to_point_utf16(&buffer_snapshot),
1942        })
1943    }
1944
1945    fn response_to_proto(
1946        response: Self::Response,
1947        _: &mut LspStore,
1948        _: PeerId,
1949        _: &Global,
1950        _: &mut App,
1951    ) -> proto::GetSignatureHelpResponse {
1952        proto::GetSignatureHelpResponse {
1953            signature_help: response
1954                .map(|signature_help| lsp_to_proto_signature(signature_help.original_data)),
1955        }
1956    }
1957
1958    async fn response_from_proto(
1959        self,
1960        response: proto::GetSignatureHelpResponse,
1961        lsp_store: Entity<LspStore>,
1962        _: Entity<Buffer>,
1963        cx: AsyncApp,
1964    ) -> Result<Self::Response> {
1965        Ok(cx.update(|cx| {
1966            response
1967                .signature_help
1968                .map(proto_to_lsp_signature)
1969                .and_then(|signature| {
1970                    SignatureHelp::new(
1971                        signature,
1972                        Some(lsp_store.read(cx).languages.clone()),
1973                        None,
1974                        cx,
1975                    )
1976                })
1977        }))
1978    }
1979
1980    fn buffer_id_from_proto(message: &Self::ProtoRequest) -> Result<BufferId> {
1981        BufferId::new(message.buffer_id)
1982    }
1983}
1984
1985#[async_trait(?Send)]
1986impl LspCommand for GetHover {
1987    type Response = Option<Hover>;
1988    type LspRequest = lsp::request::HoverRequest;
1989    type ProtoRequest = proto::GetHover;
1990
1991    fn display_name(&self) -> &str {
1992        "Get hover"
1993    }
1994
1995    fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
1996        match capabilities.server_capabilities.hover_provider {
1997            Some(lsp::HoverProviderCapability::Simple(enabled)) => enabled,
1998            Some(lsp::HoverProviderCapability::Options(_)) => true,
1999            None => false,
2000        }
2001    }
2002
2003    fn to_lsp(
2004        &self,
2005        path: &Path,
2006        _: &Buffer,
2007        _: &Arc<LanguageServer>,
2008        _: &App,
2009    ) -> Result<lsp::HoverParams> {
2010        Ok(lsp::HoverParams {
2011            text_document_position_params: make_lsp_text_document_position(path, self.position)?,
2012            work_done_progress_params: Default::default(),
2013        })
2014    }
2015
2016    async fn response_from_lsp(
2017        self,
2018        message: Option<lsp::Hover>,
2019        _: Entity<LspStore>,
2020        buffer: Entity<Buffer>,
2021        _: LanguageServerId,
2022        cx: AsyncApp,
2023    ) -> Result<Self::Response> {
2024        let Some(hover) = message else {
2025            return Ok(None);
2026        };
2027
2028        let (language, range) = buffer.read_with(&cx, |buffer, _| {
2029            (
2030                buffer.language().cloned(),
2031                hover.range.map(|range| {
2032                    let token_start =
2033                        buffer.clip_point_utf16(point_from_lsp(range.start), Bias::Left);
2034                    let token_end = buffer.clip_point_utf16(point_from_lsp(range.end), Bias::Left);
2035                    buffer.anchor_after(token_start)..buffer.anchor_before(token_end)
2036                }),
2037            )
2038        });
2039
2040        fn hover_blocks_from_marked_string(marked_string: lsp::MarkedString) -> Option<HoverBlock> {
2041            let block = match marked_string {
2042                lsp::MarkedString::String(content) => HoverBlock {
2043                    text: content,
2044                    kind: HoverBlockKind::Markdown,
2045                },
2046                lsp::MarkedString::LanguageString(lsp::LanguageString { language, value }) => {
2047                    HoverBlock {
2048                        text: value,
2049                        kind: HoverBlockKind::Code { language },
2050                    }
2051                }
2052            };
2053            if block.text.is_empty() {
2054                None
2055            } else {
2056                Some(block)
2057            }
2058        }
2059
2060        let contents = match hover.contents {
2061            lsp::HoverContents::Scalar(marked_string) => {
2062                hover_blocks_from_marked_string(marked_string)
2063                    .into_iter()
2064                    .collect()
2065            }
2066            lsp::HoverContents::Array(marked_strings) => marked_strings
2067                .into_iter()
2068                .filter_map(hover_blocks_from_marked_string)
2069                .collect(),
2070            lsp::HoverContents::Markup(markup_content) => vec![HoverBlock {
2071                text: markup_content.value,
2072                kind: if markup_content.kind == lsp::MarkupKind::Markdown {
2073                    HoverBlockKind::Markdown
2074                } else {
2075                    HoverBlockKind::PlainText
2076                },
2077            }],
2078        };
2079
2080        Ok(Some(Hover {
2081            contents,
2082            range,
2083            language,
2084        }))
2085    }
2086
2087    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> Self::ProtoRequest {
2088        proto::GetHover {
2089            project_id,
2090            buffer_id: buffer.remote_id().into(),
2091            position: Some(language::proto::serialize_anchor(
2092                &buffer.anchor_before(self.position),
2093            )),
2094            version: serialize_version(&buffer.version),
2095        }
2096    }
2097
2098    async fn from_proto(
2099        message: Self::ProtoRequest,
2100        _: Entity<LspStore>,
2101        buffer: Entity<Buffer>,
2102        mut cx: AsyncApp,
2103    ) -> Result<Self> {
2104        let position = message
2105            .position
2106            .and_then(deserialize_anchor)
2107            .context("invalid position")?;
2108        buffer
2109            .update(&mut cx, |buffer, _| {
2110                buffer.wait_for_version(deserialize_version(&message.version))
2111            })
2112            .await?;
2113        Ok(Self {
2114            position: buffer.read_with(&cx, |buffer, _| position.to_point_utf16(buffer)),
2115        })
2116    }
2117
2118    fn response_to_proto(
2119        response: Self::Response,
2120        _: &mut LspStore,
2121        _: PeerId,
2122        _: &clock::Global,
2123        _: &mut App,
2124    ) -> proto::GetHoverResponse {
2125        if let Some(response) = response {
2126            let (start, end) = if let Some(range) = response.range {
2127                (
2128                    Some(language::proto::serialize_anchor(&range.start)),
2129                    Some(language::proto::serialize_anchor(&range.end)),
2130                )
2131            } else {
2132                (None, None)
2133            };
2134
2135            let contents = response
2136                .contents
2137                .into_iter()
2138                .map(|block| proto::HoverBlock {
2139                    text: block.text,
2140                    is_markdown: block.kind == HoverBlockKind::Markdown,
2141                    language: if let HoverBlockKind::Code { language } = block.kind {
2142                        Some(language)
2143                    } else {
2144                        None
2145                    },
2146                })
2147                .collect();
2148
2149            proto::GetHoverResponse {
2150                start,
2151                end,
2152                contents,
2153            }
2154        } else {
2155            proto::GetHoverResponse {
2156                start: None,
2157                end: None,
2158                contents: Vec::new(),
2159            }
2160        }
2161    }
2162
2163    async fn response_from_proto(
2164        self,
2165        message: proto::GetHoverResponse,
2166        _: Entity<LspStore>,
2167        buffer: Entity<Buffer>,
2168        mut cx: AsyncApp,
2169    ) -> Result<Self::Response> {
2170        let contents: Vec<_> = message
2171            .contents
2172            .into_iter()
2173            .map(|block| HoverBlock {
2174                text: block.text,
2175                kind: if let Some(language) = block.language {
2176                    HoverBlockKind::Code { language }
2177                } else if block.is_markdown {
2178                    HoverBlockKind::Markdown
2179                } else {
2180                    HoverBlockKind::PlainText
2181                },
2182            })
2183            .collect();
2184        if contents.is_empty() {
2185            return Ok(None);
2186        }
2187
2188        let language = buffer.read_with(&cx, |buffer, _| buffer.language().cloned());
2189        let range = if let (Some(start), Some(end)) = (message.start, message.end) {
2190            language::proto::deserialize_anchor(start)
2191                .and_then(|start| language::proto::deserialize_anchor(end).map(|end| start..end))
2192        } else {
2193            None
2194        };
2195        if let Some(range) = range.as_ref() {
2196            buffer
2197                .update(&mut cx, |buffer, _| {
2198                    buffer.wait_for_anchors([range.start, range.end])
2199                })
2200                .await?;
2201        }
2202
2203        Ok(Some(Hover {
2204            contents,
2205            range,
2206            language,
2207        }))
2208    }
2209
2210    fn buffer_id_from_proto(message: &Self::ProtoRequest) -> Result<BufferId> {
2211        BufferId::new(message.buffer_id)
2212    }
2213}
2214
2215impl GetCompletions {
2216    pub fn can_resolve_completions(capabilities: &lsp::ServerCapabilities) -> bool {
2217        capabilities
2218            .completion_provider
2219            .as_ref()
2220            .and_then(|options| options.resolve_provider)
2221            .unwrap_or(false)
2222    }
2223}
2224
2225#[async_trait(?Send)]
2226impl LspCommand for GetCompletions {
2227    type Response = CoreCompletionResponse;
2228    type LspRequest = lsp::request::Completion;
2229    type ProtoRequest = proto::GetCompletions;
2230
2231    fn display_name(&self) -> &str {
2232        "Get completion"
2233    }
2234
2235    fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
2236        capabilities
2237            .server_capabilities
2238            .completion_provider
2239            .is_some()
2240    }
2241
2242    fn to_lsp(
2243        &self,
2244        path: &Path,
2245        _: &Buffer,
2246        _: &Arc<LanguageServer>,
2247        _: &App,
2248    ) -> Result<lsp::CompletionParams> {
2249        Ok(lsp::CompletionParams {
2250            text_document_position: make_lsp_text_document_position(path, self.position)?,
2251            context: Some(self.context.clone()),
2252            work_done_progress_params: Default::default(),
2253            partial_result_params: Default::default(),
2254        })
2255    }
2256
2257    async fn response_from_lsp(
2258        self,
2259        completions: Option<lsp::CompletionResponse>,
2260        lsp_store: Entity<LspStore>,
2261        buffer: Entity<Buffer>,
2262        server_id: LanguageServerId,
2263        mut cx: AsyncApp,
2264    ) -> Result<Self::Response> {
2265        let mut response_list = None;
2266        let (mut completions, mut is_incomplete) = if let Some(completions) = completions {
2267            match completions {
2268                lsp::CompletionResponse::Array(completions) => (completions, false),
2269                lsp::CompletionResponse::List(mut list) => {
2270                    let is_incomplete = list.is_incomplete;
2271                    let items = std::mem::take(&mut list.items);
2272                    response_list = Some(list);
2273                    (items, is_incomplete)
2274                }
2275            }
2276        } else {
2277            (Vec::new(), false)
2278        };
2279
2280        let unfiltered_completions_count = completions.len();
2281
2282        let language_server_adapter = lsp_store
2283            .read_with(&cx, |lsp_store, _| {
2284                lsp_store.language_server_adapter_for_id(server_id)
2285            })
2286            .with_context(|| format!("no language server with id {server_id}"))?;
2287
2288        let lsp_defaults = response_list
2289            .as_ref()
2290            .and_then(|list| list.item_defaults.clone())
2291            .map(Arc::new);
2292
2293        let mut completion_edits = Vec::new();
2294        buffer.update(&mut cx, |buffer, _cx| {
2295            let snapshot = buffer.snapshot();
2296            let clipped_position = buffer.clip_point_utf16(Unclipped(self.position), Bias::Left);
2297
2298            let mut range_for_token = None;
2299            completions.retain(|lsp_completion| {
2300                let lsp_edit = lsp_completion.text_edit.clone().or_else(|| {
2301                    let default_text_edit = lsp_defaults.as_deref()?.edit_range.as_ref()?;
2302                    let new_text = lsp_completion
2303                        .text_edit_text
2304                        .as_ref()
2305                        .unwrap_or(&lsp_completion.label)
2306                        .clone();
2307                    match default_text_edit {
2308                        CompletionListItemDefaultsEditRange::Range(range) => {
2309                            Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
2310                                range: *range,
2311                                new_text,
2312                            }))
2313                        }
2314                        CompletionListItemDefaultsEditRange::InsertAndReplace {
2315                            insert,
2316                            replace,
2317                        } => Some(lsp::CompletionTextEdit::InsertAndReplace(
2318                            lsp::InsertReplaceEdit {
2319                                new_text,
2320                                insert: *insert,
2321                                replace: *replace,
2322                            },
2323                        )),
2324                    }
2325                });
2326
2327                let edit = match lsp_edit {
2328                    // If the language server provides a range to overwrite, then
2329                    // check that the range is valid.
2330                    Some(completion_text_edit) => {
2331                        match parse_completion_text_edit(&completion_text_edit, &snapshot) {
2332                            Some(edit) => edit,
2333                            None => return false,
2334                        }
2335                    }
2336                    // If the language server does not provide a range, then infer
2337                    // the range based on the syntax tree.
2338                    None => {
2339                        if self.position != clipped_position {
2340                            log::info!("completion out of expected range ");
2341                            return false;
2342                        }
2343
2344                        let default_edit_range = lsp_defaults.as_ref().and_then(|lsp_defaults| {
2345                            lsp_defaults
2346                                .edit_range
2347                                .as_ref()
2348                                .and_then(|range| match range {
2349                                    CompletionListItemDefaultsEditRange::Range(r) => Some(r),
2350                                    _ => None,
2351                                })
2352                        });
2353
2354                        let range = if let Some(range) = default_edit_range {
2355                            let range = range_from_lsp(*range);
2356                            let start = snapshot.clip_point_utf16(range.start, Bias::Left);
2357                            let end = snapshot.clip_point_utf16(range.end, Bias::Left);
2358                            if start != range.start.0 || end != range.end.0 {
2359                                log::info!("completion out of expected range");
2360                                return false;
2361                            }
2362
2363                            snapshot.anchor_before(start)..snapshot.anchor_after(end)
2364                        } else {
2365                            range_for_token
2366                                .get_or_insert_with(|| {
2367                                    let offset = self.position.to_offset(&snapshot);
2368                                    let (range, kind) = snapshot.surrounding_word(
2369                                        offset,
2370                                        Some(CharScopeContext::Completion),
2371                                    );
2372                                    let range = if kind == Some(CharKind::Word) {
2373                                        range
2374                                    } else {
2375                                        offset..offset
2376                                    };
2377
2378                                    snapshot.anchor_before(range.start)
2379                                        ..snapshot.anchor_after(range.end)
2380                                })
2381                                .clone()
2382                        };
2383
2384                        // We already know text_edit is None here
2385                        let text = lsp_completion
2386                            .insert_text
2387                            .as_ref()
2388                            .unwrap_or(&lsp_completion.label)
2389                            .clone();
2390
2391                        ParsedCompletionEdit {
2392                            replace_range: range,
2393                            insert_range: None,
2394                            new_text: text,
2395                        }
2396                    }
2397                };
2398
2399                completion_edits.push(edit);
2400                true
2401            });
2402        });
2403
2404        // If completions were filtered out due to errors that may be transient, mark the result
2405        // incomplete so that it is re-queried.
2406        if unfiltered_completions_count != completions.len() {
2407            is_incomplete = true;
2408        }
2409
2410        language_server_adapter
2411            .process_completions(&mut completions)
2412            .await;
2413
2414        let completions = completions
2415            .into_iter()
2416            .zip(completion_edits)
2417            .map(|(mut lsp_completion, mut edit)| {
2418                LineEnding::normalize(&mut edit.new_text);
2419                if lsp_completion.data.is_none()
2420                    && let Some(default_data) = lsp_defaults
2421                        .as_ref()
2422                        .and_then(|item_defaults| item_defaults.data.clone())
2423                {
2424                    // Servers (e.g. JDTLS) prefer unchanged completions, when resolving the items later,
2425                    // so we do not insert the defaults here, but `data` is needed for resolving, so this is an exception.
2426                    lsp_completion.data = Some(default_data);
2427                }
2428                CoreCompletion {
2429                    replace_range: edit.replace_range,
2430                    new_text: edit.new_text,
2431                    source: CompletionSource::Lsp {
2432                        insert_range: edit.insert_range,
2433                        server_id,
2434                        lsp_completion: Box::new(lsp_completion),
2435                        lsp_defaults: lsp_defaults.clone(),
2436                        resolved: false,
2437                    },
2438                }
2439            })
2440            .collect();
2441
2442        Ok(CoreCompletionResponse {
2443            completions,
2444            is_incomplete,
2445        })
2446    }
2447
2448    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> proto::GetCompletions {
2449        let anchor = buffer.anchor_after(self.position);
2450        proto::GetCompletions {
2451            project_id,
2452            buffer_id: buffer.remote_id().into(),
2453            position: Some(language::proto::serialize_anchor(&anchor)),
2454            version: serialize_version(&buffer.version()),
2455            server_id: self.server_id.map(|id| id.to_proto()),
2456        }
2457    }
2458
2459    async fn from_proto(
2460        message: proto::GetCompletions,
2461        _: Entity<LspStore>,
2462        buffer: Entity<Buffer>,
2463        mut cx: AsyncApp,
2464    ) -> Result<Self> {
2465        let version = deserialize_version(&message.version);
2466        buffer
2467            .update(&mut cx, |buffer, _| buffer.wait_for_version(version))
2468            .await?;
2469        let position = message
2470            .position
2471            .and_then(language::proto::deserialize_anchor)
2472            .map(|p| {
2473                buffer.read_with(&cx, |buffer, _| {
2474                    buffer.clip_point_utf16(Unclipped(p.to_point_utf16(buffer)), Bias::Left)
2475                })
2476            })
2477            .context("invalid position")?;
2478        Ok(Self {
2479            position,
2480            context: CompletionContext {
2481                trigger_kind: CompletionTriggerKind::INVOKED,
2482                trigger_character: None,
2483            },
2484            server_id: message
2485                .server_id
2486                .map(|id| lsp::LanguageServerId::from_proto(id)),
2487        })
2488    }
2489
2490    fn response_to_proto(
2491        response: CoreCompletionResponse,
2492        _: &mut LspStore,
2493        _: PeerId,
2494        buffer_version: &clock::Global,
2495        _: &mut App,
2496    ) -> proto::GetCompletionsResponse {
2497        proto::GetCompletionsResponse {
2498            completions: response
2499                .completions
2500                .iter()
2501                .map(LspStore::serialize_completion)
2502                .collect(),
2503            version: serialize_version(buffer_version),
2504            can_reuse: !response.is_incomplete,
2505        }
2506    }
2507
2508    async fn response_from_proto(
2509        self,
2510        message: proto::GetCompletionsResponse,
2511        _project: Entity<LspStore>,
2512        buffer: Entity<Buffer>,
2513        mut cx: AsyncApp,
2514    ) -> Result<Self::Response> {
2515        buffer
2516            .update(&mut cx, |buffer, _| {
2517                buffer.wait_for_version(deserialize_version(&message.version))
2518            })
2519            .await?;
2520
2521        let completions = message
2522            .completions
2523            .into_iter()
2524            .map(LspStore::deserialize_completion)
2525            .collect::<Result<Vec<_>>>()?;
2526
2527        Ok(CoreCompletionResponse {
2528            completions,
2529            is_incomplete: !message.can_reuse,
2530        })
2531    }
2532
2533    fn buffer_id_from_proto(message: &proto::GetCompletions) -> Result<BufferId> {
2534        BufferId::new(message.buffer_id)
2535    }
2536}
2537
2538pub struct ParsedCompletionEdit {
2539    pub replace_range: Range<Anchor>,
2540    pub insert_range: Option<Range<Anchor>>,
2541    pub new_text: String,
2542}
2543
2544pub(crate) fn parse_completion_text_edit(
2545    edit: &lsp::CompletionTextEdit,
2546    snapshot: &BufferSnapshot,
2547) -> Option<ParsedCompletionEdit> {
2548    let (replace_range, insert_range, new_text) = match edit {
2549        lsp::CompletionTextEdit::Edit(edit) => (edit.range, None, &edit.new_text),
2550        lsp::CompletionTextEdit::InsertAndReplace(edit) => {
2551            (edit.replace, Some(edit.insert), &edit.new_text)
2552        }
2553    };
2554
2555    let replace_range = {
2556        let range = range_from_lsp(replace_range);
2557        let start = snapshot.clip_point_utf16(range.start, Bias::Left);
2558        let end = snapshot.clip_point_utf16(range.end, Bias::Left);
2559        if start != range.start.0 || end != range.end.0 {
2560            log::info!(
2561                "completion out of expected range, start: {start:?}, end: {end:?}, range: {range:?}"
2562            );
2563            return None;
2564        }
2565        snapshot.anchor_before(start)..snapshot.anchor_after(end)
2566    };
2567
2568    let insert_range = match insert_range {
2569        None => None,
2570        Some(insert_range) => {
2571            let range = range_from_lsp(insert_range);
2572            let start = snapshot.clip_point_utf16(range.start, Bias::Left);
2573            let end = snapshot.clip_point_utf16(range.end, Bias::Left);
2574            if start != range.start.0 || end != range.end.0 {
2575                log::info!("completion (insert) out of expected range");
2576                return None;
2577            }
2578            Some(snapshot.anchor_before(start)..snapshot.anchor_after(end))
2579        }
2580    };
2581
2582    Some(ParsedCompletionEdit {
2583        insert_range,
2584        replace_range,
2585        new_text: new_text.clone(),
2586    })
2587}
2588
2589#[async_trait(?Send)]
2590impl LspCommand for GetCodeActions {
2591    type Response = Vec<CodeAction>;
2592    type LspRequest = lsp::request::CodeActionRequest;
2593    type ProtoRequest = proto::GetCodeActions;
2594
2595    fn display_name(&self) -> &str {
2596        "Get code actions"
2597    }
2598
2599    fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
2600        match &capabilities.server_capabilities.code_action_provider {
2601            None => false,
2602            Some(lsp::CodeActionProviderCapability::Simple(false)) => false,
2603            _ => {
2604                // If we do know that we want specific code actions AND we know that
2605                // the server only supports specific code actions, then we want to filter
2606                // down to the ones that are supported.
2607                if let Some((requested, supported)) = self
2608                    .kinds
2609                    .as_ref()
2610                    .zip(Self::supported_code_action_kinds(capabilities))
2611                {
2612                    requested.iter().any(|requested_kind| {
2613                        supported.iter().any(|supported_kind| {
2614                            code_action_kind_matches(requested_kind, supported_kind)
2615                        })
2616                    })
2617                } else {
2618                    true
2619                }
2620            }
2621        }
2622    }
2623
2624    fn to_lsp(
2625        &self,
2626        path: &Path,
2627        buffer: &Buffer,
2628        language_server: &Arc<LanguageServer>,
2629        _: &App,
2630    ) -> Result<lsp::CodeActionParams> {
2631        let mut relevant_diagnostics = Vec::new();
2632        for entry in buffer
2633            .snapshot()
2634            .diagnostics_in_range::<_, language::PointUtf16>(self.range.clone(), false)
2635        {
2636            relevant_diagnostics.push(entry.to_lsp_diagnostic_stub()?);
2637        }
2638
2639        let only = if let Some(requested) = &self.kinds {
2640            if let Some(supported_kinds) =
2641                Self::supported_code_action_kinds(language_server.adapter_server_capabilities())
2642            {
2643                let filtered = requested
2644                    .iter()
2645                    .filter(|requested_kind| {
2646                        supported_kinds.iter().any(|supported_kind| {
2647                            code_action_kind_matches(requested_kind, supported_kind)
2648                        })
2649                    })
2650                    .cloned()
2651                    .collect();
2652                Some(filtered)
2653            } else {
2654                Some(requested.clone())
2655            }
2656        } else {
2657            None
2658        };
2659
2660        Ok(lsp::CodeActionParams {
2661            text_document: make_text_document_identifier(path)?,
2662            range: range_to_lsp(self.range.to_point_utf16(buffer))?,
2663            work_done_progress_params: Default::default(),
2664            partial_result_params: Default::default(),
2665            context: lsp::CodeActionContext {
2666                diagnostics: relevant_diagnostics,
2667                only,
2668                ..lsp::CodeActionContext::default()
2669            },
2670        })
2671    }
2672
2673    async fn response_from_lsp(
2674        self,
2675        actions: Option<lsp::CodeActionResponse>,
2676        lsp_store: Entity<LspStore>,
2677        _: Entity<Buffer>,
2678        server_id: LanguageServerId,
2679        cx: AsyncApp,
2680    ) -> Result<Vec<CodeAction>> {
2681        let requested_kinds = self.kinds.as_ref();
2682
2683        let language_server = cx.update(|cx| {
2684            lsp_store
2685                .read(cx)
2686                .language_server_for_id(server_id)
2687                .with_context(|| {
2688                    format!("Missing the language server that just returned a response {server_id}")
2689                })
2690        })?;
2691
2692        let server_capabilities = language_server.capabilities();
2693        let available_commands = server_capabilities
2694            .execute_command_provider
2695            .as_ref()
2696            .map(|options| options.commands.as_slice())
2697            .unwrap_or_default();
2698        Ok(actions
2699            .unwrap_or_default()
2700            .into_iter()
2701            .filter_map(|entry| {
2702                let (lsp_action, resolved) = match entry {
2703                    lsp::CodeActionOrCommand::CodeAction(lsp_action) => {
2704                        if let Some(command) = lsp_action.command.as_ref()
2705                            && !available_commands.contains(&command.command)
2706                        {
2707                            return None;
2708                        }
2709                        (LspAction::Action(Box::new(lsp_action)), false)
2710                    }
2711                    lsp::CodeActionOrCommand::Command(command) => {
2712                        if available_commands.contains(&command.command) {
2713                            (LspAction::Command(command), true)
2714                        } else {
2715                            return None;
2716                        }
2717                    }
2718                };
2719
2720                if let Some((kinds, kind)) = requested_kinds.zip(lsp_action.action_kind())
2721                    && !kinds
2722                        .iter()
2723                        .any(|requested_kind| code_action_kind_matches(requested_kind, &kind))
2724                {
2725                    return None;
2726                }
2727
2728                Some(CodeAction {
2729                    server_id,
2730                    range: self.range.clone(),
2731                    lsp_action,
2732                    resolved,
2733                })
2734            })
2735            .collect())
2736    }
2737
2738    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> proto::GetCodeActions {
2739        proto::GetCodeActions {
2740            project_id,
2741            buffer_id: buffer.remote_id().into(),
2742            start: Some(language::proto::serialize_anchor(&self.range.start)),
2743            end: Some(language::proto::serialize_anchor(&self.range.end)),
2744            version: serialize_version(&buffer.version()),
2745        }
2746    }
2747
2748    async fn from_proto(
2749        message: proto::GetCodeActions,
2750        _: Entity<LspStore>,
2751        buffer: Entity<Buffer>,
2752        mut cx: AsyncApp,
2753    ) -> Result<Self> {
2754        let start = message
2755            .start
2756            .and_then(language::proto::deserialize_anchor)
2757            .context("invalid start")?;
2758        let end = message
2759            .end
2760            .and_then(language::proto::deserialize_anchor)
2761            .context("invalid end")?;
2762        buffer
2763            .update(&mut cx, |buffer, _| {
2764                buffer.wait_for_version(deserialize_version(&message.version))
2765            })
2766            .await?;
2767
2768        Ok(Self {
2769            range: start..end,
2770            kinds: None,
2771        })
2772    }
2773
2774    fn response_to_proto(
2775        code_actions: Vec<CodeAction>,
2776        _: &mut LspStore,
2777        _: PeerId,
2778        buffer_version: &clock::Global,
2779        _: &mut App,
2780    ) -> proto::GetCodeActionsResponse {
2781        proto::GetCodeActionsResponse {
2782            actions: code_actions
2783                .iter()
2784                .map(LspStore::serialize_code_action)
2785                .collect(),
2786            version: serialize_version(buffer_version),
2787        }
2788    }
2789
2790    async fn response_from_proto(
2791        self,
2792        message: proto::GetCodeActionsResponse,
2793        _: Entity<LspStore>,
2794        buffer: Entity<Buffer>,
2795        mut cx: AsyncApp,
2796    ) -> Result<Vec<CodeAction>> {
2797        buffer
2798            .update(&mut cx, |buffer, _| {
2799                buffer.wait_for_version(deserialize_version(&message.version))
2800            })
2801            .await?;
2802        message
2803            .actions
2804            .into_iter()
2805            .map(LspStore::deserialize_code_action)
2806            .collect()
2807    }
2808
2809    fn buffer_id_from_proto(message: &proto::GetCodeActions) -> Result<BufferId> {
2810        BufferId::new(message.buffer_id)
2811    }
2812}
2813
2814impl GetCodeActions {
2815    fn supported_code_action_kinds(
2816        capabilities: AdapterServerCapabilities,
2817    ) -> Option<Vec<CodeActionKind>> {
2818        match capabilities.server_capabilities.code_action_provider {
2819            Some(lsp::CodeActionProviderCapability::Options(CodeActionOptions {
2820                code_action_kinds: Some(supported_action_kinds),
2821                ..
2822            })) => Some(supported_action_kinds),
2823            _ => capabilities.code_action_kinds,
2824        }
2825    }
2826
2827    pub fn can_resolve_actions(capabilities: &ServerCapabilities) -> bool {
2828        capabilities
2829            .code_action_provider
2830            .as_ref()
2831            .and_then(|options| match options {
2832                lsp::CodeActionProviderCapability::Simple(_is_supported) => None,
2833                lsp::CodeActionProviderCapability::Options(options) => options.resolve_provider,
2834            })
2835            .unwrap_or(false)
2836    }
2837}
2838
2839impl OnTypeFormatting {
2840    pub fn supports_on_type_formatting(trigger: &str, capabilities: &ServerCapabilities) -> bool {
2841        let Some(on_type_formatting_options) = &capabilities.document_on_type_formatting_provider
2842        else {
2843            return false;
2844        };
2845        on_type_formatting_options
2846            .first_trigger_character
2847            .contains(trigger)
2848            || on_type_formatting_options
2849                .more_trigger_character
2850                .iter()
2851                .flatten()
2852                .any(|chars| chars.contains(trigger))
2853    }
2854}
2855
2856#[async_trait(?Send)]
2857impl LspCommand for OnTypeFormatting {
2858    type Response = Option<Transaction>;
2859    type LspRequest = lsp::request::OnTypeFormatting;
2860    type ProtoRequest = proto::OnTypeFormatting;
2861
2862    fn display_name(&self) -> &str {
2863        "Formatting on typing"
2864    }
2865
2866    fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
2867        Self::supports_on_type_formatting(&self.trigger, &capabilities.server_capabilities)
2868    }
2869
2870    fn to_lsp(
2871        &self,
2872        path: &Path,
2873        _: &Buffer,
2874        _: &Arc<LanguageServer>,
2875        _: &App,
2876    ) -> Result<lsp::DocumentOnTypeFormattingParams> {
2877        Ok(lsp::DocumentOnTypeFormattingParams {
2878            text_document_position: make_lsp_text_document_position(path, self.position)?,
2879            ch: self.trigger.clone(),
2880            options: self.options.clone(),
2881        })
2882    }
2883
2884    async fn response_from_lsp(
2885        self,
2886        message: Option<Vec<lsp::TextEdit>>,
2887        lsp_store: Entity<LspStore>,
2888        buffer: Entity<Buffer>,
2889        server_id: LanguageServerId,
2890        mut cx: AsyncApp,
2891    ) -> Result<Option<Transaction>> {
2892        if let Some(edits) = message {
2893            let (lsp_adapter, lsp_server) =
2894                language_server_for_buffer(&lsp_store, &buffer, server_id, &mut cx)?;
2895            LocalLspStore::deserialize_text_edits(
2896                lsp_store,
2897                buffer,
2898                edits,
2899                self.push_to_history,
2900                lsp_adapter,
2901                lsp_server,
2902                &mut cx,
2903            )
2904            .await
2905        } else {
2906            Ok(None)
2907        }
2908    }
2909
2910    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> proto::OnTypeFormatting {
2911        proto::OnTypeFormatting {
2912            project_id,
2913            buffer_id: buffer.remote_id().into(),
2914            position: Some(language::proto::serialize_anchor(
2915                &buffer.anchor_before(self.position),
2916            )),
2917            trigger: self.trigger.clone(),
2918            version: serialize_version(&buffer.version()),
2919        }
2920    }
2921
2922    async fn from_proto(
2923        message: proto::OnTypeFormatting,
2924        _: Entity<LspStore>,
2925        buffer: Entity<Buffer>,
2926        mut cx: AsyncApp,
2927    ) -> Result<Self> {
2928        let position = message
2929            .position
2930            .and_then(deserialize_anchor)
2931            .context("invalid position")?;
2932        buffer
2933            .update(&mut cx, |buffer, _| {
2934                buffer.wait_for_version(deserialize_version(&message.version))
2935            })
2936            .await?;
2937
2938        let options = buffer.update(&mut cx, |buffer, cx| {
2939            lsp_formatting_options(LanguageSettings::for_buffer(buffer, cx).as_ref())
2940        });
2941
2942        Ok(Self {
2943            position: buffer.read_with(&cx, |buffer, _| position.to_point_utf16(buffer)),
2944            trigger: message.trigger.clone(),
2945            options,
2946            push_to_history: false,
2947        })
2948    }
2949
2950    fn response_to_proto(
2951        response: Option<Transaction>,
2952        _: &mut LspStore,
2953        _: PeerId,
2954        _: &clock::Global,
2955        _: &mut App,
2956    ) -> proto::OnTypeFormattingResponse {
2957        proto::OnTypeFormattingResponse {
2958            transaction: response
2959                .map(|transaction| language::proto::serialize_transaction(&transaction)),
2960        }
2961    }
2962
2963    async fn response_from_proto(
2964        self,
2965        message: proto::OnTypeFormattingResponse,
2966        _: Entity<LspStore>,
2967        _: Entity<Buffer>,
2968        _: AsyncApp,
2969    ) -> Result<Option<Transaction>> {
2970        let Some(transaction) = message.transaction else {
2971            return Ok(None);
2972        };
2973        Ok(Some(language::proto::deserialize_transaction(transaction)?))
2974    }
2975
2976    fn buffer_id_from_proto(message: &proto::OnTypeFormatting) -> Result<BufferId> {
2977        BufferId::new(message.buffer_id)
2978    }
2979}
2980
2981impl InlayHints {
2982    pub async fn lsp_to_project_hint(
2983        lsp_hint: lsp::InlayHint,
2984        buffer_handle: &Entity<Buffer>,
2985        server_id: LanguageServerId,
2986        resolve_state: ResolveState,
2987        force_no_type_left_padding: bool,
2988        cx: &mut AsyncApp,
2989    ) -> anyhow::Result<InlayHint> {
2990        let kind = lsp_hint.kind.and_then(|kind| match kind {
2991            lsp::InlayHintKind::TYPE => Some(InlayHintKind::Type),
2992            lsp::InlayHintKind::PARAMETER => Some(InlayHintKind::Parameter),
2993            _ => None,
2994        });
2995
2996        let position = buffer_handle.read_with(cx, |buffer, _| {
2997            let position = buffer.clip_point_utf16(point_from_lsp(lsp_hint.position), Bias::Left);
2998            if kind == Some(InlayHintKind::Parameter) {
2999                buffer.anchor_before(position)
3000            } else {
3001                buffer.anchor_after(position)
3002            }
3003        });
3004        let label = Self::lsp_inlay_label_to_project(lsp_hint.label, server_id)
3005            .await
3006            .context("lsp to project inlay hint conversion")?;
3007        let padding_left = if force_no_type_left_padding && kind == Some(InlayHintKind::Type) {
3008            false
3009        } else {
3010            lsp_hint.padding_left.unwrap_or(false)
3011        };
3012
3013        Ok(InlayHint {
3014            position,
3015            padding_left,
3016            padding_right: lsp_hint.padding_right.unwrap_or(false),
3017            label,
3018            kind,
3019            tooltip: lsp_hint.tooltip.map(|tooltip| match tooltip {
3020                lsp::InlayHintTooltip::String(s) => InlayHintTooltip::String(s),
3021                lsp::InlayHintTooltip::MarkupContent(markup_content) => {
3022                    InlayHintTooltip::MarkupContent(MarkupContent {
3023                        kind: match markup_content.kind {
3024                            lsp::MarkupKind::PlainText => HoverBlockKind::PlainText,
3025                            lsp::MarkupKind::Markdown => HoverBlockKind::Markdown,
3026                        },
3027                        value: markup_content.value,
3028                    })
3029                }
3030            }),
3031            resolve_state,
3032        })
3033    }
3034
3035    async fn lsp_inlay_label_to_project(
3036        lsp_label: lsp::InlayHintLabel,
3037        server_id: LanguageServerId,
3038    ) -> anyhow::Result<InlayHintLabel> {
3039        let label = match lsp_label {
3040            lsp::InlayHintLabel::String(s) => InlayHintLabel::String(s),
3041            lsp::InlayHintLabel::LabelParts(lsp_parts) => {
3042                let mut parts = Vec::with_capacity(lsp_parts.len());
3043                for lsp_part in lsp_parts {
3044                    parts.push(InlayHintLabelPart {
3045                        value: lsp_part.value,
3046                        tooltip: lsp_part.tooltip.map(|tooltip| match tooltip {
3047                            lsp::InlayHintLabelPartTooltip::String(s) => {
3048                                InlayHintLabelPartTooltip::String(s)
3049                            }
3050                            lsp::InlayHintLabelPartTooltip::MarkupContent(markup_content) => {
3051                                InlayHintLabelPartTooltip::MarkupContent(MarkupContent {
3052                                    kind: match markup_content.kind {
3053                                        lsp::MarkupKind::PlainText => HoverBlockKind::PlainText,
3054                                        lsp::MarkupKind::Markdown => HoverBlockKind::Markdown,
3055                                    },
3056                                    value: markup_content.value,
3057                                })
3058                            }
3059                        }),
3060                        location: Some(server_id).zip(lsp_part.location),
3061                    });
3062                }
3063                InlayHintLabel::LabelParts(parts)
3064            }
3065        };
3066
3067        Ok(label)
3068    }
3069
3070    pub fn project_to_proto_hint(response_hint: InlayHint) -> proto::InlayHint {
3071        let (state, lsp_resolve_state) = match response_hint.resolve_state {
3072            ResolveState::Resolved => (0, None),
3073            ResolveState::CanResolve(server_id, resolve_data) => (
3074                1,
3075                Some(proto::resolve_state::LspResolveState {
3076                    server_id: server_id.0 as u64,
3077                    value: resolve_data.map(|json_data| {
3078                        serde_json::to_string(&json_data)
3079                            .expect("failed to serialize resolve json data")
3080                    }),
3081                }),
3082            ),
3083            ResolveState::Resolving => (2, None),
3084        };
3085        let resolve_state = Some(proto::ResolveState {
3086            state,
3087            lsp_resolve_state,
3088        });
3089        proto::InlayHint {
3090            position: Some(language::proto::serialize_anchor(&response_hint.position)),
3091            padding_left: response_hint.padding_left,
3092            padding_right: response_hint.padding_right,
3093            label: Some(proto::InlayHintLabel {
3094                label: Some(match response_hint.label {
3095                    InlayHintLabel::String(s) => proto::inlay_hint_label::Label::Value(s),
3096                    InlayHintLabel::LabelParts(label_parts) => {
3097                        proto::inlay_hint_label::Label::LabelParts(proto::InlayHintLabelParts {
3098                            parts: label_parts.into_iter().map(|label_part| {
3099                                let location_url = label_part.location.as_ref().map(|(_, location)| location.uri.to_string());
3100                                let location_range_start = label_part.location.as_ref().map(|(_, location)| point_from_lsp(location.range.start).0).map(|point| proto::PointUtf16 { row: point.row, column: point.column });
3101                                let location_range_end = label_part.location.as_ref().map(|(_, location)| point_from_lsp(location.range.end).0).map(|point| proto::PointUtf16 { row: point.row, column: point.column });
3102                                proto::InlayHintLabelPart {
3103                                value: label_part.value,
3104                                tooltip: label_part.tooltip.map(|tooltip| {
3105                                    let proto_tooltip = match tooltip {
3106                                        InlayHintLabelPartTooltip::String(s) => proto::inlay_hint_label_part_tooltip::Content::Value(s),
3107                                        InlayHintLabelPartTooltip::MarkupContent(markup_content) => proto::inlay_hint_label_part_tooltip::Content::MarkupContent(proto::MarkupContent {
3108                                            is_markdown: markup_content.kind == HoverBlockKind::Markdown,
3109                                            value: markup_content.value,
3110                                        }),
3111                                    };
3112                                    proto::InlayHintLabelPartTooltip {content: Some(proto_tooltip)}
3113                                }),
3114                                location_url,
3115                                location_range_start,
3116                                location_range_end,
3117                                language_server_id: label_part.location.as_ref().map(|(server_id, _)| server_id.0 as u64),
3118                            }}).collect()
3119                        })
3120                    }
3121                }),
3122            }),
3123            kind: response_hint.kind.map(|kind| kind.name().to_string()),
3124            tooltip: response_hint.tooltip.map(|response_tooltip| {
3125                let proto_tooltip = match response_tooltip {
3126                    InlayHintTooltip::String(s) => proto::inlay_hint_tooltip::Content::Value(s),
3127                    InlayHintTooltip::MarkupContent(markup_content) => {
3128                        proto::inlay_hint_tooltip::Content::MarkupContent(proto::MarkupContent {
3129                            is_markdown: markup_content.kind == HoverBlockKind::Markdown,
3130                            value: markup_content.value,
3131                        })
3132                    }
3133                };
3134                proto::InlayHintTooltip {
3135                    content: Some(proto_tooltip),
3136                }
3137            }),
3138            resolve_state,
3139        }
3140    }
3141
3142    pub fn proto_to_project_hint(message_hint: proto::InlayHint) -> anyhow::Result<InlayHint> {
3143        let resolve_state = message_hint.resolve_state.as_ref().unwrap_or_else(|| {
3144            panic!("incorrect proto inlay hint message: no resolve state in hint {message_hint:?}",)
3145        });
3146        let resolve_state_data = resolve_state
3147            .lsp_resolve_state.as_ref()
3148            .map(|lsp_resolve_state| {
3149                let value = lsp_resolve_state.value.as_deref().map(|value| {
3150                    serde_json::from_str::<Option<lsp::LSPAny>>(value)
3151                        .with_context(|| format!("incorrect proto inlay hint message: non-json resolve state {lsp_resolve_state:?}"))
3152                }).transpose()?.flatten();
3153                anyhow::Ok((LanguageServerId(lsp_resolve_state.server_id as usize), value))
3154            })
3155            .transpose()?;
3156        let resolve_state = match resolve_state.state {
3157            0 => ResolveState::Resolved,
3158            1 => {
3159                let (server_id, lsp_resolve_state) = resolve_state_data.with_context(|| {
3160                    format!(
3161                        "No lsp resolve data for the hint that can be resolved: {message_hint:?}"
3162                    )
3163                })?;
3164                ResolveState::CanResolve(server_id, lsp_resolve_state)
3165            }
3166            2 => ResolveState::Resolving,
3167            invalid => {
3168                anyhow::bail!("Unexpected resolve state {invalid} for hint {message_hint:?}")
3169            }
3170        };
3171        Ok(InlayHint {
3172            position: message_hint
3173                .position
3174                .and_then(language::proto::deserialize_anchor)
3175                .context("invalid position")?,
3176            label: match message_hint
3177                .label
3178                .and_then(|label| label.label)
3179                .context("missing label")?
3180            {
3181                proto::inlay_hint_label::Label::Value(s) => InlayHintLabel::String(s),
3182                proto::inlay_hint_label::Label::LabelParts(parts) => {
3183                    let mut label_parts = Vec::new();
3184                    for part in parts.parts {
3185                        label_parts.push(InlayHintLabelPart {
3186                            value: part.value,
3187                            tooltip: part.tooltip.map(|tooltip| match tooltip.content {
3188                                Some(proto::inlay_hint_label_part_tooltip::Content::Value(s)) => {
3189                                    InlayHintLabelPartTooltip::String(s)
3190                                }
3191                                Some(
3192                                    proto::inlay_hint_label_part_tooltip::Content::MarkupContent(
3193                                        markup_content,
3194                                    ),
3195                                ) => InlayHintLabelPartTooltip::MarkupContent(MarkupContent {
3196                                    kind: if markup_content.is_markdown {
3197                                        HoverBlockKind::Markdown
3198                                    } else {
3199                                        HoverBlockKind::PlainText
3200                                    },
3201                                    value: markup_content.value,
3202                                }),
3203                                None => InlayHintLabelPartTooltip::String(String::new()),
3204                            }),
3205                            location: {
3206                                match part
3207                                    .location_url
3208                                    .zip(
3209                                        part.location_range_start.and_then(|start| {
3210                                            Some(start..part.location_range_end?)
3211                                        }),
3212                                    )
3213                                    .zip(part.language_server_id)
3214                                {
3215                                    Some(((uri, range), server_id)) => Some((
3216                                        LanguageServerId(server_id as usize),
3217                                        lsp::Location {
3218                                            uri: lsp::Uri::from_str(&uri).with_context(|| {
3219                                                format!("invalid uri in hint part {uri:?}")
3220                                            })?,
3221                                            range: lsp::Range::new(
3222                                                point_to_lsp(PointUtf16::new(
3223                                                    range.start.row,
3224                                                    range.start.column,
3225                                                )),
3226                                                point_to_lsp(PointUtf16::new(
3227                                                    range.end.row,
3228                                                    range.end.column,
3229                                                )),
3230                                            ),
3231                                        },
3232                                    )),
3233                                    None => None,
3234                                }
3235                            },
3236                        });
3237                    }
3238
3239                    InlayHintLabel::LabelParts(label_parts)
3240                }
3241            },
3242            padding_left: message_hint.padding_left,
3243            padding_right: message_hint.padding_right,
3244            kind: message_hint
3245                .kind
3246                .as_deref()
3247                .and_then(InlayHintKind::from_name),
3248            tooltip: message_hint.tooltip.and_then(|tooltip| {
3249                Some(match tooltip.content? {
3250                    proto::inlay_hint_tooltip::Content::Value(s) => InlayHintTooltip::String(s),
3251                    proto::inlay_hint_tooltip::Content::MarkupContent(markup_content) => {
3252                        InlayHintTooltip::MarkupContent(MarkupContent {
3253                            kind: if markup_content.is_markdown {
3254                                HoverBlockKind::Markdown
3255                            } else {
3256                                HoverBlockKind::PlainText
3257                            },
3258                            value: markup_content.value,
3259                        })
3260                    }
3261                })
3262            }),
3263            resolve_state,
3264        })
3265    }
3266
3267    pub fn project_to_lsp_hint(hint: InlayHint, snapshot: &BufferSnapshot) -> lsp::InlayHint {
3268        lsp::InlayHint {
3269            position: point_to_lsp(hint.position.to_point_utf16(snapshot)),
3270            kind: hint.kind.map(|kind| match kind {
3271                InlayHintKind::Type => lsp::InlayHintKind::TYPE,
3272                InlayHintKind::Parameter => lsp::InlayHintKind::PARAMETER,
3273            }),
3274            text_edits: None,
3275            tooltip: hint.tooltip.and_then(|tooltip| {
3276                Some(match tooltip {
3277                    InlayHintTooltip::String(s) => lsp::InlayHintTooltip::String(s),
3278                    InlayHintTooltip::MarkupContent(markup_content) => {
3279                        lsp::InlayHintTooltip::MarkupContent(lsp::MarkupContent {
3280                            kind: match markup_content.kind {
3281                                HoverBlockKind::PlainText => lsp::MarkupKind::PlainText,
3282                                HoverBlockKind::Markdown => lsp::MarkupKind::Markdown,
3283                                HoverBlockKind::Code { .. } => return None,
3284                            },
3285                            value: markup_content.value,
3286                        })
3287                    }
3288                })
3289            }),
3290            label: match hint.label {
3291                InlayHintLabel::String(s) => lsp::InlayHintLabel::String(s),
3292                InlayHintLabel::LabelParts(label_parts) => lsp::InlayHintLabel::LabelParts(
3293                    label_parts
3294                        .into_iter()
3295                        .map(|part| lsp::InlayHintLabelPart {
3296                            value: part.value,
3297                            tooltip: part.tooltip.and_then(|tooltip| {
3298                                Some(match tooltip {
3299                                    InlayHintLabelPartTooltip::String(s) => {
3300                                        lsp::InlayHintLabelPartTooltip::String(s)
3301                                    }
3302                                    InlayHintLabelPartTooltip::MarkupContent(markup_content) => {
3303                                        lsp::InlayHintLabelPartTooltip::MarkupContent(
3304                                            lsp::MarkupContent {
3305                                                kind: match markup_content.kind {
3306                                                    HoverBlockKind::PlainText => {
3307                                                        lsp::MarkupKind::PlainText
3308                                                    }
3309                                                    HoverBlockKind::Markdown => {
3310                                                        lsp::MarkupKind::Markdown
3311                                                    }
3312                                                    HoverBlockKind::Code { .. } => return None,
3313                                                },
3314                                                value: markup_content.value,
3315                                            },
3316                                        )
3317                                    }
3318                                })
3319                            }),
3320                            location: part.location.map(|(_, location)| location),
3321                            command: None,
3322                        })
3323                        .collect(),
3324                ),
3325            },
3326            padding_left: Some(hint.padding_left),
3327            padding_right: Some(hint.padding_right),
3328            data: match hint.resolve_state {
3329                ResolveState::CanResolve(_, data) => data,
3330                ResolveState::Resolving | ResolveState::Resolved => None,
3331            },
3332        }
3333    }
3334
3335    pub fn can_resolve_inlays(capabilities: &ServerCapabilities) -> bool {
3336        capabilities
3337            .inlay_hint_provider
3338            .as_ref()
3339            .and_then(|options| match options {
3340                OneOf::Left(_is_supported) => None,
3341                OneOf::Right(capabilities) => match capabilities {
3342                    lsp::InlayHintServerCapabilities::Options(o) => o.resolve_provider,
3343                    lsp::InlayHintServerCapabilities::RegistrationOptions(o) => {
3344                        o.inlay_hint_options.resolve_provider
3345                    }
3346                },
3347            })
3348            .unwrap_or(false)
3349    }
3350
3351    pub fn check_capabilities(capabilities: &ServerCapabilities) -> bool {
3352        capabilities
3353            .inlay_hint_provider
3354            .as_ref()
3355            .is_some_and(|inlay_hint_provider| match inlay_hint_provider {
3356                lsp::OneOf::Left(enabled) => *enabled,
3357                lsp::OneOf::Right(_) => true,
3358            })
3359    }
3360}
3361
3362#[async_trait(?Send)]
3363impl LspCommand for InlayHints {
3364    type Response = Vec<InlayHint>;
3365    type LspRequest = lsp::InlayHintRequest;
3366    type ProtoRequest = proto::InlayHints;
3367
3368    fn display_name(&self) -> &str {
3369        "Inlay hints"
3370    }
3371
3372    fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
3373        Self::check_capabilities(&capabilities.server_capabilities)
3374    }
3375
3376    fn to_lsp(
3377        &self,
3378        path: &Path,
3379        buffer: &Buffer,
3380        _: &Arc<LanguageServer>,
3381        _: &App,
3382    ) -> Result<lsp::InlayHintParams> {
3383        Ok(lsp::InlayHintParams {
3384            text_document: lsp::TextDocumentIdentifier {
3385                uri: file_path_to_lsp_url(path)?,
3386            },
3387            range: range_to_lsp(self.range.to_point_utf16(buffer))?,
3388            work_done_progress_params: Default::default(),
3389        })
3390    }
3391
3392    async fn response_from_lsp(
3393        self,
3394        message: Option<Vec<lsp::InlayHint>>,
3395        lsp_store: Entity<LspStore>,
3396        buffer: Entity<Buffer>,
3397        server_id: LanguageServerId,
3398        mut cx: AsyncApp,
3399    ) -> anyhow::Result<Vec<InlayHint>> {
3400        let (lsp_adapter, lsp_server) =
3401            language_server_for_buffer(&lsp_store, &buffer, server_id, &mut cx)?;
3402        // `typescript-language-server` adds padding to the left for type hints, turning
3403        // `const foo: boolean` into `const foo : boolean` which looks odd.
3404        // `rust-analyzer` does not have the padding for this case, and we have to accommodate both.
3405        //
3406        // We could trim the whole string, but being pessimistic on par with the situation above,
3407        // there might be a hint with multiple whitespaces at the end(s) which we need to display properly.
3408        // Hence let's use a heuristic first to handle the most awkward case and look for more.
3409        let force_no_type_left_padding =
3410            lsp_adapter.name.0.as_ref() == "typescript-language-server";
3411
3412        let hints = message.unwrap_or_default().into_iter().map(|lsp_hint| {
3413            let resolve_state = if InlayHints::can_resolve_inlays(&lsp_server.capabilities()) {
3414                ResolveState::CanResolve(lsp_server.server_id(), lsp_hint.data.clone())
3415            } else {
3416                ResolveState::Resolved
3417            };
3418
3419            let buffer = buffer.clone();
3420            cx.spawn(async move |cx| {
3421                InlayHints::lsp_to_project_hint(
3422                    lsp_hint,
3423                    &buffer,
3424                    server_id,
3425                    resolve_state,
3426                    force_no_type_left_padding,
3427                    cx,
3428                )
3429                .await
3430            })
3431        });
3432        future::join_all(hints)
3433            .await
3434            .into_iter()
3435            .collect::<anyhow::Result<_>>()
3436            .context("lsp to project inlay hints conversion")
3437    }
3438
3439    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> proto::InlayHints {
3440        proto::InlayHints {
3441            project_id,
3442            buffer_id: buffer.remote_id().into(),
3443            start: Some(language::proto::serialize_anchor(&self.range.start)),
3444            end: Some(language::proto::serialize_anchor(&self.range.end)),
3445            version: serialize_version(&buffer.version()),
3446        }
3447    }
3448
3449    async fn from_proto(
3450        message: proto::InlayHints,
3451        _: Entity<LspStore>,
3452        buffer: Entity<Buffer>,
3453        mut cx: AsyncApp,
3454    ) -> Result<Self> {
3455        let start = message
3456            .start
3457            .and_then(language::proto::deserialize_anchor)
3458            .context("invalid start")?;
3459        let end = message
3460            .end
3461            .and_then(language::proto::deserialize_anchor)
3462            .context("invalid end")?;
3463        buffer
3464            .update(&mut cx, |buffer, _| {
3465                buffer.wait_for_version(deserialize_version(&message.version))
3466            })
3467            .await?;
3468
3469        Ok(Self { range: start..end })
3470    }
3471
3472    fn response_to_proto(
3473        response: Vec<InlayHint>,
3474        _: &mut LspStore,
3475        _: PeerId,
3476        buffer_version: &clock::Global,
3477        _: &mut App,
3478    ) -> proto::InlayHintsResponse {
3479        proto::InlayHintsResponse {
3480            hints: response
3481                .into_iter()
3482                .map(InlayHints::project_to_proto_hint)
3483                .collect(),
3484            version: serialize_version(buffer_version),
3485        }
3486    }
3487
3488    async fn response_from_proto(
3489        self,
3490        message: proto::InlayHintsResponse,
3491        _: Entity<LspStore>,
3492        buffer: Entity<Buffer>,
3493        mut cx: AsyncApp,
3494    ) -> anyhow::Result<Vec<InlayHint>> {
3495        buffer
3496            .update(&mut cx, |buffer, _| {
3497                buffer.wait_for_version(deserialize_version(&message.version))
3498            })
3499            .await?;
3500
3501        let mut hints = Vec::new();
3502        for message_hint in message.hints {
3503            hints.push(InlayHints::proto_to_project_hint(message_hint)?);
3504        }
3505
3506        Ok(hints)
3507    }
3508
3509    fn buffer_id_from_proto(message: &proto::InlayHints) -> Result<BufferId> {
3510        BufferId::new(message.buffer_id)
3511    }
3512}
3513
3514#[async_trait(?Send)]
3515impl LspCommand for SemanticTokensFull {
3516    type Response = SemanticTokensResponse;
3517    type LspRequest = lsp::SemanticTokensFullRequest;
3518    type ProtoRequest = proto::SemanticTokens;
3519
3520    fn display_name(&self) -> &str {
3521        "Semantic tokens full"
3522    }
3523
3524    fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
3525        capabilities
3526            .server_capabilities
3527            .semantic_tokens_provider
3528            .as_ref()
3529            .is_some_and(|semantic_tokens_provider| {
3530                let options = match semantic_tokens_provider {
3531                    lsp::SemanticTokensServerCapabilities::SemanticTokensOptions(opts) => opts,
3532                    lsp::SemanticTokensServerCapabilities::SemanticTokensRegistrationOptions(
3533                        opts,
3534                    ) => &opts.semantic_tokens_options,
3535                };
3536
3537                match options.full {
3538                    Some(lsp::SemanticTokensFullOptions::Bool(is_supported)) => is_supported,
3539                    Some(lsp::SemanticTokensFullOptions::Delta { .. }) => true,
3540                    None => false,
3541                }
3542            })
3543    }
3544
3545    fn to_lsp(
3546        &self,
3547        path: &Path,
3548        _: &Buffer,
3549        _: &Arc<LanguageServer>,
3550        _: &App,
3551    ) -> Result<lsp::SemanticTokensParams> {
3552        Ok(lsp::SemanticTokensParams {
3553            text_document: lsp::TextDocumentIdentifier {
3554                uri: file_path_to_lsp_url(path)?,
3555            },
3556            partial_result_params: Default::default(),
3557            work_done_progress_params: Default::default(),
3558        })
3559    }
3560
3561    async fn response_from_lsp(
3562        self,
3563        message: Option<lsp::SemanticTokensResult>,
3564        _: Entity<LspStore>,
3565        _: Entity<Buffer>,
3566        _: LanguageServerId,
3567        _: AsyncApp,
3568    ) -> anyhow::Result<SemanticTokensResponse> {
3569        match message {
3570            Some(lsp::SemanticTokensResult::Tokens(tokens)) => Ok(SemanticTokensResponse::Full {
3571                data: tokens.data,
3572                result_id: tokens.result_id.map(SharedString::new),
3573            }),
3574            Some(lsp::SemanticTokensResult::Partial(_)) => {
3575                anyhow::bail!(
3576                    "Unexpected semantic tokens response with partial result for inlay hints"
3577                )
3578            }
3579            None => Ok(Default::default()),
3580        }
3581    }
3582
3583    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> proto::SemanticTokens {
3584        proto::SemanticTokens {
3585            project_id,
3586            buffer_id: buffer.remote_id().into(),
3587            version: serialize_version(&buffer.version()),
3588            for_server: self.for_server.map(|id| id.to_proto()),
3589        }
3590    }
3591
3592    async fn from_proto(
3593        message: proto::SemanticTokens,
3594        _: Entity<LspStore>,
3595        buffer: Entity<Buffer>,
3596        mut cx: AsyncApp,
3597    ) -> Result<Self> {
3598        buffer
3599            .update(&mut cx, |buffer, _| {
3600                buffer.wait_for_version(deserialize_version(&message.version))
3601            })
3602            .await?;
3603
3604        Ok(Self {
3605            for_server: message
3606                .for_server
3607                .map(|id| LanguageServerId::from_proto(id)),
3608        })
3609    }
3610
3611    fn response_to_proto(
3612        response: SemanticTokensResponse,
3613        _: &mut LspStore,
3614        _: PeerId,
3615        buffer_version: &clock::Global,
3616        _: &mut App,
3617    ) -> proto::SemanticTokensResponse {
3618        match response {
3619            SemanticTokensResponse::Full { data, result_id } => proto::SemanticTokensResponse {
3620                data,
3621                edits: Vec::new(),
3622                result_id: result_id.map(|s| s.to_string()),
3623                version: serialize_version(buffer_version),
3624            },
3625            SemanticTokensResponse::Delta { edits, result_id } => proto::SemanticTokensResponse {
3626                data: Vec::new(),
3627                edits: edits
3628                    .into_iter()
3629                    .map(|edit| proto::SemanticTokensEdit {
3630                        start: edit.start,
3631                        delete_count: edit.delete_count,
3632                        data: edit.data,
3633                    })
3634                    .collect(),
3635                result_id: result_id.map(|s| s.to_string()),
3636                version: serialize_version(buffer_version),
3637            },
3638        }
3639    }
3640
3641    async fn response_from_proto(
3642        self,
3643        message: proto::SemanticTokensResponse,
3644        _: Entity<LspStore>,
3645        buffer: Entity<Buffer>,
3646        mut cx: AsyncApp,
3647    ) -> anyhow::Result<SemanticTokensResponse> {
3648        buffer
3649            .update(&mut cx, |buffer, _| {
3650                buffer.wait_for_version(deserialize_version(&message.version))
3651            })
3652            .await?;
3653
3654        Ok(SemanticTokensResponse::Full {
3655            data: message.data,
3656            result_id: message.result_id.map(SharedString::new),
3657        })
3658    }
3659
3660    fn buffer_id_from_proto(message: &proto::SemanticTokens) -> Result<BufferId> {
3661        BufferId::new(message.buffer_id)
3662    }
3663}
3664
3665#[async_trait(?Send)]
3666impl LspCommand for SemanticTokensDelta {
3667    type Response = SemanticTokensResponse;
3668    type LspRequest = lsp::SemanticTokensFullDeltaRequest;
3669    type ProtoRequest = proto::SemanticTokens;
3670
3671    fn display_name(&self) -> &str {
3672        "Semantic tokens delta"
3673    }
3674
3675    fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
3676        capabilities
3677            .server_capabilities
3678            .semantic_tokens_provider
3679            .as_ref()
3680            .is_some_and(|semantic_tokens_provider| {
3681                let options = match semantic_tokens_provider {
3682                    lsp::SemanticTokensServerCapabilities::SemanticTokensOptions(opts) => opts,
3683                    lsp::SemanticTokensServerCapabilities::SemanticTokensRegistrationOptions(
3684                        opts,
3685                    ) => &opts.semantic_tokens_options,
3686                };
3687
3688                match options.full {
3689                    Some(lsp::SemanticTokensFullOptions::Delta { delta }) => delta.unwrap_or(false),
3690                    // `full: true` (instead of `full: { delta: true }`) means no support for delta.
3691                    _ => false,
3692                }
3693            })
3694    }
3695
3696    fn to_lsp(
3697        &self,
3698        path: &Path,
3699        _: &Buffer,
3700        _: &Arc<LanguageServer>,
3701        _: &App,
3702    ) -> Result<lsp::SemanticTokensDeltaParams> {
3703        Ok(lsp::SemanticTokensDeltaParams {
3704            text_document: lsp::TextDocumentIdentifier {
3705                uri: file_path_to_lsp_url(path)?,
3706            },
3707            previous_result_id: self.previous_result_id.clone().map(|s| s.to_string()),
3708            partial_result_params: Default::default(),
3709            work_done_progress_params: Default::default(),
3710        })
3711    }
3712
3713    async fn response_from_lsp(
3714        self,
3715        message: Option<lsp::SemanticTokensFullDeltaResult>,
3716        _: Entity<LspStore>,
3717        _: Entity<Buffer>,
3718        _: LanguageServerId,
3719        _: AsyncApp,
3720    ) -> anyhow::Result<SemanticTokensResponse> {
3721        match message {
3722            Some(lsp::SemanticTokensFullDeltaResult::Tokens(tokens)) => {
3723                Ok(SemanticTokensResponse::Full {
3724                    data: tokens.data,
3725                    result_id: tokens.result_id.map(SharedString::new),
3726                })
3727            }
3728            Some(lsp::SemanticTokensFullDeltaResult::TokensDelta(delta)) => {
3729                Ok(SemanticTokensResponse::Delta {
3730                    edits: delta
3731                        .edits
3732                        .into_iter()
3733                        .map(|e| SemanticTokensEdit {
3734                            start: e.start,
3735                            delete_count: e.delete_count,
3736                            data: e.data.unwrap_or_default(),
3737                        })
3738                        .collect(),
3739                    result_id: delta.result_id.map(SharedString::new),
3740                })
3741            }
3742            Some(lsp::SemanticTokensFullDeltaResult::PartialTokensDelta { .. }) => {
3743                anyhow::bail!(
3744                    "Unexpected semantic tokens response with partial result for inlay hints"
3745                )
3746            }
3747            None => Ok(Default::default()),
3748        }
3749    }
3750
3751    fn to_proto(&self, _: u64, _: &Buffer) -> proto::SemanticTokens {
3752        unimplemented!("Delta requests are never initialted on the remote client side")
3753    }
3754
3755    async fn from_proto(
3756        _: proto::SemanticTokens,
3757        _: Entity<LspStore>,
3758        _: Entity<Buffer>,
3759        _: AsyncApp,
3760    ) -> Result<Self> {
3761        unimplemented!("Delta requests are never initialted on the remote client side")
3762    }
3763
3764    fn response_to_proto(
3765        response: SemanticTokensResponse,
3766        _: &mut LspStore,
3767        _: PeerId,
3768        buffer_version: &clock::Global,
3769        _: &mut App,
3770    ) -> proto::SemanticTokensResponse {
3771        match response {
3772            SemanticTokensResponse::Full { data, result_id } => proto::SemanticTokensResponse {
3773                data,
3774                edits: Vec::new(),
3775                result_id: result_id.map(|s| s.to_string()),
3776                version: serialize_version(buffer_version),
3777            },
3778            SemanticTokensResponse::Delta { edits, result_id } => proto::SemanticTokensResponse {
3779                data: Vec::new(),
3780                edits: edits
3781                    .into_iter()
3782                    .map(|edit| proto::SemanticTokensEdit {
3783                        start: edit.start,
3784                        delete_count: edit.delete_count,
3785                        data: edit.data,
3786                    })
3787                    .collect(),
3788                result_id: result_id.map(|s| s.to_string()),
3789                version: serialize_version(buffer_version),
3790            },
3791        }
3792    }
3793
3794    async fn response_from_proto(
3795        self,
3796        message: proto::SemanticTokensResponse,
3797        _: Entity<LspStore>,
3798        buffer: Entity<Buffer>,
3799        mut cx: AsyncApp,
3800    ) -> anyhow::Result<SemanticTokensResponse> {
3801        buffer
3802            .update(&mut cx, |buffer, _| {
3803                buffer.wait_for_version(deserialize_version(&message.version))
3804            })
3805            .await?;
3806
3807        Ok(SemanticTokensResponse::Full {
3808            data: message.data,
3809            result_id: message.result_id.map(SharedString::new),
3810        })
3811    }
3812
3813    fn buffer_id_from_proto(message: &proto::SemanticTokens) -> Result<BufferId> {
3814        BufferId::new(message.buffer_id)
3815    }
3816}
3817
3818#[async_trait(?Send)]
3819impl LspCommand for GetCodeLens {
3820    type Response = Vec<CodeAction>;
3821    type LspRequest = lsp::CodeLensRequest;
3822    type ProtoRequest = proto::GetCodeLens;
3823
3824    fn display_name(&self) -> &str {
3825        "Code Lens"
3826    }
3827
3828    fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
3829        capabilities
3830            .server_capabilities
3831            .code_lens_provider
3832            .is_some()
3833    }
3834
3835    fn to_lsp(
3836        &self,
3837        path: &Path,
3838        _: &Buffer,
3839        _: &Arc<LanguageServer>,
3840        _: &App,
3841    ) -> Result<lsp::CodeLensParams> {
3842        Ok(lsp::CodeLensParams {
3843            text_document: lsp::TextDocumentIdentifier {
3844                uri: file_path_to_lsp_url(path)?,
3845            },
3846            work_done_progress_params: lsp::WorkDoneProgressParams::default(),
3847            partial_result_params: lsp::PartialResultParams::default(),
3848        })
3849    }
3850
3851    async fn response_from_lsp(
3852        self,
3853        message: Option<Vec<lsp::CodeLens>>,
3854        lsp_store: Entity<LspStore>,
3855        buffer: Entity<Buffer>,
3856        server_id: LanguageServerId,
3857        cx: AsyncApp,
3858    ) -> anyhow::Result<Vec<CodeAction>> {
3859        let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
3860        let language_server = cx.update(|cx| {
3861            lsp_store
3862                .read(cx)
3863                .language_server_for_id(server_id)
3864                .with_context(|| {
3865                    format!("Missing the language server that just returned a response {server_id}")
3866                })
3867        })?;
3868        let server_capabilities = language_server.capabilities();
3869        let available_commands = server_capabilities
3870            .execute_command_provider
3871            .as_ref()
3872            .map(|options| options.commands.as_slice())
3873            .unwrap_or_default();
3874        Ok(message
3875            .unwrap_or_default()
3876            .into_iter()
3877            .filter(|code_lens| {
3878                code_lens
3879                    .command
3880                    .as_ref()
3881                    .is_none_or(|command| available_commands.contains(&command.command))
3882            })
3883            .map(|code_lens| {
3884                let code_lens_range = range_from_lsp(code_lens.range);
3885                let start = snapshot.clip_point_utf16(code_lens_range.start, Bias::Left);
3886                let end = snapshot.clip_point_utf16(code_lens_range.end, Bias::Right);
3887                let range = snapshot.anchor_before(start)..snapshot.anchor_after(end);
3888                CodeAction {
3889                    server_id,
3890                    range,
3891                    lsp_action: LspAction::CodeLens(code_lens),
3892                    resolved: false,
3893                }
3894            })
3895            .collect())
3896    }
3897
3898    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> proto::GetCodeLens {
3899        proto::GetCodeLens {
3900            project_id,
3901            buffer_id: buffer.remote_id().into(),
3902            version: serialize_version(&buffer.version()),
3903        }
3904    }
3905
3906    async fn from_proto(
3907        message: proto::GetCodeLens,
3908        _: Entity<LspStore>,
3909        buffer: Entity<Buffer>,
3910        mut cx: AsyncApp,
3911    ) -> Result<Self> {
3912        buffer
3913            .update(&mut cx, |buffer, _| {
3914                buffer.wait_for_version(deserialize_version(&message.version))
3915            })
3916            .await?;
3917        Ok(Self)
3918    }
3919
3920    fn response_to_proto(
3921        response: Vec<CodeAction>,
3922        _: &mut LspStore,
3923        _: PeerId,
3924        buffer_version: &clock::Global,
3925        _: &mut App,
3926    ) -> proto::GetCodeLensResponse {
3927        proto::GetCodeLensResponse {
3928            lens_actions: response
3929                .iter()
3930                .map(LspStore::serialize_code_action)
3931                .collect(),
3932            version: serialize_version(buffer_version),
3933        }
3934    }
3935
3936    async fn response_from_proto(
3937        self,
3938        message: proto::GetCodeLensResponse,
3939        _: Entity<LspStore>,
3940        buffer: Entity<Buffer>,
3941        mut cx: AsyncApp,
3942    ) -> anyhow::Result<Vec<CodeAction>> {
3943        buffer
3944            .update(&mut cx, |buffer, _| {
3945                buffer.wait_for_version(deserialize_version(&message.version))
3946            })
3947            .await?;
3948        message
3949            .lens_actions
3950            .into_iter()
3951            .map(LspStore::deserialize_code_action)
3952            .collect::<Result<Vec<_>>>()
3953            .context("deserializing proto code lens response")
3954    }
3955
3956    fn buffer_id_from_proto(message: &proto::GetCodeLens) -> Result<BufferId> {
3957        BufferId::new(message.buffer_id)
3958    }
3959}
3960
3961impl LinkedEditingRange {
3962    pub fn check_server_capabilities(capabilities: ServerCapabilities) -> bool {
3963        let Some(linked_editing_options) = capabilities.linked_editing_range_provider else {
3964            return false;
3965        };
3966        if let LinkedEditingRangeServerCapabilities::Simple(false) = linked_editing_options {
3967            return false;
3968        }
3969        true
3970    }
3971}
3972
3973#[async_trait(?Send)]
3974impl LspCommand for LinkedEditingRange {
3975    type Response = Vec<Range<Anchor>>;
3976    type LspRequest = lsp::request::LinkedEditingRange;
3977    type ProtoRequest = proto::LinkedEditingRange;
3978
3979    fn display_name(&self) -> &str {
3980        "Linked editing range"
3981    }
3982
3983    fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
3984        Self::check_server_capabilities(capabilities.server_capabilities)
3985    }
3986
3987    fn to_lsp(
3988        &self,
3989        path: &Path,
3990        buffer: &Buffer,
3991        _server: &Arc<LanguageServer>,
3992        _: &App,
3993    ) -> Result<lsp::LinkedEditingRangeParams> {
3994        let position = self.position.to_point_utf16(&buffer.snapshot());
3995        Ok(lsp::LinkedEditingRangeParams {
3996            text_document_position_params: make_lsp_text_document_position(path, position)?,
3997            work_done_progress_params: Default::default(),
3998        })
3999    }
4000
4001    async fn response_from_lsp(
4002        self,
4003        message: Option<lsp::LinkedEditingRanges>,
4004        _: Entity<LspStore>,
4005        buffer: Entity<Buffer>,
4006        _server_id: LanguageServerId,
4007        cx: AsyncApp,
4008    ) -> Result<Vec<Range<Anchor>>> {
4009        if let Some(lsp::LinkedEditingRanges { mut ranges, .. }) = message {
4010            ranges.sort_by_key(|range| range.start);
4011
4012            Ok(buffer.read_with(&cx, |buffer, _| {
4013                ranges
4014                    .into_iter()
4015                    .map(|range| {
4016                        let start =
4017                            buffer.clip_point_utf16(point_from_lsp(range.start), Bias::Left);
4018                        let end = buffer.clip_point_utf16(point_from_lsp(range.end), Bias::Left);
4019                        buffer.anchor_before(start)..buffer.anchor_after(end)
4020                    })
4021                    .collect()
4022            }))
4023        } else {
4024            Ok(vec![])
4025        }
4026    }
4027
4028    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> proto::LinkedEditingRange {
4029        proto::LinkedEditingRange {
4030            project_id,
4031            buffer_id: buffer.remote_id().to_proto(),
4032            position: Some(serialize_anchor(&self.position)),
4033            version: serialize_version(&buffer.version()),
4034        }
4035    }
4036
4037    async fn from_proto(
4038        message: proto::LinkedEditingRange,
4039        _: Entity<LspStore>,
4040        buffer: Entity<Buffer>,
4041        mut cx: AsyncApp,
4042    ) -> Result<Self> {
4043        let position = message.position.context("invalid position")?;
4044        buffer
4045            .update(&mut cx, |buffer, _| {
4046                buffer.wait_for_version(deserialize_version(&message.version))
4047            })
4048            .await?;
4049        let position = deserialize_anchor(position).context("invalid position")?;
4050        buffer
4051            .update(&mut cx, |buffer, _| buffer.wait_for_anchors([position]))
4052            .await?;
4053        Ok(Self { position })
4054    }
4055
4056    fn response_to_proto(
4057        response: Vec<Range<Anchor>>,
4058        _: &mut LspStore,
4059        _: PeerId,
4060        buffer_version: &clock::Global,
4061        _: &mut App,
4062    ) -> proto::LinkedEditingRangeResponse {
4063        proto::LinkedEditingRangeResponse {
4064            items: response
4065                .into_iter()
4066                .map(|range| proto::AnchorRange {
4067                    start: Some(serialize_anchor(&range.start)),
4068                    end: Some(serialize_anchor(&range.end)),
4069                })
4070                .collect(),
4071            version: serialize_version(buffer_version),
4072        }
4073    }
4074
4075    async fn response_from_proto(
4076        self,
4077        message: proto::LinkedEditingRangeResponse,
4078        _: Entity<LspStore>,
4079        buffer: Entity<Buffer>,
4080        mut cx: AsyncApp,
4081    ) -> Result<Vec<Range<Anchor>>> {
4082        buffer
4083            .update(&mut cx, |buffer, _| {
4084                buffer.wait_for_version(deserialize_version(&message.version))
4085            })
4086            .await?;
4087        let items: Vec<Range<Anchor>> = message
4088            .items
4089            .into_iter()
4090            .filter_map(|range| {
4091                let start = deserialize_anchor(range.start?)?;
4092                let end = deserialize_anchor(range.end?)?;
4093                Some(start..end)
4094            })
4095            .collect();
4096        for range in &items {
4097            buffer
4098                .update(&mut cx, |buffer, _| {
4099                    buffer.wait_for_anchors([range.start, range.end])
4100                })
4101                .await?;
4102        }
4103        Ok(items)
4104    }
4105
4106    fn buffer_id_from_proto(message: &proto::LinkedEditingRange) -> Result<BufferId> {
4107        BufferId::new(message.buffer_id)
4108    }
4109}
4110
4111impl GetDocumentDiagnostics {
4112    pub fn diagnostics_from_proto(
4113        response: proto::GetDocumentDiagnosticsResponse,
4114    ) -> Vec<LspPullDiagnostics> {
4115        response
4116            .pulled_diagnostics
4117            .into_iter()
4118            .filter_map(|diagnostics| {
4119                Some(LspPullDiagnostics::Response {
4120                    registration_id: diagnostics.registration_id.map(SharedString::from),
4121                    server_id: LanguageServerId::from_proto(diagnostics.server_id),
4122                    uri: lsp::Uri::from_str(diagnostics.uri.as_str()).log_err()?,
4123                    diagnostics: if diagnostics.changed {
4124                        PulledDiagnostics::Unchanged {
4125                            result_id: SharedString::new(diagnostics.result_id?),
4126                        }
4127                    } else {
4128                        PulledDiagnostics::Changed {
4129                            result_id: diagnostics.result_id.map(SharedString::new),
4130                            diagnostics: diagnostics
4131                                .diagnostics
4132                                .into_iter()
4133                                .filter_map(|diagnostic| {
4134                                    GetDocumentDiagnostics::deserialize_lsp_diagnostic(diagnostic)
4135                                        .context("deserializing diagnostics")
4136                                        .log_err()
4137                                })
4138                                .collect(),
4139                        }
4140                    },
4141                })
4142            })
4143            .collect()
4144    }
4145
4146    pub fn deserialize_lsp_diagnostic(diagnostic: proto::LspDiagnostic) -> Result<lsp::Diagnostic> {
4147        let start = diagnostic.start.context("invalid start range")?;
4148        let end = diagnostic.end.context("invalid end range")?;
4149
4150        let range = Range::<PointUtf16> {
4151            start: PointUtf16 {
4152                row: start.row,
4153                column: start.column,
4154            },
4155            end: PointUtf16 {
4156                row: end.row,
4157                column: end.column,
4158            },
4159        };
4160
4161        let data = diagnostic.data.and_then(|data| Value::from_str(&data).ok());
4162        let code = diagnostic.code.map(lsp::NumberOrString::String);
4163
4164        let related_information = diagnostic
4165            .related_information
4166            .into_iter()
4167            .map(|info| {
4168                let start = info.location_range_start.unwrap();
4169                let end = info.location_range_end.unwrap();
4170
4171                lsp::DiagnosticRelatedInformation {
4172                    location: lsp::Location {
4173                        range: lsp::Range {
4174                            start: point_to_lsp(PointUtf16::new(start.row, start.column)),
4175                            end: point_to_lsp(PointUtf16::new(end.row, end.column)),
4176                        },
4177                        uri: lsp::Uri::from_str(&info.location_url.unwrap()).unwrap(),
4178                    },
4179                    message: info.message,
4180                }
4181            })
4182            .collect::<Vec<_>>();
4183
4184        let tags = diagnostic
4185            .tags
4186            .into_iter()
4187            .filter_map(|tag| match proto::LspDiagnosticTag::from_i32(tag) {
4188                Some(proto::LspDiagnosticTag::Unnecessary) => Some(lsp::DiagnosticTag::UNNECESSARY),
4189                Some(proto::LspDiagnosticTag::Deprecated) => Some(lsp::DiagnosticTag::DEPRECATED),
4190                _ => None,
4191            })
4192            .collect::<Vec<_>>();
4193
4194        Ok(lsp::Diagnostic {
4195            range: language::range_to_lsp(range)?,
4196            severity: match proto::lsp_diagnostic::Severity::from_i32(diagnostic.severity).unwrap()
4197            {
4198                proto::lsp_diagnostic::Severity::Error => Some(lsp::DiagnosticSeverity::ERROR),
4199                proto::lsp_diagnostic::Severity::Warning => Some(lsp::DiagnosticSeverity::WARNING),
4200                proto::lsp_diagnostic::Severity::Information => {
4201                    Some(lsp::DiagnosticSeverity::INFORMATION)
4202                }
4203                proto::lsp_diagnostic::Severity::Hint => Some(lsp::DiagnosticSeverity::HINT),
4204                _ => None,
4205            },
4206            code,
4207            code_description: diagnostic
4208                .code_description
4209                .map(|code_description| CodeDescription {
4210                    href: Some(lsp::Uri::from_str(&code_description).unwrap()),
4211                }),
4212            related_information: Some(related_information),
4213            tags: Some(tags),
4214            source: diagnostic.source.clone(),
4215            message: diagnostic.message,
4216            data,
4217        })
4218    }
4219
4220    pub fn serialize_lsp_diagnostic(diagnostic: lsp::Diagnostic) -> Result<proto::LspDiagnostic> {
4221        let range = language::range_from_lsp(diagnostic.range);
4222        let related_information = diagnostic
4223            .related_information
4224            .unwrap_or_default()
4225            .into_iter()
4226            .map(|related_information| {
4227                let location_range_start =
4228                    point_from_lsp(related_information.location.range.start).0;
4229                let location_range_end = point_from_lsp(related_information.location.range.end).0;
4230
4231                Ok(proto::LspDiagnosticRelatedInformation {
4232                    location_url: Some(related_information.location.uri.to_string()),
4233                    location_range_start: Some(proto::PointUtf16 {
4234                        row: location_range_start.row,
4235                        column: location_range_start.column,
4236                    }),
4237                    location_range_end: Some(proto::PointUtf16 {
4238                        row: location_range_end.row,
4239                        column: location_range_end.column,
4240                    }),
4241                    message: related_information.message,
4242                })
4243            })
4244            .collect::<Result<Vec<_>>>()?;
4245
4246        let tags = diagnostic
4247            .tags
4248            .unwrap_or_default()
4249            .into_iter()
4250            .map(|tag| match tag {
4251                lsp::DiagnosticTag::UNNECESSARY => proto::LspDiagnosticTag::Unnecessary,
4252                lsp::DiagnosticTag::DEPRECATED => proto::LspDiagnosticTag::Deprecated,
4253                _ => proto::LspDiagnosticTag::None,
4254            } as i32)
4255            .collect();
4256
4257        Ok(proto::LspDiagnostic {
4258            start: Some(proto::PointUtf16 {
4259                row: range.start.0.row,
4260                column: range.start.0.column,
4261            }),
4262            end: Some(proto::PointUtf16 {
4263                row: range.end.0.row,
4264                column: range.end.0.column,
4265            }),
4266            severity: match diagnostic.severity {
4267                Some(lsp::DiagnosticSeverity::ERROR) => proto::lsp_diagnostic::Severity::Error,
4268                Some(lsp::DiagnosticSeverity::WARNING) => proto::lsp_diagnostic::Severity::Warning,
4269                Some(lsp::DiagnosticSeverity::INFORMATION) => {
4270                    proto::lsp_diagnostic::Severity::Information
4271                }
4272                Some(lsp::DiagnosticSeverity::HINT) => proto::lsp_diagnostic::Severity::Hint,
4273                _ => proto::lsp_diagnostic::Severity::None,
4274            } as i32,
4275            code: diagnostic.code.as_ref().map(|code| match code {
4276                lsp::NumberOrString::Number(code) => code.to_string(),
4277                lsp::NumberOrString::String(code) => code.clone(),
4278            }),
4279            source: diagnostic.source.clone(),
4280            related_information,
4281            tags,
4282            code_description: diagnostic
4283                .code_description
4284                .and_then(|desc| desc.href.map(|url| url.to_string())),
4285            message: diagnostic.message,
4286            data: diagnostic.data.as_ref().map(|data| data.to_string()),
4287        })
4288    }
4289
4290    pub fn deserialize_workspace_diagnostics_report(
4291        report: lsp::WorkspaceDiagnosticReportResult,
4292        server_id: LanguageServerId,
4293        registration_id: Option<SharedString>,
4294    ) -> Vec<WorkspaceLspPullDiagnostics> {
4295        let mut pulled_diagnostics = HashMap::default();
4296        match report {
4297            lsp::WorkspaceDiagnosticReportResult::Report(workspace_diagnostic_report) => {
4298                for report in workspace_diagnostic_report.items {
4299                    match report {
4300                        lsp::WorkspaceDocumentDiagnosticReport::Full(report) => {
4301                            process_full_workspace_diagnostics_report(
4302                                &mut pulled_diagnostics,
4303                                server_id,
4304                                report,
4305                                registration_id.clone(),
4306                            )
4307                        }
4308                        lsp::WorkspaceDocumentDiagnosticReport::Unchanged(report) => {
4309                            process_unchanged_workspace_diagnostics_report(
4310                                &mut pulled_diagnostics,
4311                                server_id,
4312                                report,
4313                                registration_id.clone(),
4314                            )
4315                        }
4316                    }
4317                }
4318            }
4319            lsp::WorkspaceDiagnosticReportResult::Partial(
4320                workspace_diagnostic_report_partial_result,
4321            ) => {
4322                for report in workspace_diagnostic_report_partial_result.items {
4323                    match report {
4324                        lsp::WorkspaceDocumentDiagnosticReport::Full(report) => {
4325                            process_full_workspace_diagnostics_report(
4326                                &mut pulled_diagnostics,
4327                                server_id,
4328                                report,
4329                                registration_id.clone(),
4330                            )
4331                        }
4332                        lsp::WorkspaceDocumentDiagnosticReport::Unchanged(report) => {
4333                            process_unchanged_workspace_diagnostics_report(
4334                                &mut pulled_diagnostics,
4335                                server_id,
4336                                report,
4337                                registration_id.clone(),
4338                            )
4339                        }
4340                    }
4341                }
4342            }
4343        }
4344        pulled_diagnostics.into_values().collect()
4345    }
4346}
4347
4348#[derive(Debug)]
4349pub struct WorkspaceLspPullDiagnostics {
4350    pub version: Option<i32>,
4351    pub diagnostics: LspPullDiagnostics,
4352}
4353
4354fn process_full_workspace_diagnostics_report(
4355    diagnostics: &mut HashMap<lsp::Uri, WorkspaceLspPullDiagnostics>,
4356    server_id: LanguageServerId,
4357    report: lsp::WorkspaceFullDocumentDiagnosticReport,
4358    registration_id: Option<SharedString>,
4359) {
4360    let mut new_diagnostics = HashMap::default();
4361    process_full_diagnostics_report(
4362        &mut new_diagnostics,
4363        server_id,
4364        report.uri,
4365        report.full_document_diagnostic_report,
4366        registration_id,
4367    );
4368    diagnostics.extend(new_diagnostics.into_iter().map(|(uri, diagnostics)| {
4369        (
4370            uri,
4371            WorkspaceLspPullDiagnostics {
4372                version: report.version.map(|v| v as i32),
4373                diagnostics,
4374            },
4375        )
4376    }));
4377}
4378
4379fn process_unchanged_workspace_diagnostics_report(
4380    diagnostics: &mut HashMap<lsp::Uri, WorkspaceLspPullDiagnostics>,
4381    server_id: LanguageServerId,
4382    report: lsp::WorkspaceUnchangedDocumentDiagnosticReport,
4383    registration_id: Option<SharedString>,
4384) {
4385    let mut new_diagnostics = HashMap::default();
4386    process_unchanged_diagnostics_report(
4387        &mut new_diagnostics,
4388        server_id,
4389        report.uri,
4390        report.unchanged_document_diagnostic_report,
4391        registration_id,
4392    );
4393    diagnostics.extend(new_diagnostics.into_iter().map(|(uri, diagnostics)| {
4394        (
4395            uri,
4396            WorkspaceLspPullDiagnostics {
4397                version: report.version.map(|v| v as i32),
4398                diagnostics,
4399            },
4400        )
4401    }));
4402}
4403
4404#[async_trait(?Send)]
4405impl LspCommand for GetDocumentDiagnostics {
4406    type Response = Vec<LspPullDiagnostics>;
4407    type LspRequest = lsp::request::DocumentDiagnosticRequest;
4408    type ProtoRequest = proto::GetDocumentDiagnostics;
4409
4410    fn display_name(&self) -> &str {
4411        "Get diagnostics"
4412    }
4413
4414    fn check_capabilities(&self, _: AdapterServerCapabilities) -> bool {
4415        true
4416    }
4417
4418    fn to_lsp(
4419        &self,
4420        path: &Path,
4421        _: &Buffer,
4422        _: &Arc<LanguageServer>,
4423        _: &App,
4424    ) -> Result<lsp::DocumentDiagnosticParams> {
4425        Ok(lsp::DocumentDiagnosticParams {
4426            text_document: lsp::TextDocumentIdentifier {
4427                uri: file_path_to_lsp_url(path)?,
4428            },
4429            identifier: self.identifier.as_ref().map(ToString::to_string),
4430            previous_result_id: self.previous_result_id.as_ref().map(ToString::to_string),
4431            partial_result_params: Default::default(),
4432            work_done_progress_params: Default::default(),
4433        })
4434    }
4435
4436    async fn response_from_lsp(
4437        self,
4438        message: lsp::DocumentDiagnosticReportResult,
4439        _: Entity<LspStore>,
4440        buffer: Entity<Buffer>,
4441        server_id: LanguageServerId,
4442        cx: AsyncApp,
4443    ) -> Result<Self::Response> {
4444        let url = buffer.read_with(&cx, |buffer, cx| {
4445            buffer
4446                .file()
4447                .and_then(|file| file.as_local())
4448                .map(|file| {
4449                    let abs_path = file.abs_path(cx);
4450                    file_path_to_lsp_url(&abs_path)
4451                })
4452                .transpose()?
4453                .with_context(|| format!("missing url on buffer {}", buffer.remote_id()))
4454        })?;
4455
4456        let mut pulled_diagnostics = HashMap::default();
4457        match message {
4458            lsp::DocumentDiagnosticReportResult::Report(report) => match report {
4459                lsp::DocumentDiagnosticReport::Full(report) => {
4460                    if let Some(related_documents) = report.related_documents {
4461                        process_related_documents(
4462                            &mut pulled_diagnostics,
4463                            server_id,
4464                            related_documents,
4465                            self.registration_id.clone(),
4466                        );
4467                    }
4468                    process_full_diagnostics_report(
4469                        &mut pulled_diagnostics,
4470                        server_id,
4471                        url,
4472                        report.full_document_diagnostic_report,
4473                        self.registration_id,
4474                    );
4475                }
4476                lsp::DocumentDiagnosticReport::Unchanged(report) => {
4477                    if let Some(related_documents) = report.related_documents {
4478                        process_related_documents(
4479                            &mut pulled_diagnostics,
4480                            server_id,
4481                            related_documents,
4482                            self.registration_id.clone(),
4483                        );
4484                    }
4485                    process_unchanged_diagnostics_report(
4486                        &mut pulled_diagnostics,
4487                        server_id,
4488                        url,
4489                        report.unchanged_document_diagnostic_report,
4490                        self.registration_id,
4491                    );
4492                }
4493            },
4494            lsp::DocumentDiagnosticReportResult::Partial(report) => {
4495                if let Some(related_documents) = report.related_documents {
4496                    process_related_documents(
4497                        &mut pulled_diagnostics,
4498                        server_id,
4499                        related_documents,
4500                        self.registration_id,
4501                    );
4502                }
4503            }
4504        }
4505
4506        Ok(pulled_diagnostics.into_values().collect())
4507    }
4508
4509    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> proto::GetDocumentDiagnostics {
4510        proto::GetDocumentDiagnostics {
4511            project_id,
4512            buffer_id: buffer.remote_id().into(),
4513            version: serialize_version(&buffer.version()),
4514        }
4515    }
4516
4517    async fn from_proto(
4518        _: proto::GetDocumentDiagnostics,
4519        _: Entity<LspStore>,
4520        _: Entity<Buffer>,
4521        _: AsyncApp,
4522    ) -> Result<Self> {
4523        anyhow::bail!(
4524            "proto::GetDocumentDiagnostics is not expected to be converted from proto directly, as it needs `previous_result_id` fetched first"
4525        )
4526    }
4527
4528    fn response_to_proto(
4529        response: Self::Response,
4530        _: &mut LspStore,
4531        _: PeerId,
4532        _: &clock::Global,
4533        _: &mut App,
4534    ) -> proto::GetDocumentDiagnosticsResponse {
4535        let pulled_diagnostics = response
4536            .into_iter()
4537            .filter_map(|diagnostics| match diagnostics {
4538                LspPullDiagnostics::Default => None,
4539                LspPullDiagnostics::Response {
4540                    server_id,
4541                    uri,
4542                    diagnostics,
4543                    registration_id,
4544                } => {
4545                    let mut changed = false;
4546                    let (diagnostics, result_id) = match diagnostics {
4547                        PulledDiagnostics::Unchanged { result_id } => (Vec::new(), Some(result_id)),
4548                        PulledDiagnostics::Changed {
4549                            result_id,
4550                            diagnostics,
4551                        } => {
4552                            changed = true;
4553                            (diagnostics, result_id)
4554                        }
4555                    };
4556                    Some(proto::PulledDiagnostics {
4557                        changed,
4558                        result_id: result_id.map(|id| id.to_string()),
4559                        uri: uri.to_string(),
4560                        server_id: server_id.to_proto(),
4561                        diagnostics: diagnostics
4562                            .into_iter()
4563                            .filter_map(|diagnostic| {
4564                                GetDocumentDiagnostics::serialize_lsp_diagnostic(diagnostic)
4565                                    .context("serializing diagnostics")
4566                                    .log_err()
4567                            })
4568                            .collect(),
4569                        registration_id: registration_id.as_ref().map(ToString::to_string),
4570                    })
4571                }
4572            })
4573            .collect();
4574
4575        proto::GetDocumentDiagnosticsResponse { pulled_diagnostics }
4576    }
4577
4578    async fn response_from_proto(
4579        self,
4580        response: proto::GetDocumentDiagnosticsResponse,
4581        _: Entity<LspStore>,
4582        _: Entity<Buffer>,
4583        _: AsyncApp,
4584    ) -> Result<Self::Response> {
4585        Ok(Self::diagnostics_from_proto(response))
4586    }
4587
4588    fn buffer_id_from_proto(message: &proto::GetDocumentDiagnostics) -> Result<BufferId> {
4589        BufferId::new(message.buffer_id)
4590    }
4591}
4592
4593#[async_trait(?Send)]
4594impl LspCommand for GetDocumentColor {
4595    type Response = Vec<DocumentColor>;
4596    type LspRequest = lsp::request::DocumentColor;
4597    type ProtoRequest = proto::GetDocumentColor;
4598
4599    fn display_name(&self) -> &str {
4600        "Document color"
4601    }
4602
4603    fn check_capabilities(&self, server_capabilities: AdapterServerCapabilities) -> bool {
4604        server_capabilities
4605            .server_capabilities
4606            .color_provider
4607            .as_ref()
4608            .is_some_and(|capability| match capability {
4609                lsp::ColorProviderCapability::Simple(supported) => *supported,
4610                lsp::ColorProviderCapability::ColorProvider(..) => true,
4611                lsp::ColorProviderCapability::Options(..) => true,
4612            })
4613    }
4614
4615    fn to_lsp(
4616        &self,
4617        path: &Path,
4618        _: &Buffer,
4619        _: &Arc<LanguageServer>,
4620        _: &App,
4621    ) -> Result<lsp::DocumentColorParams> {
4622        Ok(lsp::DocumentColorParams {
4623            text_document: make_text_document_identifier(path)?,
4624            work_done_progress_params: Default::default(),
4625            partial_result_params: Default::default(),
4626        })
4627    }
4628
4629    async fn response_from_lsp(
4630        self,
4631        message: Vec<lsp::ColorInformation>,
4632        _: Entity<LspStore>,
4633        _: Entity<Buffer>,
4634        _: LanguageServerId,
4635        _: AsyncApp,
4636    ) -> Result<Self::Response> {
4637        Ok(message
4638            .into_iter()
4639            .map(|color| DocumentColor {
4640                lsp_range: color.range,
4641                color: color.color,
4642                resolved: false,
4643                color_presentations: Vec::new(),
4644            })
4645            .collect())
4646    }
4647
4648    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> Self::ProtoRequest {
4649        proto::GetDocumentColor {
4650            project_id,
4651            buffer_id: buffer.remote_id().to_proto(),
4652            version: serialize_version(&buffer.version()),
4653        }
4654    }
4655
4656    async fn from_proto(
4657        _: Self::ProtoRequest,
4658        _: Entity<LspStore>,
4659        _: Entity<Buffer>,
4660        _: AsyncApp,
4661    ) -> Result<Self> {
4662        Ok(Self {})
4663    }
4664
4665    fn response_to_proto(
4666        response: Self::Response,
4667        _: &mut LspStore,
4668        _: PeerId,
4669        buffer_version: &clock::Global,
4670        _: &mut App,
4671    ) -> proto::GetDocumentColorResponse {
4672        proto::GetDocumentColorResponse {
4673            colors: response
4674                .into_iter()
4675                .map(|color| {
4676                    let start = point_from_lsp(color.lsp_range.start).0;
4677                    let end = point_from_lsp(color.lsp_range.end).0;
4678                    proto::ColorInformation {
4679                        red: color.color.red,
4680                        green: color.color.green,
4681                        blue: color.color.blue,
4682                        alpha: color.color.alpha,
4683                        lsp_range_start: Some(proto::PointUtf16 {
4684                            row: start.row,
4685                            column: start.column,
4686                        }),
4687                        lsp_range_end: Some(proto::PointUtf16 {
4688                            row: end.row,
4689                            column: end.column,
4690                        }),
4691                    }
4692                })
4693                .collect(),
4694            version: serialize_version(buffer_version),
4695        }
4696    }
4697
4698    async fn response_from_proto(
4699        self,
4700        message: proto::GetDocumentColorResponse,
4701        _: Entity<LspStore>,
4702        _: Entity<Buffer>,
4703        _: AsyncApp,
4704    ) -> Result<Self::Response> {
4705        Ok(message
4706            .colors
4707            .into_iter()
4708            .filter_map(|color| {
4709                let start = color.lsp_range_start?;
4710                let start = PointUtf16::new(start.row, start.column);
4711                let end = color.lsp_range_end?;
4712                let end = PointUtf16::new(end.row, end.column);
4713                Some(DocumentColor {
4714                    resolved: false,
4715                    color_presentations: Vec::new(),
4716                    lsp_range: lsp::Range {
4717                        start: point_to_lsp(start),
4718                        end: point_to_lsp(end),
4719                    },
4720                    color: lsp::Color {
4721                        red: color.red,
4722                        green: color.green,
4723                        blue: color.blue,
4724                        alpha: color.alpha,
4725                    },
4726                })
4727            })
4728            .collect())
4729    }
4730
4731    fn buffer_id_from_proto(message: &Self::ProtoRequest) -> Result<BufferId> {
4732        BufferId::new(message.buffer_id)
4733    }
4734}
4735
4736#[async_trait(?Send)]
4737impl LspCommand for GetFoldingRanges {
4738    type Response = Vec<LspFoldingRange>;
4739    type LspRequest = lsp::request::FoldingRangeRequest;
4740    type ProtoRequest = proto::GetFoldingRanges;
4741
4742    fn display_name(&self) -> &str {
4743        "Folding ranges"
4744    }
4745
4746    fn check_capabilities(&self, server_capabilities: AdapterServerCapabilities) -> bool {
4747        server_capabilities
4748            .server_capabilities
4749            .folding_range_provider
4750            .as_ref()
4751            .is_some_and(|capability| match capability {
4752                lsp::FoldingRangeProviderCapability::Simple(supported) => *supported,
4753                lsp::FoldingRangeProviderCapability::FoldingProvider(..)
4754                | lsp::FoldingRangeProviderCapability::Options(..) => true,
4755            })
4756    }
4757
4758    fn to_lsp(
4759        &self,
4760        path: &Path,
4761        _: &Buffer,
4762        _: &Arc<LanguageServer>,
4763        _: &App,
4764    ) -> Result<lsp::FoldingRangeParams> {
4765        Ok(lsp::FoldingRangeParams {
4766            text_document: make_text_document_identifier(path)?,
4767            work_done_progress_params: Default::default(),
4768            partial_result_params: Default::default(),
4769        })
4770    }
4771
4772    async fn response_from_lsp(
4773        self,
4774        message: Option<Vec<lsp::FoldingRange>>,
4775        _: Entity<LspStore>,
4776        buffer: Entity<Buffer>,
4777        _: LanguageServerId,
4778        cx: AsyncApp,
4779    ) -> Result<Self::Response> {
4780        let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4781        let max_point = snapshot.max_point_utf16();
4782        Ok(message
4783            .unwrap_or_default()
4784            .into_iter()
4785            .filter(|range| range.start_line < range.end_line)
4786            .filter(|range| range.start_line <= max_point.row && range.end_line <= max_point.row)
4787            .map(|folding_range| {
4788                let start_col = folding_range.start_character.unwrap_or(u32::MAX);
4789                let end_col = folding_range.end_character.unwrap_or(u32::MAX);
4790                let start = snapshot.clip_point_utf16(
4791                    Unclipped(PointUtf16::new(folding_range.start_line, start_col)),
4792                    Bias::Right,
4793                );
4794                let end = snapshot.clip_point_utf16(
4795                    Unclipped(PointUtf16::new(folding_range.end_line, end_col)),
4796                    Bias::Left,
4797                );
4798                let start = snapshot.anchor_after(start);
4799                let end = snapshot.anchor_before(end);
4800                let collapsed_text = folding_range
4801                    .collapsed_text
4802                    .filter(|t| !t.is_empty())
4803                    .map(|t| SharedString::from(crate::lsp_store::collapse_newlines(&t, " ")));
4804                LspFoldingRange {
4805                    range: start..end,
4806                    collapsed_text,
4807                }
4808            })
4809            .collect())
4810    }
4811
4812    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> Self::ProtoRequest {
4813        proto::GetFoldingRanges {
4814            project_id,
4815            buffer_id: buffer.remote_id().to_proto(),
4816            version: serialize_version(&buffer.version()),
4817        }
4818    }
4819
4820    async fn from_proto(
4821        _: Self::ProtoRequest,
4822        _: Entity<LspStore>,
4823        _: Entity<Buffer>,
4824        _: AsyncApp,
4825    ) -> Result<Self> {
4826        Ok(Self)
4827    }
4828
4829    fn response_to_proto(
4830        response: Self::Response,
4831        _: &mut LspStore,
4832        _: PeerId,
4833        buffer_version: &clock::Global,
4834        _: &mut App,
4835    ) -> proto::GetFoldingRangesResponse {
4836        let mut ranges = Vec::with_capacity(response.len());
4837        let mut collapsed_texts = Vec::with_capacity(response.len());
4838        for folding_range in response {
4839            ranges.push(serialize_anchor_range(folding_range.range));
4840            collapsed_texts.push(
4841                folding_range
4842                    .collapsed_text
4843                    .map(|t| t.to_string())
4844                    .unwrap_or_default(),
4845            );
4846        }
4847        proto::GetFoldingRangesResponse {
4848            ranges,
4849            collapsed_texts,
4850            version: serialize_version(buffer_version),
4851        }
4852    }
4853
4854    async fn response_from_proto(
4855        self,
4856        message: proto::GetFoldingRangesResponse,
4857        _: Entity<LspStore>,
4858        buffer: Entity<Buffer>,
4859        mut cx: AsyncApp,
4860    ) -> Result<Self::Response> {
4861        buffer
4862            .update(&mut cx, |buffer, _| {
4863                buffer.wait_for_version(deserialize_version(&message.version))
4864            })
4865            .await?;
4866        message
4867            .ranges
4868            .into_iter()
4869            .zip(
4870                message
4871                    .collapsed_texts
4872                    .into_iter()
4873                    .map(Some)
4874                    .chain(std::iter::repeat(None)),
4875            )
4876            .map(|(range, collapsed_text)| {
4877                Ok(LspFoldingRange {
4878                    range: deserialize_anchor_range(range)?,
4879                    collapsed_text: collapsed_text
4880                        .filter(|t| !t.is_empty())
4881                        .map(SharedString::from),
4882                })
4883            })
4884            .collect()
4885    }
4886
4887    fn buffer_id_from_proto(message: &Self::ProtoRequest) -> Result<BufferId> {
4888        BufferId::new(message.buffer_id)
4889    }
4890}
4891
4892fn process_related_documents(
4893    diagnostics: &mut HashMap<lsp::Uri, LspPullDiagnostics>,
4894    server_id: LanguageServerId,
4895    documents: impl IntoIterator<Item = (lsp::Uri, lsp::DocumentDiagnosticReportKind)>,
4896    registration_id: Option<SharedString>,
4897) {
4898    for (url, report_kind) in documents {
4899        match report_kind {
4900            lsp::DocumentDiagnosticReportKind::Full(report) => process_full_diagnostics_report(
4901                diagnostics,
4902                server_id,
4903                url,
4904                report,
4905                registration_id.clone(),
4906            ),
4907            lsp::DocumentDiagnosticReportKind::Unchanged(report) => {
4908                process_unchanged_diagnostics_report(
4909                    diagnostics,
4910                    server_id,
4911                    url,
4912                    report,
4913                    registration_id.clone(),
4914                )
4915            }
4916        }
4917    }
4918}
4919
4920fn process_unchanged_diagnostics_report(
4921    diagnostics: &mut HashMap<lsp::Uri, LspPullDiagnostics>,
4922    server_id: LanguageServerId,
4923    uri: lsp::Uri,
4924    report: lsp::UnchangedDocumentDiagnosticReport,
4925    registration_id: Option<SharedString>,
4926) {
4927    let result_id = SharedString::new(report.result_id);
4928    match diagnostics.entry(uri.clone()) {
4929        hash_map::Entry::Occupied(mut o) => match o.get_mut() {
4930            LspPullDiagnostics::Default => {
4931                o.insert(LspPullDiagnostics::Response {
4932                    server_id,
4933                    uri,
4934                    diagnostics: PulledDiagnostics::Unchanged { result_id },
4935                    registration_id,
4936                });
4937            }
4938            LspPullDiagnostics::Response {
4939                server_id: existing_server_id,
4940                uri: existing_uri,
4941                diagnostics: existing_diagnostics,
4942                ..
4943            } => {
4944                if server_id != *existing_server_id || &uri != existing_uri {
4945                    debug_panic!(
4946                        "Unexpected state: file {uri} has two different sets of diagnostics reported"
4947                    );
4948                }
4949                match existing_diagnostics {
4950                    PulledDiagnostics::Unchanged { .. } => {
4951                        *existing_diagnostics = PulledDiagnostics::Unchanged { result_id };
4952                    }
4953                    PulledDiagnostics::Changed { .. } => {}
4954                }
4955            }
4956        },
4957        hash_map::Entry::Vacant(v) => {
4958            v.insert(LspPullDiagnostics::Response {
4959                server_id,
4960                uri,
4961                diagnostics: PulledDiagnostics::Unchanged { result_id },
4962                registration_id,
4963            });
4964        }
4965    }
4966}
4967
4968fn process_full_diagnostics_report(
4969    diagnostics: &mut HashMap<lsp::Uri, LspPullDiagnostics>,
4970    server_id: LanguageServerId,
4971    uri: lsp::Uri,
4972    report: lsp::FullDocumentDiagnosticReport,
4973    registration_id: Option<SharedString>,
4974) {
4975    let result_id = report.result_id.map(SharedString::new);
4976    match diagnostics.entry(uri.clone()) {
4977        hash_map::Entry::Occupied(mut o) => match o.get_mut() {
4978            LspPullDiagnostics::Default => {
4979                o.insert(LspPullDiagnostics::Response {
4980                    server_id,
4981                    uri,
4982                    diagnostics: PulledDiagnostics::Changed {
4983                        result_id,
4984                        diagnostics: report.items,
4985                    },
4986                    registration_id,
4987                });
4988            }
4989            LspPullDiagnostics::Response {
4990                server_id: existing_server_id,
4991                uri: existing_uri,
4992                diagnostics: existing_diagnostics,
4993                ..
4994            } => {
4995                if server_id != *existing_server_id || &uri != existing_uri {
4996                    debug_panic!(
4997                        "Unexpected state: file {uri} has two different sets of diagnostics reported"
4998                    );
4999                }
5000                match existing_diagnostics {
5001                    PulledDiagnostics::Unchanged { .. } => {
5002                        *existing_diagnostics = PulledDiagnostics::Changed {
5003                            result_id,
5004                            diagnostics: report.items,
5005                        };
5006                    }
5007                    PulledDiagnostics::Changed {
5008                        result_id: existing_result_id,
5009                        diagnostics: existing_diagnostics,
5010                    } => {
5011                        if result_id.is_some() {
5012                            *existing_result_id = result_id;
5013                        }
5014                        existing_diagnostics.extend(report.items);
5015                    }
5016                }
5017            }
5018        },
5019        hash_map::Entry::Vacant(v) => {
5020            v.insert(LspPullDiagnostics::Response {
5021                server_id,
5022                uri,
5023                diagnostics: PulledDiagnostics::Changed {
5024                    result_id,
5025                    diagnostics: report.items,
5026                },
5027                registration_id,
5028            });
5029        }
5030    }
5031}