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, Clone, Copy)]
 175pub struct GetDefinitions {
 176    pub position: PointUtf16,
 177}
 178
 179#[derive(Debug, Clone, Copy)]
 180pub(crate) struct GetDeclarations {
 181    pub position: PointUtf16,
 182}
 183
 184#[derive(Debug, Clone, Copy)]
 185pub(crate) struct GetTypeDefinitions {
 186    pub position: PointUtf16,
 187}
 188
 189#[derive(Debug, Clone, Copy)]
 190pub(crate) struct GetImplementations {
 191    pub position: PointUtf16,
 192}
 193
 194#[derive(Debug, Clone, Copy)]
 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, false);
 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 GetDefinitions {
 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 GetDeclarations {
 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 GetImplementations {
 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 GetTypeDefinitions {
 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        lsp_store: Entity<LspStore>,
1850        _: Entity<Buffer>,
1851        _: LanguageServerId,
1852        cx: AsyncApp,
1853    ) -> Result<Self::Response> {
1854        let Some(message) = message else {
1855            return Ok(None);
1856        };
1857        cx.update(|cx| SignatureHelp::new(message, Some(lsp_store.read(cx).languages.clone()), cx))
1858    }
1859
1860    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> Self::ProtoRequest {
1861        let offset = buffer.point_utf16_to_offset(self.position);
1862        proto::GetSignatureHelp {
1863            project_id,
1864            buffer_id: buffer.remote_id().to_proto(),
1865            position: Some(serialize_anchor(&buffer.anchor_after(offset))),
1866            version: serialize_version(&buffer.version()),
1867        }
1868    }
1869
1870    async fn from_proto(
1871        payload: Self::ProtoRequest,
1872        _: Entity<LspStore>,
1873        buffer: Entity<Buffer>,
1874        mut cx: AsyncApp,
1875    ) -> Result<Self> {
1876        buffer
1877            .update(&mut cx, |buffer, _| {
1878                buffer.wait_for_version(deserialize_version(&payload.version))
1879            })?
1880            .await
1881            .with_context(|| format!("waiting for version for buffer {}", buffer.entity_id()))?;
1882        let buffer_snapshot = buffer.read_with(&mut cx, |buffer, _| buffer.snapshot())?;
1883        Ok(Self {
1884            position: payload
1885                .position
1886                .and_then(deserialize_anchor)
1887                .context("invalid position")?
1888                .to_point_utf16(&buffer_snapshot),
1889        })
1890    }
1891
1892    fn response_to_proto(
1893        response: Self::Response,
1894        _: &mut LspStore,
1895        _: PeerId,
1896        _: &Global,
1897        _: &mut App,
1898    ) -> proto::GetSignatureHelpResponse {
1899        proto::GetSignatureHelpResponse {
1900            signature_help: response
1901                .map(|signature_help| lsp_to_proto_signature(signature_help.original_data)),
1902        }
1903    }
1904
1905    async fn response_from_proto(
1906        self,
1907        response: proto::GetSignatureHelpResponse,
1908        lsp_store: Entity<LspStore>,
1909        _: Entity<Buffer>,
1910        cx: AsyncApp,
1911    ) -> Result<Self::Response> {
1912        cx.update(|cx| {
1913            response
1914                .signature_help
1915                .map(proto_to_lsp_signature)
1916                .and_then(|signature| {
1917                    SignatureHelp::new(signature, Some(lsp_store.read(cx).languages.clone()), cx)
1918                })
1919        })
1920    }
1921
1922    fn buffer_id_from_proto(message: &Self::ProtoRequest) -> Result<BufferId> {
1923        BufferId::new(message.buffer_id)
1924    }
1925}
1926
1927#[async_trait(?Send)]
1928impl LspCommand for GetHover {
1929    type Response = Option<Hover>;
1930    type LspRequest = lsp::request::HoverRequest;
1931    type ProtoRequest = proto::GetHover;
1932
1933    fn display_name(&self) -> &str {
1934        "Get hover"
1935    }
1936
1937    fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
1938        match capabilities.server_capabilities.hover_provider {
1939            Some(lsp::HoverProviderCapability::Simple(enabled)) => enabled,
1940            Some(lsp::HoverProviderCapability::Options(_)) => true,
1941            None => false,
1942        }
1943    }
1944
1945    fn to_lsp(
1946        &self,
1947        path: &Path,
1948        _: &Buffer,
1949        _: &Arc<LanguageServer>,
1950        _: &App,
1951    ) -> Result<lsp::HoverParams> {
1952        Ok(lsp::HoverParams {
1953            text_document_position_params: make_lsp_text_document_position(path, self.position)?,
1954            work_done_progress_params: Default::default(),
1955        })
1956    }
1957
1958    async fn response_from_lsp(
1959        self,
1960        message: Option<lsp::Hover>,
1961        _: Entity<LspStore>,
1962        buffer: Entity<Buffer>,
1963        _: LanguageServerId,
1964        mut cx: AsyncApp,
1965    ) -> Result<Self::Response> {
1966        let Some(hover) = message else {
1967            return Ok(None);
1968        };
1969
1970        let (language, range) = buffer.read_with(&mut cx, |buffer, _| {
1971            (
1972                buffer.language().cloned(),
1973                hover.range.map(|range| {
1974                    let token_start =
1975                        buffer.clip_point_utf16(point_from_lsp(range.start), Bias::Left);
1976                    let token_end = buffer.clip_point_utf16(point_from_lsp(range.end), Bias::Left);
1977                    buffer.anchor_after(token_start)..buffer.anchor_before(token_end)
1978                }),
1979            )
1980        })?;
1981
1982        fn hover_blocks_from_marked_string(marked_string: lsp::MarkedString) -> Option<HoverBlock> {
1983            let block = match marked_string {
1984                lsp::MarkedString::String(content) => HoverBlock {
1985                    text: content,
1986                    kind: HoverBlockKind::Markdown,
1987                },
1988                lsp::MarkedString::LanguageString(lsp::LanguageString { language, value }) => {
1989                    HoverBlock {
1990                        text: value,
1991                        kind: HoverBlockKind::Code { language },
1992                    }
1993                }
1994            };
1995            if block.text.is_empty() {
1996                None
1997            } else {
1998                Some(block)
1999            }
2000        }
2001
2002        let contents = match hover.contents {
2003            lsp::HoverContents::Scalar(marked_string) => {
2004                hover_blocks_from_marked_string(marked_string)
2005                    .into_iter()
2006                    .collect()
2007            }
2008            lsp::HoverContents::Array(marked_strings) => marked_strings
2009                .into_iter()
2010                .filter_map(hover_blocks_from_marked_string)
2011                .collect(),
2012            lsp::HoverContents::Markup(markup_content) => vec![HoverBlock {
2013                text: markup_content.value,
2014                kind: if markup_content.kind == lsp::MarkupKind::Markdown {
2015                    HoverBlockKind::Markdown
2016                } else {
2017                    HoverBlockKind::PlainText
2018                },
2019            }],
2020        };
2021
2022        Ok(Some(Hover {
2023            contents,
2024            range,
2025            language,
2026        }))
2027    }
2028
2029    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> Self::ProtoRequest {
2030        proto::GetHover {
2031            project_id,
2032            buffer_id: buffer.remote_id().into(),
2033            position: Some(language::proto::serialize_anchor(
2034                &buffer.anchor_before(self.position),
2035            )),
2036            version: serialize_version(&buffer.version),
2037        }
2038    }
2039
2040    async fn from_proto(
2041        message: Self::ProtoRequest,
2042        _: Entity<LspStore>,
2043        buffer: Entity<Buffer>,
2044        mut cx: AsyncApp,
2045    ) -> Result<Self> {
2046        let position = message
2047            .position
2048            .and_then(deserialize_anchor)
2049            .context("invalid position")?;
2050        buffer
2051            .update(&mut cx, |buffer, _| {
2052                buffer.wait_for_version(deserialize_version(&message.version))
2053            })?
2054            .await?;
2055        Ok(Self {
2056            position: buffer.read_with(&mut cx, |buffer, _| position.to_point_utf16(buffer))?,
2057        })
2058    }
2059
2060    fn response_to_proto(
2061        response: Self::Response,
2062        _: &mut LspStore,
2063        _: PeerId,
2064        _: &clock::Global,
2065        _: &mut App,
2066    ) -> proto::GetHoverResponse {
2067        if let Some(response) = response {
2068            let (start, end) = if let Some(range) = response.range {
2069                (
2070                    Some(language::proto::serialize_anchor(&range.start)),
2071                    Some(language::proto::serialize_anchor(&range.end)),
2072                )
2073            } else {
2074                (None, None)
2075            };
2076
2077            let contents = response
2078                .contents
2079                .into_iter()
2080                .map(|block| proto::HoverBlock {
2081                    text: block.text,
2082                    is_markdown: block.kind == HoverBlockKind::Markdown,
2083                    language: if let HoverBlockKind::Code { language } = block.kind {
2084                        Some(language)
2085                    } else {
2086                        None
2087                    },
2088                })
2089                .collect();
2090
2091            proto::GetHoverResponse {
2092                start,
2093                end,
2094                contents,
2095            }
2096        } else {
2097            proto::GetHoverResponse {
2098                start: None,
2099                end: None,
2100                contents: Vec::new(),
2101            }
2102        }
2103    }
2104
2105    async fn response_from_proto(
2106        self,
2107        message: proto::GetHoverResponse,
2108        _: Entity<LspStore>,
2109        buffer: Entity<Buffer>,
2110        mut cx: AsyncApp,
2111    ) -> Result<Self::Response> {
2112        let contents: Vec<_> = message
2113            .contents
2114            .into_iter()
2115            .map(|block| HoverBlock {
2116                text: block.text,
2117                kind: if let Some(language) = block.language {
2118                    HoverBlockKind::Code { language }
2119                } else if block.is_markdown {
2120                    HoverBlockKind::Markdown
2121                } else {
2122                    HoverBlockKind::PlainText
2123                },
2124            })
2125            .collect();
2126        if contents.is_empty() {
2127            return Ok(None);
2128        }
2129
2130        let language = buffer.read_with(&mut cx, |buffer, _| buffer.language().cloned())?;
2131        let range = if let (Some(start), Some(end)) = (message.start, message.end) {
2132            language::proto::deserialize_anchor(start)
2133                .and_then(|start| language::proto::deserialize_anchor(end).map(|end| start..end))
2134        } else {
2135            None
2136        };
2137        if let Some(range) = range.as_ref() {
2138            buffer
2139                .update(&mut cx, |buffer, _| {
2140                    buffer.wait_for_anchors([range.start, range.end])
2141                })?
2142                .await?;
2143        }
2144
2145        Ok(Some(Hover {
2146            contents,
2147            range,
2148            language,
2149        }))
2150    }
2151
2152    fn buffer_id_from_proto(message: &Self::ProtoRequest) -> Result<BufferId> {
2153        BufferId::new(message.buffer_id)
2154    }
2155}
2156
2157#[async_trait(?Send)]
2158impl LspCommand for GetCompletions {
2159    type Response = CoreCompletionResponse;
2160    type LspRequest = lsp::request::Completion;
2161    type ProtoRequest = proto::GetCompletions;
2162
2163    fn display_name(&self) -> &str {
2164        "Get completion"
2165    }
2166
2167    fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
2168        capabilities
2169            .server_capabilities
2170            .completion_provider
2171            .is_some()
2172    }
2173
2174    fn to_lsp(
2175        &self,
2176        path: &Path,
2177        _: &Buffer,
2178        _: &Arc<LanguageServer>,
2179        _: &App,
2180    ) -> Result<lsp::CompletionParams> {
2181        Ok(lsp::CompletionParams {
2182            text_document_position: make_lsp_text_document_position(path, self.position)?,
2183            context: Some(self.context.clone()),
2184            work_done_progress_params: Default::default(),
2185            partial_result_params: Default::default(),
2186        })
2187    }
2188
2189    async fn response_from_lsp(
2190        self,
2191        completions: Option<lsp::CompletionResponse>,
2192        lsp_store: Entity<LspStore>,
2193        buffer: Entity<Buffer>,
2194        server_id: LanguageServerId,
2195        mut cx: AsyncApp,
2196    ) -> Result<Self::Response> {
2197        let mut response_list = None;
2198        let (mut completions, mut is_incomplete) = if let Some(completions) = completions {
2199            match completions {
2200                lsp::CompletionResponse::Array(completions) => (completions, false),
2201                lsp::CompletionResponse::List(mut list) => {
2202                    let is_incomplete = list.is_incomplete;
2203                    let items = std::mem::take(&mut list.items);
2204                    response_list = Some(list);
2205                    (items, is_incomplete)
2206                }
2207            }
2208        } else {
2209            (Vec::new(), false)
2210        };
2211
2212        let unfiltered_completions_count = completions.len();
2213
2214        let language_server_adapter = lsp_store
2215            .read_with(&mut cx, |lsp_store, _| {
2216                lsp_store.language_server_adapter_for_id(server_id)
2217            })?
2218            .with_context(|| format!("no language server with id {server_id}"))?;
2219
2220        let lsp_defaults = response_list
2221            .as_ref()
2222            .and_then(|list| list.item_defaults.clone())
2223            .map(Arc::new);
2224
2225        let mut completion_edits = Vec::new();
2226        buffer.update(&mut cx, |buffer, _cx| {
2227            let snapshot = buffer.snapshot();
2228            let clipped_position = buffer.clip_point_utf16(Unclipped(self.position), Bias::Left);
2229
2230            let mut range_for_token = None;
2231            completions.retain(|lsp_completion| {
2232                let lsp_edit = lsp_completion.text_edit.clone().or_else(|| {
2233                    let default_text_edit = lsp_defaults.as_deref()?.edit_range.as_ref()?;
2234                    let new_text = lsp_completion
2235                        .insert_text
2236                        .as_ref()
2237                        .unwrap_or(&lsp_completion.label)
2238                        .clone();
2239                    match default_text_edit {
2240                        CompletionListItemDefaultsEditRange::Range(range) => {
2241                            Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
2242                                range: *range,
2243                                new_text,
2244                            }))
2245                        }
2246                        CompletionListItemDefaultsEditRange::InsertAndReplace {
2247                            insert,
2248                            replace,
2249                        } => Some(lsp::CompletionTextEdit::InsertAndReplace(
2250                            lsp::InsertReplaceEdit {
2251                                new_text,
2252                                insert: *insert,
2253                                replace: *replace,
2254                            },
2255                        )),
2256                    }
2257                });
2258
2259                let edit = match lsp_edit {
2260                    // If the language server provides a range to overwrite, then
2261                    // check that the range is valid.
2262                    Some(completion_text_edit) => {
2263                        match parse_completion_text_edit(&completion_text_edit, &snapshot) {
2264                            Some(edit) => edit,
2265                            None => return false,
2266                        }
2267                    }
2268                    // If the language server does not provide a range, then infer
2269                    // the range based on the syntax tree.
2270                    None => {
2271                        if self.position != clipped_position {
2272                            log::info!("completion out of expected range ");
2273                            return false;
2274                        }
2275
2276                        let default_edit_range = lsp_defaults.as_ref().and_then(|lsp_defaults| {
2277                            lsp_defaults
2278                                .edit_range
2279                                .as_ref()
2280                                .and_then(|range| match range {
2281                                    CompletionListItemDefaultsEditRange::Range(r) => Some(r),
2282                                    _ => None,
2283                                })
2284                        });
2285
2286                        let range = if let Some(range) = default_edit_range {
2287                            let range = range_from_lsp(*range);
2288                            let start = snapshot.clip_point_utf16(range.start, Bias::Left);
2289                            let end = snapshot.clip_point_utf16(range.end, Bias::Left);
2290                            if start != range.start.0 || end != range.end.0 {
2291                                log::info!("completion out of expected range");
2292                                return false;
2293                            }
2294
2295                            snapshot.anchor_before(start)..snapshot.anchor_after(end)
2296                        } else {
2297                            range_for_token
2298                                .get_or_insert_with(|| {
2299                                    let offset = self.position.to_offset(&snapshot);
2300                                    let (range, kind) = snapshot.surrounding_word(offset, true);
2301                                    let range = if kind == Some(CharKind::Word) {
2302                                        range
2303                                    } else {
2304                                        offset..offset
2305                                    };
2306
2307                                    snapshot.anchor_before(range.start)
2308                                        ..snapshot.anchor_after(range.end)
2309                                })
2310                                .clone()
2311                        };
2312
2313                        // We already know text_edit is None here
2314                        let text = lsp_completion
2315                            .insert_text
2316                            .as_ref()
2317                            .unwrap_or(&lsp_completion.label)
2318                            .clone();
2319
2320                        ParsedCompletionEdit {
2321                            replace_range: range,
2322                            insert_range: None,
2323                            new_text: text,
2324                        }
2325                    }
2326                };
2327
2328                completion_edits.push(edit);
2329                true
2330            });
2331        })?;
2332
2333        // If completions were filtered out due to errors that may be transient, mark the result
2334        // incomplete so that it is re-queried.
2335        if unfiltered_completions_count != completions.len() {
2336            is_incomplete = true;
2337        }
2338
2339        language_server_adapter
2340            .process_completions(&mut completions)
2341            .await;
2342
2343        let completions = completions
2344            .into_iter()
2345            .zip(completion_edits)
2346            .map(|(mut lsp_completion, mut edit)| {
2347                LineEnding::normalize(&mut edit.new_text);
2348                if lsp_completion.data.is_none() {
2349                    if let Some(default_data) = lsp_defaults
2350                        .as_ref()
2351                        .and_then(|item_defaults| item_defaults.data.clone())
2352                    {
2353                        // Servers (e.g. JDTLS) prefer unchanged completions, when resolving the items later,
2354                        // so we do not insert the defaults here, but `data` is needed for resolving, so this is an exception.
2355                        lsp_completion.data = Some(default_data);
2356                    }
2357                }
2358                CoreCompletion {
2359                    replace_range: edit.replace_range,
2360                    new_text: edit.new_text,
2361                    source: CompletionSource::Lsp {
2362                        insert_range: edit.insert_range,
2363                        server_id,
2364                        lsp_completion: Box::new(lsp_completion),
2365                        lsp_defaults: lsp_defaults.clone(),
2366                        resolved: false,
2367                    },
2368                }
2369            })
2370            .collect();
2371
2372        Ok(CoreCompletionResponse {
2373            completions,
2374            is_incomplete,
2375        })
2376    }
2377
2378    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> proto::GetCompletions {
2379        let anchor = buffer.anchor_after(self.position);
2380        proto::GetCompletions {
2381            project_id,
2382            buffer_id: buffer.remote_id().into(),
2383            position: Some(language::proto::serialize_anchor(&anchor)),
2384            version: serialize_version(&buffer.version()),
2385        }
2386    }
2387
2388    async fn from_proto(
2389        message: proto::GetCompletions,
2390        _: Entity<LspStore>,
2391        buffer: Entity<Buffer>,
2392        mut cx: AsyncApp,
2393    ) -> Result<Self> {
2394        let version = deserialize_version(&message.version);
2395        buffer
2396            .update(&mut cx, |buffer, _| buffer.wait_for_version(version))?
2397            .await?;
2398        let position = message
2399            .position
2400            .and_then(language::proto::deserialize_anchor)
2401            .map(|p| {
2402                buffer.read_with(&mut cx, |buffer, _| {
2403                    buffer.clip_point_utf16(Unclipped(p.to_point_utf16(buffer)), Bias::Left)
2404                })
2405            })
2406            .context("invalid position")??;
2407        Ok(Self {
2408            position,
2409            context: CompletionContext {
2410                trigger_kind: CompletionTriggerKind::INVOKED,
2411                trigger_character: None,
2412            },
2413        })
2414    }
2415
2416    fn response_to_proto(
2417        response: CoreCompletionResponse,
2418        _: &mut LspStore,
2419        _: PeerId,
2420        buffer_version: &clock::Global,
2421        _: &mut App,
2422    ) -> proto::GetCompletionsResponse {
2423        proto::GetCompletionsResponse {
2424            completions: response
2425                .completions
2426                .iter()
2427                .map(LspStore::serialize_completion)
2428                .collect(),
2429            version: serialize_version(buffer_version),
2430            can_reuse: !response.is_incomplete,
2431        }
2432    }
2433
2434    async fn response_from_proto(
2435        self,
2436        message: proto::GetCompletionsResponse,
2437        _project: Entity<LspStore>,
2438        buffer: Entity<Buffer>,
2439        mut cx: AsyncApp,
2440    ) -> Result<Self::Response> {
2441        buffer
2442            .update(&mut cx, |buffer, _| {
2443                buffer.wait_for_version(deserialize_version(&message.version))
2444            })?
2445            .await?;
2446
2447        let completions = message
2448            .completions
2449            .into_iter()
2450            .map(LspStore::deserialize_completion)
2451            .collect::<Result<Vec<_>>>()?;
2452
2453        Ok(CoreCompletionResponse {
2454            completions,
2455            is_incomplete: !message.can_reuse,
2456        })
2457    }
2458
2459    fn buffer_id_from_proto(message: &proto::GetCompletions) -> Result<BufferId> {
2460        BufferId::new(message.buffer_id)
2461    }
2462}
2463
2464pub struct ParsedCompletionEdit {
2465    pub replace_range: Range<Anchor>,
2466    pub insert_range: Option<Range<Anchor>>,
2467    pub new_text: String,
2468}
2469
2470pub(crate) fn parse_completion_text_edit(
2471    edit: &lsp::CompletionTextEdit,
2472    snapshot: &BufferSnapshot,
2473) -> Option<ParsedCompletionEdit> {
2474    let (replace_range, insert_range, new_text) = match edit {
2475        lsp::CompletionTextEdit::Edit(edit) => (edit.range, None, &edit.new_text),
2476        lsp::CompletionTextEdit::InsertAndReplace(edit) => {
2477            (edit.replace, Some(edit.insert), &edit.new_text)
2478        }
2479    };
2480
2481    let replace_range = {
2482        let range = range_from_lsp(replace_range);
2483        let start = snapshot.clip_point_utf16(range.start, Bias::Left);
2484        let end = snapshot.clip_point_utf16(range.end, Bias::Left);
2485        if start != range.start.0 || end != range.end.0 {
2486            log::info!(
2487                "completion out of expected range, start: {start:?}, end: {end:?}, range: {range:?}"
2488            );
2489            return None;
2490        }
2491        snapshot.anchor_before(start)..snapshot.anchor_after(end)
2492    };
2493
2494    let insert_range = match insert_range {
2495        None => None,
2496        Some(insert_range) => {
2497            let range = range_from_lsp(insert_range);
2498            let start = snapshot.clip_point_utf16(range.start, Bias::Left);
2499            let end = snapshot.clip_point_utf16(range.end, Bias::Left);
2500            if start != range.start.0 || end != range.end.0 {
2501                log::info!("completion (insert) out of expected range");
2502                return None;
2503            }
2504            Some(snapshot.anchor_before(start)..snapshot.anchor_after(end))
2505        }
2506    };
2507
2508    Some(ParsedCompletionEdit {
2509        insert_range: insert_range,
2510        replace_range: replace_range,
2511        new_text: new_text.clone(),
2512    })
2513}
2514
2515#[async_trait(?Send)]
2516impl LspCommand for GetCodeActions {
2517    type Response = Vec<CodeAction>;
2518    type LspRequest = lsp::request::CodeActionRequest;
2519    type ProtoRequest = proto::GetCodeActions;
2520
2521    fn display_name(&self) -> &str {
2522        "Get code actions"
2523    }
2524
2525    fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
2526        match &capabilities.server_capabilities.code_action_provider {
2527            None => false,
2528            Some(lsp::CodeActionProviderCapability::Simple(false)) => false,
2529            _ => {
2530                // If we do know that we want specific code actions AND we know that
2531                // the server only supports specific code actions, then we want to filter
2532                // down to the ones that are supported.
2533                if let Some((requested, supported)) = self
2534                    .kinds
2535                    .as_ref()
2536                    .zip(Self::supported_code_action_kinds(capabilities))
2537                {
2538                    let server_supported = supported.into_iter().collect::<HashSet<_>>();
2539                    requested.iter().any(|kind| server_supported.contains(kind))
2540                } else {
2541                    true
2542                }
2543            }
2544        }
2545    }
2546
2547    fn to_lsp(
2548        &self,
2549        path: &Path,
2550        buffer: &Buffer,
2551        language_server: &Arc<LanguageServer>,
2552        _: &App,
2553    ) -> Result<lsp::CodeActionParams> {
2554        let mut relevant_diagnostics = Vec::new();
2555        for entry in buffer
2556            .snapshot()
2557            .diagnostics_in_range::<_, language::PointUtf16>(self.range.clone(), false)
2558        {
2559            relevant_diagnostics.push(entry.to_lsp_diagnostic_stub()?);
2560        }
2561
2562        let supported =
2563            Self::supported_code_action_kinds(language_server.adapter_server_capabilities());
2564
2565        let only = if let Some(requested) = &self.kinds {
2566            if let Some(supported_kinds) = supported {
2567                let server_supported = supported_kinds.into_iter().collect::<HashSet<_>>();
2568
2569                let filtered = requested
2570                    .iter()
2571                    .filter(|kind| server_supported.contains(kind))
2572                    .cloned()
2573                    .collect();
2574                Some(filtered)
2575            } else {
2576                Some(requested.clone())
2577            }
2578        } else {
2579            supported
2580        };
2581
2582        Ok(lsp::CodeActionParams {
2583            text_document: make_text_document_identifier(path)?,
2584            range: range_to_lsp(self.range.to_point_utf16(buffer))?,
2585            work_done_progress_params: Default::default(),
2586            partial_result_params: Default::default(),
2587            context: lsp::CodeActionContext {
2588                diagnostics: relevant_diagnostics,
2589                only,
2590                ..lsp::CodeActionContext::default()
2591            },
2592        })
2593    }
2594
2595    async fn response_from_lsp(
2596        self,
2597        actions: Option<lsp::CodeActionResponse>,
2598        lsp_store: Entity<LspStore>,
2599        _: Entity<Buffer>,
2600        server_id: LanguageServerId,
2601        cx: AsyncApp,
2602    ) -> Result<Vec<CodeAction>> {
2603        let requested_kinds_set = if let Some(kinds) = self.kinds {
2604            Some(kinds.into_iter().collect::<HashSet<_>>())
2605        } else {
2606            None
2607        };
2608
2609        let language_server = cx.update(|cx| {
2610            lsp_store
2611                .read(cx)
2612                .language_server_for_id(server_id)
2613                .with_context(|| {
2614                    format!("Missing the language server that just returned a response {server_id}")
2615                })
2616        })??;
2617
2618        let server_capabilities = language_server.capabilities();
2619        let available_commands = server_capabilities
2620            .execute_command_provider
2621            .as_ref()
2622            .map(|options| options.commands.as_slice())
2623            .unwrap_or_default();
2624        Ok(actions
2625            .unwrap_or_default()
2626            .into_iter()
2627            .filter_map(|entry| {
2628                let (lsp_action, resolved) = match entry {
2629                    lsp::CodeActionOrCommand::CodeAction(lsp_action) => {
2630                        if let Some(command) = lsp_action.command.as_ref() {
2631                            if !available_commands.contains(&command.command) {
2632                                return None;
2633                            }
2634                        }
2635                        (LspAction::Action(Box::new(lsp_action)), false)
2636                    }
2637                    lsp::CodeActionOrCommand::Command(command) => {
2638                        if available_commands.contains(&command.command) {
2639                            (LspAction::Command(command), true)
2640                        } else {
2641                            return None;
2642                        }
2643                    }
2644                };
2645
2646                if let Some((requested_kinds, kind)) =
2647                    requested_kinds_set.as_ref().zip(lsp_action.action_kind())
2648                {
2649                    if !requested_kinds.contains(&kind) {
2650                        return None;
2651                    }
2652                }
2653
2654                Some(CodeAction {
2655                    server_id,
2656                    range: self.range.clone(),
2657                    lsp_action,
2658                    resolved,
2659                })
2660            })
2661            .collect())
2662    }
2663
2664    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> proto::GetCodeActions {
2665        proto::GetCodeActions {
2666            project_id,
2667            buffer_id: buffer.remote_id().into(),
2668            start: Some(language::proto::serialize_anchor(&self.range.start)),
2669            end: Some(language::proto::serialize_anchor(&self.range.end)),
2670            version: serialize_version(&buffer.version()),
2671        }
2672    }
2673
2674    async fn from_proto(
2675        message: proto::GetCodeActions,
2676        _: Entity<LspStore>,
2677        buffer: Entity<Buffer>,
2678        mut cx: AsyncApp,
2679    ) -> Result<Self> {
2680        let start = message
2681            .start
2682            .and_then(language::proto::deserialize_anchor)
2683            .context("invalid start")?;
2684        let end = message
2685            .end
2686            .and_then(language::proto::deserialize_anchor)
2687            .context("invalid end")?;
2688        buffer
2689            .update(&mut cx, |buffer, _| {
2690                buffer.wait_for_version(deserialize_version(&message.version))
2691            })?
2692            .await?;
2693
2694        Ok(Self {
2695            range: start..end,
2696            kinds: None,
2697        })
2698    }
2699
2700    fn response_to_proto(
2701        code_actions: Vec<CodeAction>,
2702        _: &mut LspStore,
2703        _: PeerId,
2704        buffer_version: &clock::Global,
2705        _: &mut App,
2706    ) -> proto::GetCodeActionsResponse {
2707        proto::GetCodeActionsResponse {
2708            actions: code_actions
2709                .iter()
2710                .map(LspStore::serialize_code_action)
2711                .collect(),
2712            version: serialize_version(buffer_version),
2713        }
2714    }
2715
2716    async fn response_from_proto(
2717        self,
2718        message: proto::GetCodeActionsResponse,
2719        _: Entity<LspStore>,
2720        buffer: Entity<Buffer>,
2721        mut cx: AsyncApp,
2722    ) -> Result<Vec<CodeAction>> {
2723        buffer
2724            .update(&mut cx, |buffer, _| {
2725                buffer.wait_for_version(deserialize_version(&message.version))
2726            })?
2727            .await?;
2728        message
2729            .actions
2730            .into_iter()
2731            .map(LspStore::deserialize_code_action)
2732            .collect()
2733    }
2734
2735    fn buffer_id_from_proto(message: &proto::GetCodeActions) -> Result<BufferId> {
2736        BufferId::new(message.buffer_id)
2737    }
2738}
2739
2740impl GetCodeActions {
2741    fn supported_code_action_kinds(
2742        capabilities: AdapterServerCapabilities,
2743    ) -> Option<Vec<CodeActionKind>> {
2744        match capabilities.server_capabilities.code_action_provider {
2745            Some(lsp::CodeActionProviderCapability::Options(CodeActionOptions {
2746                code_action_kinds: Some(supported_action_kinds),
2747                ..
2748            })) => Some(supported_action_kinds.clone()),
2749            _ => capabilities.code_action_kinds,
2750        }
2751    }
2752
2753    pub fn can_resolve_actions(capabilities: &ServerCapabilities) -> bool {
2754        capabilities
2755            .code_action_provider
2756            .as_ref()
2757            .and_then(|options| match options {
2758                lsp::CodeActionProviderCapability::Simple(_is_supported) => None,
2759                lsp::CodeActionProviderCapability::Options(options) => options.resolve_provider,
2760            })
2761            .unwrap_or(false)
2762    }
2763}
2764
2765#[async_trait(?Send)]
2766impl LspCommand for OnTypeFormatting {
2767    type Response = Option<Transaction>;
2768    type LspRequest = lsp::request::OnTypeFormatting;
2769    type ProtoRequest = proto::OnTypeFormatting;
2770
2771    fn display_name(&self) -> &str {
2772        "Formatting on typing"
2773    }
2774
2775    fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
2776        let Some(on_type_formatting_options) = &capabilities
2777            .server_capabilities
2778            .document_on_type_formatting_provider
2779        else {
2780            return false;
2781        };
2782        on_type_formatting_options
2783            .first_trigger_character
2784            .contains(&self.trigger)
2785            || on_type_formatting_options
2786                .more_trigger_character
2787                .iter()
2788                .flatten()
2789                .any(|chars| chars.contains(&self.trigger))
2790    }
2791
2792    fn to_lsp(
2793        &self,
2794        path: &Path,
2795        _: &Buffer,
2796        _: &Arc<LanguageServer>,
2797        _: &App,
2798    ) -> Result<lsp::DocumentOnTypeFormattingParams> {
2799        Ok(lsp::DocumentOnTypeFormattingParams {
2800            text_document_position: make_lsp_text_document_position(path, self.position)?,
2801            ch: self.trigger.clone(),
2802            options: self.options.clone(),
2803        })
2804    }
2805
2806    async fn response_from_lsp(
2807        self,
2808        message: Option<Vec<lsp::TextEdit>>,
2809        lsp_store: Entity<LspStore>,
2810        buffer: Entity<Buffer>,
2811        server_id: LanguageServerId,
2812        mut cx: AsyncApp,
2813    ) -> Result<Option<Transaction>> {
2814        if let Some(edits) = message {
2815            let (lsp_adapter, lsp_server) =
2816                language_server_for_buffer(&lsp_store, &buffer, server_id, &mut cx)?;
2817            LocalLspStore::deserialize_text_edits(
2818                lsp_store,
2819                buffer,
2820                edits,
2821                self.push_to_history,
2822                lsp_adapter,
2823                lsp_server,
2824                &mut cx,
2825            )
2826            .await
2827        } else {
2828            Ok(None)
2829        }
2830    }
2831
2832    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> proto::OnTypeFormatting {
2833        proto::OnTypeFormatting {
2834            project_id,
2835            buffer_id: buffer.remote_id().into(),
2836            position: Some(language::proto::serialize_anchor(
2837                &buffer.anchor_before(self.position),
2838            )),
2839            trigger: self.trigger.clone(),
2840            version: serialize_version(&buffer.version()),
2841        }
2842    }
2843
2844    async fn from_proto(
2845        message: proto::OnTypeFormatting,
2846        _: Entity<LspStore>,
2847        buffer: Entity<Buffer>,
2848        mut cx: AsyncApp,
2849    ) -> Result<Self> {
2850        let position = message
2851            .position
2852            .and_then(deserialize_anchor)
2853            .context("invalid position")?;
2854        buffer
2855            .update(&mut cx, |buffer, _| {
2856                buffer.wait_for_version(deserialize_version(&message.version))
2857            })?
2858            .await?;
2859
2860        let options = buffer.update(&mut cx, |buffer, cx| {
2861            lsp_formatting_options(
2862                language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx).as_ref(),
2863            )
2864        })?;
2865
2866        Ok(Self {
2867            position: buffer.read_with(&mut cx, |buffer, _| position.to_point_utf16(buffer))?,
2868            trigger: message.trigger.clone(),
2869            options,
2870            push_to_history: false,
2871        })
2872    }
2873
2874    fn response_to_proto(
2875        response: Option<Transaction>,
2876        _: &mut LspStore,
2877        _: PeerId,
2878        _: &clock::Global,
2879        _: &mut App,
2880    ) -> proto::OnTypeFormattingResponse {
2881        proto::OnTypeFormattingResponse {
2882            transaction: response
2883                .map(|transaction| language::proto::serialize_transaction(&transaction)),
2884        }
2885    }
2886
2887    async fn response_from_proto(
2888        self,
2889        message: proto::OnTypeFormattingResponse,
2890        _: Entity<LspStore>,
2891        _: Entity<Buffer>,
2892        _: AsyncApp,
2893    ) -> Result<Option<Transaction>> {
2894        let Some(transaction) = message.transaction else {
2895            return Ok(None);
2896        };
2897        Ok(Some(language::proto::deserialize_transaction(transaction)?))
2898    }
2899
2900    fn buffer_id_from_proto(message: &proto::OnTypeFormatting) -> Result<BufferId> {
2901        BufferId::new(message.buffer_id)
2902    }
2903}
2904
2905impl InlayHints {
2906    pub async fn lsp_to_project_hint(
2907        lsp_hint: lsp::InlayHint,
2908        buffer_handle: &Entity<Buffer>,
2909        server_id: LanguageServerId,
2910        resolve_state: ResolveState,
2911        force_no_type_left_padding: bool,
2912        cx: &mut AsyncApp,
2913    ) -> anyhow::Result<InlayHint> {
2914        let kind = lsp_hint.kind.and_then(|kind| match kind {
2915            lsp::InlayHintKind::TYPE => Some(InlayHintKind::Type),
2916            lsp::InlayHintKind::PARAMETER => Some(InlayHintKind::Parameter),
2917            _ => None,
2918        });
2919
2920        let position = buffer_handle.read_with(cx, |buffer, _| {
2921            let position = buffer.clip_point_utf16(point_from_lsp(lsp_hint.position), Bias::Left);
2922            if kind == Some(InlayHintKind::Parameter) {
2923                buffer.anchor_before(position)
2924            } else {
2925                buffer.anchor_after(position)
2926            }
2927        })?;
2928        let label = Self::lsp_inlay_label_to_project(lsp_hint.label, server_id)
2929            .await
2930            .context("lsp to project inlay hint conversion")?;
2931        let padding_left = if force_no_type_left_padding && kind == Some(InlayHintKind::Type) {
2932            false
2933        } else {
2934            lsp_hint.padding_left.unwrap_or(false)
2935        };
2936
2937        Ok(InlayHint {
2938            position,
2939            padding_left,
2940            padding_right: lsp_hint.padding_right.unwrap_or(false),
2941            label,
2942            kind,
2943            tooltip: lsp_hint.tooltip.map(|tooltip| match tooltip {
2944                lsp::InlayHintTooltip::String(s) => InlayHintTooltip::String(s),
2945                lsp::InlayHintTooltip::MarkupContent(markup_content) => {
2946                    InlayHintTooltip::MarkupContent(MarkupContent {
2947                        kind: match markup_content.kind {
2948                            lsp::MarkupKind::PlainText => HoverBlockKind::PlainText,
2949                            lsp::MarkupKind::Markdown => HoverBlockKind::Markdown,
2950                        },
2951                        value: markup_content.value,
2952                    })
2953                }
2954            }),
2955            resolve_state,
2956        })
2957    }
2958
2959    async fn lsp_inlay_label_to_project(
2960        lsp_label: lsp::InlayHintLabel,
2961        server_id: LanguageServerId,
2962    ) -> anyhow::Result<InlayHintLabel> {
2963        let label = match lsp_label {
2964            lsp::InlayHintLabel::String(s) => InlayHintLabel::String(s),
2965            lsp::InlayHintLabel::LabelParts(lsp_parts) => {
2966                let mut parts = Vec::with_capacity(lsp_parts.len());
2967                for lsp_part in lsp_parts {
2968                    parts.push(InlayHintLabelPart {
2969                        value: lsp_part.value,
2970                        tooltip: lsp_part.tooltip.map(|tooltip| match tooltip {
2971                            lsp::InlayHintLabelPartTooltip::String(s) => {
2972                                InlayHintLabelPartTooltip::String(s)
2973                            }
2974                            lsp::InlayHintLabelPartTooltip::MarkupContent(markup_content) => {
2975                                InlayHintLabelPartTooltip::MarkupContent(MarkupContent {
2976                                    kind: match markup_content.kind {
2977                                        lsp::MarkupKind::PlainText => HoverBlockKind::PlainText,
2978                                        lsp::MarkupKind::Markdown => HoverBlockKind::Markdown,
2979                                    },
2980                                    value: markup_content.value,
2981                                })
2982                            }
2983                        }),
2984                        location: Some(server_id).zip(lsp_part.location),
2985                    });
2986                }
2987                InlayHintLabel::LabelParts(parts)
2988            }
2989        };
2990
2991        Ok(label)
2992    }
2993
2994    pub fn project_to_proto_hint(response_hint: InlayHint) -> proto::InlayHint {
2995        let (state, lsp_resolve_state) = match response_hint.resolve_state {
2996            ResolveState::Resolved => (0, None),
2997            ResolveState::CanResolve(server_id, resolve_data) => (
2998                1,
2999                Some(proto::resolve_state::LspResolveState {
3000                    server_id: server_id.0 as u64,
3001                    value: resolve_data.map(|json_data| {
3002                        serde_json::to_string(&json_data)
3003                            .expect("failed to serialize resolve json data")
3004                    }),
3005                }),
3006            ),
3007            ResolveState::Resolving => (2, None),
3008        };
3009        let resolve_state = Some(proto::ResolveState {
3010            state,
3011            lsp_resolve_state,
3012        });
3013        proto::InlayHint {
3014            position: Some(language::proto::serialize_anchor(&response_hint.position)),
3015            padding_left: response_hint.padding_left,
3016            padding_right: response_hint.padding_right,
3017            label: Some(proto::InlayHintLabel {
3018                label: Some(match response_hint.label {
3019                    InlayHintLabel::String(s) => proto::inlay_hint_label::Label::Value(s),
3020                    InlayHintLabel::LabelParts(label_parts) => {
3021                        proto::inlay_hint_label::Label::LabelParts(proto::InlayHintLabelParts {
3022                            parts: label_parts.into_iter().map(|label_part| {
3023                                let location_url = label_part.location.as_ref().map(|(_, location)| location.uri.to_string());
3024                                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 });
3025                                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 });
3026                                proto::InlayHintLabelPart {
3027                                value: label_part.value,
3028                                tooltip: label_part.tooltip.map(|tooltip| {
3029                                    let proto_tooltip = match tooltip {
3030                                        InlayHintLabelPartTooltip::String(s) => proto::inlay_hint_label_part_tooltip::Content::Value(s),
3031                                        InlayHintLabelPartTooltip::MarkupContent(markup_content) => proto::inlay_hint_label_part_tooltip::Content::MarkupContent(proto::MarkupContent {
3032                                            is_markdown: markup_content.kind == HoverBlockKind::Markdown,
3033                                            value: markup_content.value,
3034                                        }),
3035                                    };
3036                                    proto::InlayHintLabelPartTooltip {content: Some(proto_tooltip)}
3037                                }),
3038                                location_url,
3039                                location_range_start,
3040                                location_range_end,
3041                                language_server_id: label_part.location.as_ref().map(|(server_id, _)| server_id.0 as u64),
3042                            }}).collect()
3043                        })
3044                    }
3045                }),
3046            }),
3047            kind: response_hint.kind.map(|kind| kind.name().to_string()),
3048            tooltip: response_hint.tooltip.map(|response_tooltip| {
3049                let proto_tooltip = match response_tooltip {
3050                    InlayHintTooltip::String(s) => proto::inlay_hint_tooltip::Content::Value(s),
3051                    InlayHintTooltip::MarkupContent(markup_content) => {
3052                        proto::inlay_hint_tooltip::Content::MarkupContent(proto::MarkupContent {
3053                            is_markdown: markup_content.kind == HoverBlockKind::Markdown,
3054                            value: markup_content.value,
3055                        })
3056                    }
3057                };
3058                proto::InlayHintTooltip {
3059                    content: Some(proto_tooltip),
3060                }
3061            }),
3062            resolve_state,
3063        }
3064    }
3065
3066    pub fn proto_to_project_hint(message_hint: proto::InlayHint) -> anyhow::Result<InlayHint> {
3067        let resolve_state = message_hint.resolve_state.as_ref().unwrap_or_else(|| {
3068            panic!("incorrect proto inlay hint message: no resolve state in hint {message_hint:?}",)
3069        });
3070        let resolve_state_data = resolve_state
3071            .lsp_resolve_state.as_ref()
3072            .map(|lsp_resolve_state| {
3073                let value = lsp_resolve_state.value.as_deref().map(|value| {
3074                    serde_json::from_str::<Option<lsp::LSPAny>>(value)
3075                        .with_context(|| format!("incorrect proto inlay hint message: non-json resolve state {lsp_resolve_state:?}"))
3076                }).transpose()?.flatten();
3077                anyhow::Ok((LanguageServerId(lsp_resolve_state.server_id as usize), value))
3078            })
3079            .transpose()?;
3080        let resolve_state = match resolve_state.state {
3081            0 => ResolveState::Resolved,
3082            1 => {
3083                let (server_id, lsp_resolve_state) = resolve_state_data.with_context(|| {
3084                    format!(
3085                        "No lsp resolve data for the hint that can be resolved: {message_hint:?}"
3086                    )
3087                })?;
3088                ResolveState::CanResolve(server_id, lsp_resolve_state)
3089            }
3090            2 => ResolveState::Resolving,
3091            invalid => {
3092                anyhow::bail!("Unexpected resolve state {invalid} for hint {message_hint:?}")
3093            }
3094        };
3095        Ok(InlayHint {
3096            position: message_hint
3097                .position
3098                .and_then(language::proto::deserialize_anchor)
3099                .context("invalid position")?,
3100            label: match message_hint
3101                .label
3102                .and_then(|label| label.label)
3103                .context("missing label")?
3104            {
3105                proto::inlay_hint_label::Label::Value(s) => InlayHintLabel::String(s),
3106                proto::inlay_hint_label::Label::LabelParts(parts) => {
3107                    let mut label_parts = Vec::new();
3108                    for part in parts.parts {
3109                        label_parts.push(InlayHintLabelPart {
3110                            value: part.value,
3111                            tooltip: part.tooltip.map(|tooltip| match tooltip.content {
3112                                Some(proto::inlay_hint_label_part_tooltip::Content::Value(s)) => {
3113                                    InlayHintLabelPartTooltip::String(s)
3114                                }
3115                                Some(
3116                                    proto::inlay_hint_label_part_tooltip::Content::MarkupContent(
3117                                        markup_content,
3118                                    ),
3119                                ) => InlayHintLabelPartTooltip::MarkupContent(MarkupContent {
3120                                    kind: if markup_content.is_markdown {
3121                                        HoverBlockKind::Markdown
3122                                    } else {
3123                                        HoverBlockKind::PlainText
3124                                    },
3125                                    value: markup_content.value,
3126                                }),
3127                                None => InlayHintLabelPartTooltip::String(String::new()),
3128                            }),
3129                            location: {
3130                                match part
3131                                    .location_url
3132                                    .zip(
3133                                        part.location_range_start.and_then(|start| {
3134                                            Some(start..part.location_range_end?)
3135                                        }),
3136                                    )
3137                                    .zip(part.language_server_id)
3138                                {
3139                                    Some(((uri, range), server_id)) => Some((
3140                                        LanguageServerId(server_id as usize),
3141                                        lsp::Location {
3142                                            uri: lsp::Url::parse(&uri)
3143                                                .context("invalid uri in hint part {part:?}")?,
3144                                            range: lsp::Range::new(
3145                                                point_to_lsp(PointUtf16::new(
3146                                                    range.start.row,
3147                                                    range.start.column,
3148                                                )),
3149                                                point_to_lsp(PointUtf16::new(
3150                                                    range.end.row,
3151                                                    range.end.column,
3152                                                )),
3153                                            ),
3154                                        },
3155                                    )),
3156                                    None => None,
3157                                }
3158                            },
3159                        });
3160                    }
3161
3162                    InlayHintLabel::LabelParts(label_parts)
3163                }
3164            },
3165            padding_left: message_hint.padding_left,
3166            padding_right: message_hint.padding_right,
3167            kind: message_hint
3168                .kind
3169                .as_deref()
3170                .and_then(InlayHintKind::from_name),
3171            tooltip: message_hint.tooltip.and_then(|tooltip| {
3172                Some(match tooltip.content? {
3173                    proto::inlay_hint_tooltip::Content::Value(s) => InlayHintTooltip::String(s),
3174                    proto::inlay_hint_tooltip::Content::MarkupContent(markup_content) => {
3175                        InlayHintTooltip::MarkupContent(MarkupContent {
3176                            kind: if markup_content.is_markdown {
3177                                HoverBlockKind::Markdown
3178                            } else {
3179                                HoverBlockKind::PlainText
3180                            },
3181                            value: markup_content.value,
3182                        })
3183                    }
3184                })
3185            }),
3186            resolve_state,
3187        })
3188    }
3189
3190    pub fn project_to_lsp_hint(hint: InlayHint, snapshot: &BufferSnapshot) -> lsp::InlayHint {
3191        lsp::InlayHint {
3192            position: point_to_lsp(hint.position.to_point_utf16(snapshot)),
3193            kind: hint.kind.map(|kind| match kind {
3194                InlayHintKind::Type => lsp::InlayHintKind::TYPE,
3195                InlayHintKind::Parameter => lsp::InlayHintKind::PARAMETER,
3196            }),
3197            text_edits: None,
3198            tooltip: hint.tooltip.and_then(|tooltip| {
3199                Some(match tooltip {
3200                    InlayHintTooltip::String(s) => lsp::InlayHintTooltip::String(s),
3201                    InlayHintTooltip::MarkupContent(markup_content) => {
3202                        lsp::InlayHintTooltip::MarkupContent(lsp::MarkupContent {
3203                            kind: match markup_content.kind {
3204                                HoverBlockKind::PlainText => lsp::MarkupKind::PlainText,
3205                                HoverBlockKind::Markdown => lsp::MarkupKind::Markdown,
3206                                HoverBlockKind::Code { .. } => return None,
3207                            },
3208                            value: markup_content.value,
3209                        })
3210                    }
3211                })
3212            }),
3213            label: match hint.label {
3214                InlayHintLabel::String(s) => lsp::InlayHintLabel::String(s),
3215                InlayHintLabel::LabelParts(label_parts) => lsp::InlayHintLabel::LabelParts(
3216                    label_parts
3217                        .into_iter()
3218                        .map(|part| lsp::InlayHintLabelPart {
3219                            value: part.value,
3220                            tooltip: part.tooltip.and_then(|tooltip| {
3221                                Some(match tooltip {
3222                                    InlayHintLabelPartTooltip::String(s) => {
3223                                        lsp::InlayHintLabelPartTooltip::String(s)
3224                                    }
3225                                    InlayHintLabelPartTooltip::MarkupContent(markup_content) => {
3226                                        lsp::InlayHintLabelPartTooltip::MarkupContent(
3227                                            lsp::MarkupContent {
3228                                                kind: match markup_content.kind {
3229                                                    HoverBlockKind::PlainText => {
3230                                                        lsp::MarkupKind::PlainText
3231                                                    }
3232                                                    HoverBlockKind::Markdown => {
3233                                                        lsp::MarkupKind::Markdown
3234                                                    }
3235                                                    HoverBlockKind::Code { .. } => return None,
3236                                                },
3237                                                value: markup_content.value,
3238                                            },
3239                                        )
3240                                    }
3241                                })
3242                            }),
3243                            location: part.location.map(|(_, location)| location),
3244                            command: None,
3245                        })
3246                        .collect(),
3247                ),
3248            },
3249            padding_left: Some(hint.padding_left),
3250            padding_right: Some(hint.padding_right),
3251            data: match hint.resolve_state {
3252                ResolveState::CanResolve(_, data) => data,
3253                ResolveState::Resolving | ResolveState::Resolved => None,
3254            },
3255        }
3256    }
3257
3258    pub fn can_resolve_inlays(capabilities: &ServerCapabilities) -> bool {
3259        capabilities
3260            .inlay_hint_provider
3261            .as_ref()
3262            .and_then(|options| match options {
3263                OneOf::Left(_is_supported) => None,
3264                OneOf::Right(capabilities) => match capabilities {
3265                    lsp::InlayHintServerCapabilities::Options(o) => o.resolve_provider,
3266                    lsp::InlayHintServerCapabilities::RegistrationOptions(o) => {
3267                        o.inlay_hint_options.resolve_provider
3268                    }
3269                },
3270            })
3271            .unwrap_or(false)
3272    }
3273}
3274
3275#[async_trait(?Send)]
3276impl LspCommand for InlayHints {
3277    type Response = Vec<InlayHint>;
3278    type LspRequest = lsp::InlayHintRequest;
3279    type ProtoRequest = proto::InlayHints;
3280
3281    fn display_name(&self) -> &str {
3282        "Inlay hints"
3283    }
3284
3285    fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
3286        let Some(inlay_hint_provider) = &capabilities.server_capabilities.inlay_hint_provider
3287        else {
3288            return false;
3289        };
3290        match inlay_hint_provider {
3291            lsp::OneOf::Left(enabled) => *enabled,
3292            lsp::OneOf::Right(inlay_hint_capabilities) => match inlay_hint_capabilities {
3293                lsp::InlayHintServerCapabilities::Options(_) => true,
3294                lsp::InlayHintServerCapabilities::RegistrationOptions(_) => false,
3295            },
3296        }
3297    }
3298
3299    fn to_lsp(
3300        &self,
3301        path: &Path,
3302        buffer: &Buffer,
3303        _: &Arc<LanguageServer>,
3304        _: &App,
3305    ) -> Result<lsp::InlayHintParams> {
3306        Ok(lsp::InlayHintParams {
3307            text_document: lsp::TextDocumentIdentifier {
3308                uri: file_path_to_lsp_url(path)?,
3309            },
3310            range: range_to_lsp(self.range.to_point_utf16(buffer))?,
3311            work_done_progress_params: Default::default(),
3312        })
3313    }
3314
3315    async fn response_from_lsp(
3316        self,
3317        message: Option<Vec<lsp::InlayHint>>,
3318        lsp_store: Entity<LspStore>,
3319        buffer: Entity<Buffer>,
3320        server_id: LanguageServerId,
3321        mut cx: AsyncApp,
3322    ) -> anyhow::Result<Vec<InlayHint>> {
3323        let (lsp_adapter, lsp_server) =
3324            language_server_for_buffer(&lsp_store, &buffer, server_id, &mut cx)?;
3325        // `typescript-language-server` adds padding to the left for type hints, turning
3326        // `const foo: boolean` into `const foo : boolean` which looks odd.
3327        // `rust-analyzer` does not have the padding for this case, and we have to accommodate both.
3328        //
3329        // We could trim the whole string, but being pessimistic on par with the situation above,
3330        // there might be a hint with multiple whitespaces at the end(s) which we need to display properly.
3331        // Hence let's use a heuristic first to handle the most awkward case and look for more.
3332        let force_no_type_left_padding =
3333            lsp_adapter.name.0.as_ref() == "typescript-language-server";
3334
3335        let hints = message.unwrap_or_default().into_iter().map(|lsp_hint| {
3336            let resolve_state = if InlayHints::can_resolve_inlays(&lsp_server.capabilities()) {
3337                ResolveState::CanResolve(lsp_server.server_id(), lsp_hint.data.clone())
3338            } else {
3339                ResolveState::Resolved
3340            };
3341
3342            let buffer = buffer.clone();
3343            cx.spawn(async move |cx| {
3344                InlayHints::lsp_to_project_hint(
3345                    lsp_hint,
3346                    &buffer,
3347                    server_id,
3348                    resolve_state,
3349                    force_no_type_left_padding,
3350                    cx,
3351                )
3352                .await
3353            })
3354        });
3355        future::join_all(hints)
3356            .await
3357            .into_iter()
3358            .collect::<anyhow::Result<_>>()
3359            .context("lsp to project inlay hints conversion")
3360    }
3361
3362    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> proto::InlayHints {
3363        proto::InlayHints {
3364            project_id,
3365            buffer_id: buffer.remote_id().into(),
3366            start: Some(language::proto::serialize_anchor(&self.range.start)),
3367            end: Some(language::proto::serialize_anchor(&self.range.end)),
3368            version: serialize_version(&buffer.version()),
3369        }
3370    }
3371
3372    async fn from_proto(
3373        message: proto::InlayHints,
3374        _: Entity<LspStore>,
3375        buffer: Entity<Buffer>,
3376        mut cx: AsyncApp,
3377    ) -> Result<Self> {
3378        let start = message
3379            .start
3380            .and_then(language::proto::deserialize_anchor)
3381            .context("invalid start")?;
3382        let end = message
3383            .end
3384            .and_then(language::proto::deserialize_anchor)
3385            .context("invalid end")?;
3386        buffer
3387            .update(&mut cx, |buffer, _| {
3388                buffer.wait_for_version(deserialize_version(&message.version))
3389            })?
3390            .await?;
3391
3392        Ok(Self { range: start..end })
3393    }
3394
3395    fn response_to_proto(
3396        response: Vec<InlayHint>,
3397        _: &mut LspStore,
3398        _: PeerId,
3399        buffer_version: &clock::Global,
3400        _: &mut App,
3401    ) -> proto::InlayHintsResponse {
3402        proto::InlayHintsResponse {
3403            hints: response
3404                .into_iter()
3405                .map(InlayHints::project_to_proto_hint)
3406                .collect(),
3407            version: serialize_version(buffer_version),
3408        }
3409    }
3410
3411    async fn response_from_proto(
3412        self,
3413        message: proto::InlayHintsResponse,
3414        _: Entity<LspStore>,
3415        buffer: Entity<Buffer>,
3416        mut cx: AsyncApp,
3417    ) -> anyhow::Result<Vec<InlayHint>> {
3418        buffer
3419            .update(&mut cx, |buffer, _| {
3420                buffer.wait_for_version(deserialize_version(&message.version))
3421            })?
3422            .await?;
3423
3424        let mut hints = Vec::new();
3425        for message_hint in message.hints {
3426            hints.push(InlayHints::proto_to_project_hint(message_hint)?);
3427        }
3428
3429        Ok(hints)
3430    }
3431
3432    fn buffer_id_from_proto(message: &proto::InlayHints) -> Result<BufferId> {
3433        BufferId::new(message.buffer_id)
3434    }
3435}
3436
3437#[async_trait(?Send)]
3438impl LspCommand for GetCodeLens {
3439    type Response = Vec<CodeAction>;
3440    type LspRequest = lsp::CodeLensRequest;
3441    type ProtoRequest = proto::GetCodeLens;
3442
3443    fn display_name(&self) -> &str {
3444        "Code Lens"
3445    }
3446
3447    fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
3448        capabilities
3449            .server_capabilities
3450            .code_lens_provider
3451            .as_ref()
3452            .map_or(false, |code_lens_options| {
3453                code_lens_options.resolve_provider.unwrap_or(false)
3454            })
3455    }
3456
3457    fn to_lsp(
3458        &self,
3459        path: &Path,
3460        _: &Buffer,
3461        _: &Arc<LanguageServer>,
3462        _: &App,
3463    ) -> Result<lsp::CodeLensParams> {
3464        Ok(lsp::CodeLensParams {
3465            text_document: lsp::TextDocumentIdentifier {
3466                uri: file_path_to_lsp_url(path)?,
3467            },
3468            work_done_progress_params: lsp::WorkDoneProgressParams::default(),
3469            partial_result_params: lsp::PartialResultParams::default(),
3470        })
3471    }
3472
3473    async fn response_from_lsp(
3474        self,
3475        message: Option<Vec<lsp::CodeLens>>,
3476        lsp_store: Entity<LspStore>,
3477        buffer: Entity<Buffer>,
3478        server_id: LanguageServerId,
3479        mut cx: AsyncApp,
3480    ) -> anyhow::Result<Vec<CodeAction>> {
3481        let snapshot = buffer.read_with(&mut cx, |buffer, _| buffer.snapshot())?;
3482        let language_server = cx.update(|cx| {
3483            lsp_store
3484                .read(cx)
3485                .language_server_for_id(server_id)
3486                .with_context(|| {
3487                    format!("Missing the language server that just returned a response {server_id}")
3488                })
3489        })??;
3490        let server_capabilities = language_server.capabilities();
3491        let available_commands = server_capabilities
3492            .execute_command_provider
3493            .as_ref()
3494            .map(|options| options.commands.as_slice())
3495            .unwrap_or_default();
3496        Ok(message
3497            .unwrap_or_default()
3498            .into_iter()
3499            .filter(|code_lens| {
3500                code_lens
3501                    .command
3502                    .as_ref()
3503                    .is_none_or(|command| available_commands.contains(&command.command))
3504            })
3505            .map(|code_lens| {
3506                let code_lens_range = range_from_lsp(code_lens.range);
3507                let start = snapshot.clip_point_utf16(code_lens_range.start, Bias::Left);
3508                let end = snapshot.clip_point_utf16(code_lens_range.end, Bias::Right);
3509                let range = snapshot.anchor_before(start)..snapshot.anchor_after(end);
3510                CodeAction {
3511                    server_id,
3512                    range,
3513                    lsp_action: LspAction::CodeLens(code_lens),
3514                    resolved: false,
3515                }
3516            })
3517            .collect())
3518    }
3519
3520    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> proto::GetCodeLens {
3521        proto::GetCodeLens {
3522            project_id,
3523            buffer_id: buffer.remote_id().into(),
3524            version: serialize_version(&buffer.version()),
3525        }
3526    }
3527
3528    async fn from_proto(
3529        message: proto::GetCodeLens,
3530        _: Entity<LspStore>,
3531        buffer: Entity<Buffer>,
3532        mut cx: AsyncApp,
3533    ) -> Result<Self> {
3534        buffer
3535            .update(&mut cx, |buffer, _| {
3536                buffer.wait_for_version(deserialize_version(&message.version))
3537            })?
3538            .await?;
3539        Ok(Self)
3540    }
3541
3542    fn response_to_proto(
3543        response: Vec<CodeAction>,
3544        _: &mut LspStore,
3545        _: PeerId,
3546        buffer_version: &clock::Global,
3547        _: &mut App,
3548    ) -> proto::GetCodeLensResponse {
3549        proto::GetCodeLensResponse {
3550            lens_actions: response
3551                .iter()
3552                .map(LspStore::serialize_code_action)
3553                .collect(),
3554            version: serialize_version(buffer_version),
3555        }
3556    }
3557
3558    async fn response_from_proto(
3559        self,
3560        message: proto::GetCodeLensResponse,
3561        _: Entity<LspStore>,
3562        buffer: Entity<Buffer>,
3563        mut cx: AsyncApp,
3564    ) -> anyhow::Result<Vec<CodeAction>> {
3565        buffer
3566            .update(&mut cx, |buffer, _| {
3567                buffer.wait_for_version(deserialize_version(&message.version))
3568            })?
3569            .await?;
3570        message
3571            .lens_actions
3572            .into_iter()
3573            .map(LspStore::deserialize_code_action)
3574            .collect::<Result<Vec<_>>>()
3575            .context("deserializing proto code lens response")
3576    }
3577
3578    fn buffer_id_from_proto(message: &proto::GetCodeLens) -> Result<BufferId> {
3579        BufferId::new(message.buffer_id)
3580    }
3581}
3582
3583#[async_trait(?Send)]
3584impl LspCommand for LinkedEditingRange {
3585    type Response = Vec<Range<Anchor>>;
3586    type LspRequest = lsp::request::LinkedEditingRange;
3587    type ProtoRequest = proto::LinkedEditingRange;
3588
3589    fn display_name(&self) -> &str {
3590        "Linked editing range"
3591    }
3592
3593    fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
3594        let Some(linked_editing_options) = &capabilities
3595            .server_capabilities
3596            .linked_editing_range_provider
3597        else {
3598            return false;
3599        };
3600        if let LinkedEditingRangeServerCapabilities::Simple(false) = linked_editing_options {
3601            return false;
3602        }
3603        true
3604    }
3605
3606    fn to_lsp(
3607        &self,
3608        path: &Path,
3609        buffer: &Buffer,
3610        _server: &Arc<LanguageServer>,
3611        _: &App,
3612    ) -> Result<lsp::LinkedEditingRangeParams> {
3613        let position = self.position.to_point_utf16(&buffer.snapshot());
3614        Ok(lsp::LinkedEditingRangeParams {
3615            text_document_position_params: make_lsp_text_document_position(path, position)?,
3616            work_done_progress_params: Default::default(),
3617        })
3618    }
3619
3620    async fn response_from_lsp(
3621        self,
3622        message: Option<lsp::LinkedEditingRanges>,
3623        _: Entity<LspStore>,
3624        buffer: Entity<Buffer>,
3625        _server_id: LanguageServerId,
3626        cx: AsyncApp,
3627    ) -> Result<Vec<Range<Anchor>>> {
3628        if let Some(lsp::LinkedEditingRanges { mut ranges, .. }) = message {
3629            ranges.sort_by_key(|range| range.start);
3630
3631            buffer.read_with(&cx, |buffer, _| {
3632                ranges
3633                    .into_iter()
3634                    .map(|range| {
3635                        let start =
3636                            buffer.clip_point_utf16(point_from_lsp(range.start), Bias::Left);
3637                        let end = buffer.clip_point_utf16(point_from_lsp(range.end), Bias::Left);
3638                        buffer.anchor_before(start)..buffer.anchor_after(end)
3639                    })
3640                    .collect()
3641            })
3642        } else {
3643            Ok(vec![])
3644        }
3645    }
3646
3647    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> proto::LinkedEditingRange {
3648        proto::LinkedEditingRange {
3649            project_id,
3650            buffer_id: buffer.remote_id().to_proto(),
3651            position: Some(serialize_anchor(&self.position)),
3652            version: serialize_version(&buffer.version()),
3653        }
3654    }
3655
3656    async fn from_proto(
3657        message: proto::LinkedEditingRange,
3658        _: Entity<LspStore>,
3659        buffer: Entity<Buffer>,
3660        mut cx: AsyncApp,
3661    ) -> Result<Self> {
3662        let position = message.position.context("invalid position")?;
3663        buffer
3664            .update(&mut cx, |buffer, _| {
3665                buffer.wait_for_version(deserialize_version(&message.version))
3666            })?
3667            .await?;
3668        let position = deserialize_anchor(position).context("invalid position")?;
3669        buffer
3670            .update(&mut cx, |buffer, _| buffer.wait_for_anchors([position]))?
3671            .await?;
3672        Ok(Self { position })
3673    }
3674
3675    fn response_to_proto(
3676        response: Vec<Range<Anchor>>,
3677        _: &mut LspStore,
3678        _: PeerId,
3679        buffer_version: &clock::Global,
3680        _: &mut App,
3681    ) -> proto::LinkedEditingRangeResponse {
3682        proto::LinkedEditingRangeResponse {
3683            items: response
3684                .into_iter()
3685                .map(|range| proto::AnchorRange {
3686                    start: Some(serialize_anchor(&range.start)),
3687                    end: Some(serialize_anchor(&range.end)),
3688                })
3689                .collect(),
3690            version: serialize_version(buffer_version),
3691        }
3692    }
3693
3694    async fn response_from_proto(
3695        self,
3696        message: proto::LinkedEditingRangeResponse,
3697        _: Entity<LspStore>,
3698        buffer: Entity<Buffer>,
3699        mut cx: AsyncApp,
3700    ) -> Result<Vec<Range<Anchor>>> {
3701        buffer
3702            .update(&mut cx, |buffer, _| {
3703                buffer.wait_for_version(deserialize_version(&message.version))
3704            })?
3705            .await?;
3706        let items: Vec<Range<Anchor>> = message
3707            .items
3708            .into_iter()
3709            .filter_map(|range| {
3710                let start = deserialize_anchor(range.start?)?;
3711                let end = deserialize_anchor(range.end?)?;
3712                Some(start..end)
3713            })
3714            .collect();
3715        for range in &items {
3716            buffer
3717                .update(&mut cx, |buffer, _| {
3718                    buffer.wait_for_anchors([range.start, range.end])
3719                })?
3720                .await?;
3721        }
3722        Ok(items)
3723    }
3724
3725    fn buffer_id_from_proto(message: &proto::LinkedEditingRange) -> Result<BufferId> {
3726        BufferId::new(message.buffer_id)
3727    }
3728}
3729
3730impl GetDocumentDiagnostics {
3731    pub fn diagnostics_from_proto(
3732        response: proto::GetDocumentDiagnosticsResponse,
3733    ) -> Vec<LspPullDiagnostics> {
3734        response
3735            .pulled_diagnostics
3736            .into_iter()
3737            .filter_map(|diagnostics| {
3738                Some(LspPullDiagnostics::Response {
3739                    server_id: LanguageServerId::from_proto(diagnostics.server_id),
3740                    uri: lsp::Url::from_str(diagnostics.uri.as_str()).log_err()?,
3741                    diagnostics: if diagnostics.changed {
3742                        PulledDiagnostics::Unchanged {
3743                            result_id: diagnostics.result_id?,
3744                        }
3745                    } else {
3746                        PulledDiagnostics::Changed {
3747                            result_id: diagnostics.result_id,
3748                            diagnostics: diagnostics
3749                                .diagnostics
3750                                .into_iter()
3751                                .filter_map(|diagnostic| {
3752                                    GetDocumentDiagnostics::deserialize_lsp_diagnostic(diagnostic)
3753                                        .context("deserializing diagnostics")
3754                                        .log_err()
3755                                })
3756                                .collect(),
3757                        }
3758                    },
3759                })
3760            })
3761            .collect()
3762    }
3763
3764    fn deserialize_lsp_diagnostic(diagnostic: proto::LspDiagnostic) -> Result<lsp::Diagnostic> {
3765        let start = diagnostic.start.context("invalid start range")?;
3766        let end = diagnostic.end.context("invalid end range")?;
3767
3768        let range = Range::<PointUtf16> {
3769            start: PointUtf16 {
3770                row: start.row,
3771                column: start.column,
3772            },
3773            end: PointUtf16 {
3774                row: end.row,
3775                column: end.column,
3776            },
3777        };
3778
3779        let data = diagnostic.data.and_then(|data| Value::from_str(&data).ok());
3780        let code = diagnostic.code.map(lsp::NumberOrString::String);
3781
3782        let related_information = diagnostic
3783            .related_information
3784            .into_iter()
3785            .map(|info| {
3786                let start = info.location_range_start.unwrap();
3787                let end = info.location_range_end.unwrap();
3788
3789                lsp::DiagnosticRelatedInformation {
3790                    location: lsp::Location {
3791                        range: lsp::Range {
3792                            start: point_to_lsp(PointUtf16::new(start.row, start.column)),
3793                            end: point_to_lsp(PointUtf16::new(end.row, end.column)),
3794                        },
3795                        uri: lsp::Url::parse(&info.location_url.unwrap()).unwrap(),
3796                    },
3797                    message: info.message.clone(),
3798                }
3799            })
3800            .collect::<Vec<_>>();
3801
3802        let tags = diagnostic
3803            .tags
3804            .into_iter()
3805            .filter_map(|tag| match proto::LspDiagnosticTag::from_i32(tag) {
3806                Some(proto::LspDiagnosticTag::Unnecessary) => Some(lsp::DiagnosticTag::UNNECESSARY),
3807                Some(proto::LspDiagnosticTag::Deprecated) => Some(lsp::DiagnosticTag::DEPRECATED),
3808                _ => None,
3809            })
3810            .collect::<Vec<_>>();
3811
3812        Ok(lsp::Diagnostic {
3813            range: language::range_to_lsp(range)?,
3814            severity: match proto::lsp_diagnostic::Severity::from_i32(diagnostic.severity).unwrap()
3815            {
3816                proto::lsp_diagnostic::Severity::Error => Some(lsp::DiagnosticSeverity::ERROR),
3817                proto::lsp_diagnostic::Severity::Warning => Some(lsp::DiagnosticSeverity::WARNING),
3818                proto::lsp_diagnostic::Severity::Information => {
3819                    Some(lsp::DiagnosticSeverity::INFORMATION)
3820                }
3821                proto::lsp_diagnostic::Severity::Hint => Some(lsp::DiagnosticSeverity::HINT),
3822                _ => None,
3823            },
3824            code,
3825            code_description: match diagnostic.code_description {
3826                Some(code_description) => Some(CodeDescription {
3827                    href: Some(lsp::Url::parse(&code_description).unwrap()),
3828                }),
3829                None => None,
3830            },
3831            related_information: Some(related_information),
3832            tags: Some(tags),
3833            source: diagnostic.source.clone(),
3834            message: diagnostic.message,
3835            data,
3836        })
3837    }
3838
3839    fn serialize_lsp_diagnostic(diagnostic: lsp::Diagnostic) -> Result<proto::LspDiagnostic> {
3840        let range = language::range_from_lsp(diagnostic.range);
3841        let related_information = diagnostic
3842            .related_information
3843            .unwrap_or_default()
3844            .into_iter()
3845            .map(|related_information| {
3846                let location_range_start =
3847                    point_from_lsp(related_information.location.range.start).0;
3848                let location_range_end = point_from_lsp(related_information.location.range.end).0;
3849
3850                Ok(proto::LspDiagnosticRelatedInformation {
3851                    location_url: Some(related_information.location.uri.to_string()),
3852                    location_range_start: Some(proto::PointUtf16 {
3853                        row: location_range_start.row,
3854                        column: location_range_start.column,
3855                    }),
3856                    location_range_end: Some(proto::PointUtf16 {
3857                        row: location_range_end.row,
3858                        column: location_range_end.column,
3859                    }),
3860                    message: related_information.message,
3861                })
3862            })
3863            .collect::<Result<Vec<_>>>()?;
3864
3865        let tags = diagnostic
3866            .tags
3867            .unwrap_or_default()
3868            .into_iter()
3869            .map(|tag| match tag {
3870                lsp::DiagnosticTag::UNNECESSARY => proto::LspDiagnosticTag::Unnecessary,
3871                lsp::DiagnosticTag::DEPRECATED => proto::LspDiagnosticTag::Deprecated,
3872                _ => proto::LspDiagnosticTag::None,
3873            } as i32)
3874            .collect();
3875
3876        Ok(proto::LspDiagnostic {
3877            start: Some(proto::PointUtf16 {
3878                row: range.start.0.row,
3879                column: range.start.0.column,
3880            }),
3881            end: Some(proto::PointUtf16 {
3882                row: range.end.0.row,
3883                column: range.end.0.column,
3884            }),
3885            severity: match diagnostic.severity {
3886                Some(lsp::DiagnosticSeverity::ERROR) => proto::lsp_diagnostic::Severity::Error,
3887                Some(lsp::DiagnosticSeverity::WARNING) => proto::lsp_diagnostic::Severity::Warning,
3888                Some(lsp::DiagnosticSeverity::INFORMATION) => {
3889                    proto::lsp_diagnostic::Severity::Information
3890                }
3891                Some(lsp::DiagnosticSeverity::HINT) => proto::lsp_diagnostic::Severity::Hint,
3892                _ => proto::lsp_diagnostic::Severity::None,
3893            } as i32,
3894            code: diagnostic.code.as_ref().map(|code| match code {
3895                lsp::NumberOrString::Number(code) => code.to_string(),
3896                lsp::NumberOrString::String(code) => code.clone(),
3897            }),
3898            source: diagnostic.source.clone(),
3899            related_information,
3900            tags,
3901            code_description: diagnostic
3902                .code_description
3903                .and_then(|desc| desc.href.map(|url| url.to_string())),
3904            message: diagnostic.message,
3905            data: diagnostic.data.as_ref().map(|data| data.to_string()),
3906        })
3907    }
3908
3909    pub fn deserialize_workspace_diagnostics_report(
3910        report: lsp::WorkspaceDiagnosticReportResult,
3911        server_id: LanguageServerId,
3912    ) -> Vec<WorkspaceLspPullDiagnostics> {
3913        let mut pulled_diagnostics = HashMap::default();
3914        match report {
3915            lsp::WorkspaceDiagnosticReportResult::Report(workspace_diagnostic_report) => {
3916                for report in workspace_diagnostic_report.items {
3917                    match report {
3918                        lsp::WorkspaceDocumentDiagnosticReport::Full(report) => {
3919                            process_full_workspace_diagnostics_report(
3920                                &mut pulled_diagnostics,
3921                                server_id,
3922                                report,
3923                            )
3924                        }
3925                        lsp::WorkspaceDocumentDiagnosticReport::Unchanged(report) => {
3926                            process_unchanged_workspace_diagnostics_report(
3927                                &mut pulled_diagnostics,
3928                                server_id,
3929                                report,
3930                            )
3931                        }
3932                    }
3933                }
3934            }
3935            lsp::WorkspaceDiagnosticReportResult::Partial(
3936                workspace_diagnostic_report_partial_result,
3937            ) => {
3938                for report in workspace_diagnostic_report_partial_result.items {
3939                    match report {
3940                        lsp::WorkspaceDocumentDiagnosticReport::Full(report) => {
3941                            process_full_workspace_diagnostics_report(
3942                                &mut pulled_diagnostics,
3943                                server_id,
3944                                report,
3945                            )
3946                        }
3947                        lsp::WorkspaceDocumentDiagnosticReport::Unchanged(report) => {
3948                            process_unchanged_workspace_diagnostics_report(
3949                                &mut pulled_diagnostics,
3950                                server_id,
3951                                report,
3952                            )
3953                        }
3954                    }
3955                }
3956            }
3957        }
3958        pulled_diagnostics.into_values().collect()
3959    }
3960}
3961
3962#[derive(Debug)]
3963pub struct WorkspaceLspPullDiagnostics {
3964    pub version: Option<i32>,
3965    pub diagnostics: LspPullDiagnostics,
3966}
3967
3968fn process_full_workspace_diagnostics_report(
3969    diagnostics: &mut HashMap<lsp::Url, WorkspaceLspPullDiagnostics>,
3970    server_id: LanguageServerId,
3971    report: lsp::WorkspaceFullDocumentDiagnosticReport,
3972) {
3973    let mut new_diagnostics = HashMap::default();
3974    process_full_diagnostics_report(
3975        &mut new_diagnostics,
3976        server_id,
3977        report.uri,
3978        report.full_document_diagnostic_report,
3979    );
3980    diagnostics.extend(new_diagnostics.into_iter().map(|(uri, diagnostics)| {
3981        (
3982            uri,
3983            WorkspaceLspPullDiagnostics {
3984                version: report.version.map(|v| v as i32),
3985                diagnostics,
3986            },
3987        )
3988    }));
3989}
3990
3991fn process_unchanged_workspace_diagnostics_report(
3992    diagnostics: &mut HashMap<lsp::Url, WorkspaceLspPullDiagnostics>,
3993    server_id: LanguageServerId,
3994    report: lsp::WorkspaceUnchangedDocumentDiagnosticReport,
3995) {
3996    let mut new_diagnostics = HashMap::default();
3997    process_unchanged_diagnostics_report(
3998        &mut new_diagnostics,
3999        server_id,
4000        report.uri,
4001        report.unchanged_document_diagnostic_report,
4002    );
4003    diagnostics.extend(new_diagnostics.into_iter().map(|(uri, diagnostics)| {
4004        (
4005            uri,
4006            WorkspaceLspPullDiagnostics {
4007                version: report.version.map(|v| v as i32),
4008                diagnostics,
4009            },
4010        )
4011    }));
4012}
4013
4014#[async_trait(?Send)]
4015impl LspCommand for GetDocumentDiagnostics {
4016    type Response = Vec<LspPullDiagnostics>;
4017    type LspRequest = lsp::request::DocumentDiagnosticRequest;
4018    type ProtoRequest = proto::GetDocumentDiagnostics;
4019
4020    fn display_name(&self) -> &str {
4021        "Get diagnostics"
4022    }
4023
4024    fn check_capabilities(&self, server_capabilities: AdapterServerCapabilities) -> bool {
4025        server_capabilities
4026            .server_capabilities
4027            .diagnostic_provider
4028            .is_some()
4029    }
4030
4031    fn to_lsp(
4032        &self,
4033        path: &Path,
4034        _: &Buffer,
4035        language_server: &Arc<LanguageServer>,
4036        _: &App,
4037    ) -> Result<lsp::DocumentDiagnosticParams> {
4038        let identifier = match language_server.capabilities().diagnostic_provider {
4039            Some(lsp::DiagnosticServerCapabilities::Options(options)) => options.identifier,
4040            Some(lsp::DiagnosticServerCapabilities::RegistrationOptions(options)) => {
4041                options.diagnostic_options.identifier
4042            }
4043            None => None,
4044        };
4045
4046        Ok(lsp::DocumentDiagnosticParams {
4047            text_document: lsp::TextDocumentIdentifier {
4048                uri: file_path_to_lsp_url(path)?,
4049            },
4050            identifier,
4051            previous_result_id: self.previous_result_id.clone(),
4052            partial_result_params: Default::default(),
4053            work_done_progress_params: Default::default(),
4054        })
4055    }
4056
4057    async fn response_from_lsp(
4058        self,
4059        message: lsp::DocumentDiagnosticReportResult,
4060        _: Entity<LspStore>,
4061        buffer: Entity<Buffer>,
4062        server_id: LanguageServerId,
4063        cx: AsyncApp,
4064    ) -> Result<Self::Response> {
4065        let url = buffer.read_with(&cx, |buffer, cx| {
4066            buffer
4067                .file()
4068                .and_then(|file| file.as_local())
4069                .map(|file| {
4070                    let abs_path = file.abs_path(cx);
4071                    file_path_to_lsp_url(&abs_path)
4072                })
4073                .transpose()?
4074                .with_context(|| format!("missing url on buffer {}", buffer.remote_id()))
4075        })??;
4076
4077        let mut pulled_diagnostics = HashMap::default();
4078        match message {
4079            lsp::DocumentDiagnosticReportResult::Report(report) => match report {
4080                lsp::DocumentDiagnosticReport::Full(report) => {
4081                    if let Some(related_documents) = report.related_documents {
4082                        process_related_documents(
4083                            &mut pulled_diagnostics,
4084                            server_id,
4085                            related_documents,
4086                        );
4087                    }
4088                    process_full_diagnostics_report(
4089                        &mut pulled_diagnostics,
4090                        server_id,
4091                        url,
4092                        report.full_document_diagnostic_report,
4093                    );
4094                }
4095                lsp::DocumentDiagnosticReport::Unchanged(report) => {
4096                    if let Some(related_documents) = report.related_documents {
4097                        process_related_documents(
4098                            &mut pulled_diagnostics,
4099                            server_id,
4100                            related_documents,
4101                        );
4102                    }
4103                    process_unchanged_diagnostics_report(
4104                        &mut pulled_diagnostics,
4105                        server_id,
4106                        url,
4107                        report.unchanged_document_diagnostic_report,
4108                    );
4109                }
4110            },
4111            lsp::DocumentDiagnosticReportResult::Partial(report) => {
4112                if let Some(related_documents) = report.related_documents {
4113                    process_related_documents(
4114                        &mut pulled_diagnostics,
4115                        server_id,
4116                        related_documents,
4117                    );
4118                }
4119            }
4120        }
4121
4122        Ok(pulled_diagnostics.into_values().collect())
4123    }
4124
4125    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> proto::GetDocumentDiagnostics {
4126        proto::GetDocumentDiagnostics {
4127            project_id,
4128            buffer_id: buffer.remote_id().into(),
4129            version: serialize_version(&buffer.version()),
4130        }
4131    }
4132
4133    async fn from_proto(
4134        _: proto::GetDocumentDiagnostics,
4135        _: Entity<LspStore>,
4136        _: Entity<Buffer>,
4137        _: AsyncApp,
4138    ) -> Result<Self> {
4139        anyhow::bail!(
4140            "proto::GetDocumentDiagnostics is not expected to be converted from proto directly, as it needs `previous_result_id` fetched first"
4141        )
4142    }
4143
4144    fn response_to_proto(
4145        response: Self::Response,
4146        _: &mut LspStore,
4147        _: PeerId,
4148        _: &clock::Global,
4149        _: &mut App,
4150    ) -> proto::GetDocumentDiagnosticsResponse {
4151        let pulled_diagnostics = response
4152            .into_iter()
4153            .filter_map(|diagnostics| match diagnostics {
4154                LspPullDiagnostics::Default => None,
4155                LspPullDiagnostics::Response {
4156                    server_id,
4157                    uri,
4158                    diagnostics,
4159                } => {
4160                    let mut changed = false;
4161                    let (diagnostics, result_id) = match diagnostics {
4162                        PulledDiagnostics::Unchanged { result_id } => (Vec::new(), Some(result_id)),
4163                        PulledDiagnostics::Changed {
4164                            result_id,
4165                            diagnostics,
4166                        } => {
4167                            changed = true;
4168                            (diagnostics, result_id)
4169                        }
4170                    };
4171                    Some(proto::PulledDiagnostics {
4172                        changed,
4173                        result_id,
4174                        uri: uri.to_string(),
4175                        server_id: server_id.to_proto(),
4176                        diagnostics: diagnostics
4177                            .into_iter()
4178                            .filter_map(|diagnostic| {
4179                                GetDocumentDiagnostics::serialize_lsp_diagnostic(diagnostic)
4180                                    .context("serializing diagnostics")
4181                                    .log_err()
4182                            })
4183                            .collect(),
4184                    })
4185                }
4186            })
4187            .collect();
4188
4189        proto::GetDocumentDiagnosticsResponse { pulled_diagnostics }
4190    }
4191
4192    async fn response_from_proto(
4193        self,
4194        response: proto::GetDocumentDiagnosticsResponse,
4195        _: Entity<LspStore>,
4196        _: Entity<Buffer>,
4197        _: AsyncApp,
4198    ) -> Result<Self::Response> {
4199        Ok(Self::diagnostics_from_proto(response))
4200    }
4201
4202    fn buffer_id_from_proto(message: &proto::GetDocumentDiagnostics) -> Result<BufferId> {
4203        BufferId::new(message.buffer_id)
4204    }
4205}
4206
4207#[async_trait(?Send)]
4208impl LspCommand for GetDocumentColor {
4209    type Response = Vec<DocumentColor>;
4210    type LspRequest = lsp::request::DocumentColor;
4211    type ProtoRequest = proto::GetDocumentColor;
4212
4213    fn display_name(&self) -> &str {
4214        "Document color"
4215    }
4216
4217    fn check_capabilities(&self, server_capabilities: AdapterServerCapabilities) -> bool {
4218        server_capabilities
4219            .server_capabilities
4220            .color_provider
4221            .is_some_and(|capability| match capability {
4222                lsp::ColorProviderCapability::Simple(supported) => supported,
4223                lsp::ColorProviderCapability::ColorProvider(..) => true,
4224                lsp::ColorProviderCapability::Options(..) => true,
4225            })
4226    }
4227
4228    fn to_lsp(
4229        &self,
4230        path: &Path,
4231        _: &Buffer,
4232        _: &Arc<LanguageServer>,
4233        _: &App,
4234    ) -> Result<lsp::DocumentColorParams> {
4235        Ok(lsp::DocumentColorParams {
4236            text_document: make_text_document_identifier(path)?,
4237            work_done_progress_params: Default::default(),
4238            partial_result_params: Default::default(),
4239        })
4240    }
4241
4242    async fn response_from_lsp(
4243        self,
4244        message: Vec<lsp::ColorInformation>,
4245        _: Entity<LspStore>,
4246        _: Entity<Buffer>,
4247        _: LanguageServerId,
4248        _: AsyncApp,
4249    ) -> Result<Self::Response> {
4250        Ok(message
4251            .into_iter()
4252            .map(|color| DocumentColor {
4253                lsp_range: color.range,
4254                color: color.color,
4255                resolved: false,
4256                color_presentations: Vec::new(),
4257            })
4258            .collect())
4259    }
4260
4261    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> Self::ProtoRequest {
4262        proto::GetDocumentColor {
4263            project_id,
4264            buffer_id: buffer.remote_id().to_proto(),
4265            version: serialize_version(&buffer.version()),
4266        }
4267    }
4268
4269    async fn from_proto(
4270        _: Self::ProtoRequest,
4271        _: Entity<LspStore>,
4272        _: Entity<Buffer>,
4273        _: AsyncApp,
4274    ) -> Result<Self> {
4275        Ok(Self {})
4276    }
4277
4278    fn response_to_proto(
4279        response: Self::Response,
4280        _: &mut LspStore,
4281        _: PeerId,
4282        buffer_version: &clock::Global,
4283        _: &mut App,
4284    ) -> proto::GetDocumentColorResponse {
4285        proto::GetDocumentColorResponse {
4286            colors: response
4287                .into_iter()
4288                .map(|color| {
4289                    let start = point_from_lsp(color.lsp_range.start).0;
4290                    let end = point_from_lsp(color.lsp_range.end).0;
4291                    proto::ColorInformation {
4292                        red: color.color.red,
4293                        green: color.color.green,
4294                        blue: color.color.blue,
4295                        alpha: color.color.alpha,
4296                        lsp_range_start: Some(proto::PointUtf16 {
4297                            row: start.row,
4298                            column: start.column,
4299                        }),
4300                        lsp_range_end: Some(proto::PointUtf16 {
4301                            row: end.row,
4302                            column: end.column,
4303                        }),
4304                    }
4305                })
4306                .collect(),
4307            version: serialize_version(buffer_version),
4308        }
4309    }
4310
4311    async fn response_from_proto(
4312        self,
4313        message: proto::GetDocumentColorResponse,
4314        _: Entity<LspStore>,
4315        _: Entity<Buffer>,
4316        _: AsyncApp,
4317    ) -> Result<Self::Response> {
4318        Ok(message
4319            .colors
4320            .into_iter()
4321            .filter_map(|color| {
4322                let start = color.lsp_range_start?;
4323                let start = PointUtf16::new(start.row, start.column);
4324                let end = color.lsp_range_end?;
4325                let end = PointUtf16::new(end.row, end.column);
4326                Some(DocumentColor {
4327                    resolved: false,
4328                    color_presentations: Vec::new(),
4329                    lsp_range: lsp::Range {
4330                        start: point_to_lsp(start),
4331                        end: point_to_lsp(end),
4332                    },
4333                    color: lsp::Color {
4334                        red: color.red,
4335                        green: color.green,
4336                        blue: color.blue,
4337                        alpha: color.alpha,
4338                    },
4339                })
4340            })
4341            .collect())
4342    }
4343
4344    fn buffer_id_from_proto(message: &Self::ProtoRequest) -> Result<BufferId> {
4345        BufferId::new(message.buffer_id)
4346    }
4347}
4348
4349fn process_related_documents(
4350    diagnostics: &mut HashMap<lsp::Url, LspPullDiagnostics>,
4351    server_id: LanguageServerId,
4352    documents: impl IntoIterator<Item = (lsp::Url, lsp::DocumentDiagnosticReportKind)>,
4353) {
4354    for (url, report_kind) in documents {
4355        match report_kind {
4356            lsp::DocumentDiagnosticReportKind::Full(report) => {
4357                process_full_diagnostics_report(diagnostics, server_id, url, report)
4358            }
4359            lsp::DocumentDiagnosticReportKind::Unchanged(report) => {
4360                process_unchanged_diagnostics_report(diagnostics, server_id, url, report)
4361            }
4362        }
4363    }
4364}
4365
4366fn process_unchanged_diagnostics_report(
4367    diagnostics: &mut HashMap<lsp::Url, LspPullDiagnostics>,
4368    server_id: LanguageServerId,
4369    uri: lsp::Url,
4370    report: lsp::UnchangedDocumentDiagnosticReport,
4371) {
4372    let result_id = report.result_id;
4373    match diagnostics.entry(uri.clone()) {
4374        hash_map::Entry::Occupied(mut o) => match o.get_mut() {
4375            LspPullDiagnostics::Default => {
4376                o.insert(LspPullDiagnostics::Response {
4377                    server_id,
4378                    uri,
4379                    diagnostics: PulledDiagnostics::Unchanged { result_id },
4380                });
4381            }
4382            LspPullDiagnostics::Response {
4383                server_id: existing_server_id,
4384                uri: existing_uri,
4385                diagnostics: existing_diagnostics,
4386            } => {
4387                if server_id != *existing_server_id || &uri != existing_uri {
4388                    debug_panic!(
4389                        "Unexpected state: file {uri} has two different sets of diagnostics reported"
4390                    );
4391                }
4392                match existing_diagnostics {
4393                    PulledDiagnostics::Unchanged { .. } => {
4394                        *existing_diagnostics = PulledDiagnostics::Unchanged { result_id };
4395                    }
4396                    PulledDiagnostics::Changed { .. } => {}
4397                }
4398            }
4399        },
4400        hash_map::Entry::Vacant(v) => {
4401            v.insert(LspPullDiagnostics::Response {
4402                server_id,
4403                uri,
4404                diagnostics: PulledDiagnostics::Unchanged { result_id },
4405            });
4406        }
4407    }
4408}
4409
4410fn process_full_diagnostics_report(
4411    diagnostics: &mut HashMap<lsp::Url, LspPullDiagnostics>,
4412    server_id: LanguageServerId,
4413    uri: lsp::Url,
4414    report: lsp::FullDocumentDiagnosticReport,
4415) {
4416    let result_id = report.result_id;
4417    match diagnostics.entry(uri.clone()) {
4418        hash_map::Entry::Occupied(mut o) => match o.get_mut() {
4419            LspPullDiagnostics::Default => {
4420                o.insert(LspPullDiagnostics::Response {
4421                    server_id,
4422                    uri,
4423                    diagnostics: PulledDiagnostics::Changed {
4424                        result_id,
4425                        diagnostics: report.items,
4426                    },
4427                });
4428            }
4429            LspPullDiagnostics::Response {
4430                server_id: existing_server_id,
4431                uri: existing_uri,
4432                diagnostics: existing_diagnostics,
4433            } => {
4434                if server_id != *existing_server_id || &uri != existing_uri {
4435                    debug_panic!(
4436                        "Unexpected state: file {uri} has two different sets of diagnostics reported"
4437                    );
4438                }
4439                match existing_diagnostics {
4440                    PulledDiagnostics::Unchanged { .. } => {
4441                        *existing_diagnostics = PulledDiagnostics::Changed {
4442                            result_id,
4443                            diagnostics: report.items,
4444                        };
4445                    }
4446                    PulledDiagnostics::Changed {
4447                        result_id: existing_result_id,
4448                        diagnostics: existing_diagnostics,
4449                    } => {
4450                        if result_id.is_some() {
4451                            *existing_result_id = result_id;
4452                        }
4453                        existing_diagnostics.extend(report.items);
4454                    }
4455                }
4456            }
4457        },
4458        hash_map::Entry::Vacant(v) => {
4459            v.insert(LspPullDiagnostics::Response {
4460                server_id,
4461                uri,
4462                diagnostics: PulledDiagnostics::Changed {
4463                    result_id,
4464                    diagnostics: report.items,
4465                },
4466            });
4467        }
4468    }
4469}
4470
4471#[cfg(test)]
4472mod tests {
4473    use super::*;
4474    use lsp::{DiagnosticSeverity, DiagnosticTag};
4475    use serde_json::json;
4476
4477    #[test]
4478    fn test_serialize_lsp_diagnostic() {
4479        let lsp_diagnostic = lsp::Diagnostic {
4480            range: lsp::Range {
4481                start: lsp::Position::new(0, 1),
4482                end: lsp::Position::new(2, 3),
4483            },
4484            severity: Some(DiagnosticSeverity::ERROR),
4485            code: Some(lsp::NumberOrString::String("E001".to_string())),
4486            source: Some("test-source".to_string()),
4487            message: "Test error message".to_string(),
4488            related_information: None,
4489            tags: Some(vec![DiagnosticTag::DEPRECATED]),
4490            code_description: None,
4491            data: Some(json!({"detail": "test detail"})),
4492        };
4493
4494        let proto_diagnostic =
4495            GetDocumentDiagnostics::serialize_lsp_diagnostic(lsp_diagnostic.clone())
4496                .expect("Failed to serialize diagnostic");
4497
4498        let start = proto_diagnostic.start.unwrap();
4499        let end = proto_diagnostic.end.unwrap();
4500        assert_eq!(start.row, 0);
4501        assert_eq!(start.column, 1);
4502        assert_eq!(end.row, 2);
4503        assert_eq!(end.column, 3);
4504        assert_eq!(
4505            proto_diagnostic.severity,
4506            proto::lsp_diagnostic::Severity::Error as i32
4507        );
4508        assert_eq!(proto_diagnostic.code, Some("E001".to_string()));
4509        assert_eq!(proto_diagnostic.source, Some("test-source".to_string()));
4510        assert_eq!(proto_diagnostic.message, "Test error message");
4511    }
4512
4513    #[test]
4514    fn test_deserialize_lsp_diagnostic() {
4515        let proto_diagnostic = proto::LspDiagnostic {
4516            start: Some(proto::PointUtf16 { row: 0, column: 1 }),
4517            end: Some(proto::PointUtf16 { row: 2, column: 3 }),
4518            severity: proto::lsp_diagnostic::Severity::Warning as i32,
4519            code: Some("ERR".to_string()),
4520            source: Some("Prism".to_string()),
4521            message: "assigned but unused variable - a".to_string(),
4522            related_information: vec![],
4523            tags: vec![],
4524            code_description: None,
4525            data: None,
4526        };
4527
4528        let lsp_diagnostic = GetDocumentDiagnostics::deserialize_lsp_diagnostic(proto_diagnostic)
4529            .expect("Failed to deserialize diagnostic");
4530
4531        assert_eq!(lsp_diagnostic.range.start.line, 0);
4532        assert_eq!(lsp_diagnostic.range.start.character, 1);
4533        assert_eq!(lsp_diagnostic.range.end.line, 2);
4534        assert_eq!(lsp_diagnostic.range.end.character, 3);
4535        assert_eq!(lsp_diagnostic.severity, Some(DiagnosticSeverity::WARNING));
4536        assert_eq!(
4537            lsp_diagnostic.code,
4538            Some(lsp::NumberOrString::String("ERR".to_string()))
4539        );
4540        assert_eq!(lsp_diagnostic.source, Some("Prism".to_string()));
4541        assert_eq!(lsp_diagnostic.message, "assigned but unused variable - a");
4542    }
4543
4544    #[test]
4545    fn test_related_information() {
4546        let related_info = lsp::DiagnosticRelatedInformation {
4547            location: lsp::Location {
4548                uri: lsp::Url::parse("file:///test.rs").unwrap(),
4549                range: lsp::Range {
4550                    start: lsp::Position::new(1, 1),
4551                    end: lsp::Position::new(1, 5),
4552                },
4553            },
4554            message: "Related info message".to_string(),
4555        };
4556
4557        let lsp_diagnostic = lsp::Diagnostic {
4558            range: lsp::Range {
4559                start: lsp::Position::new(0, 0),
4560                end: lsp::Position::new(0, 1),
4561            },
4562            severity: Some(DiagnosticSeverity::INFORMATION),
4563            code: None,
4564            source: Some("Prism".to_string()),
4565            message: "assigned but unused variable - a".to_string(),
4566            related_information: Some(vec![related_info]),
4567            tags: None,
4568            code_description: None,
4569            data: None,
4570        };
4571
4572        let proto_diagnostic = GetDocumentDiagnostics::serialize_lsp_diagnostic(lsp_diagnostic)
4573            .expect("Failed to serialize diagnostic");
4574
4575        assert_eq!(proto_diagnostic.related_information.len(), 1);
4576        let related = &proto_diagnostic.related_information[0];
4577        assert_eq!(related.location_url, Some("file:///test.rs".to_string()));
4578        assert_eq!(related.message, "Related info message");
4579    }
4580
4581    #[test]
4582    fn test_invalid_ranges() {
4583        let proto_diagnostic = proto::LspDiagnostic {
4584            start: None,
4585            end: Some(proto::PointUtf16 { row: 2, column: 3 }),
4586            severity: proto::lsp_diagnostic::Severity::Error as i32,
4587            code: None,
4588            source: None,
4589            message: "Test message".to_string(),
4590            related_information: vec![],
4591            tags: vec![],
4592            code_description: None,
4593            data: None,
4594        };
4595
4596        let result = GetDocumentDiagnostics::deserialize_lsp_diagnostic(proto_diagnostic);
4597        assert!(result.is_err());
4598    }
4599}