lsp_command.rs

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