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!("completion out of expected range");
2487            return None;
2488        }
2489        snapshot.anchor_before(start)..snapshot.anchor_after(end)
2490    };
2491
2492    let insert_range = match insert_range {
2493        None => None,
2494        Some(insert_range) => {
2495            let range = range_from_lsp(insert_range);
2496            let start = snapshot.clip_point_utf16(range.start, Bias::Left);
2497            let end = snapshot.clip_point_utf16(range.end, Bias::Left);
2498            if start != range.start.0 || end != range.end.0 {
2499                log::info!("completion (insert) out of expected range");
2500                return None;
2501            }
2502            Some(snapshot.anchor_before(start)..snapshot.anchor_after(end))
2503        }
2504    };
2505
2506    Some(ParsedCompletionEdit {
2507        insert_range: insert_range,
2508        replace_range: replace_range,
2509        new_text: new_text.clone(),
2510    })
2511}
2512
2513#[async_trait(?Send)]
2514impl LspCommand for GetCodeActions {
2515    type Response = Vec<CodeAction>;
2516    type LspRequest = lsp::request::CodeActionRequest;
2517    type ProtoRequest = proto::GetCodeActions;
2518
2519    fn display_name(&self) -> &str {
2520        "Get code actions"
2521    }
2522
2523    fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
2524        match &capabilities.server_capabilities.code_action_provider {
2525            None => false,
2526            Some(lsp::CodeActionProviderCapability::Simple(false)) => false,
2527            _ => {
2528                // If we do know that we want specific code actions AND we know that
2529                // the server only supports specific code actions, then we want to filter
2530                // down to the ones that are supported.
2531                if let Some((requested, supported)) = self
2532                    .kinds
2533                    .as_ref()
2534                    .zip(Self::supported_code_action_kinds(capabilities))
2535                {
2536                    let server_supported = supported.into_iter().collect::<HashSet<_>>();
2537                    requested.iter().any(|kind| server_supported.contains(kind))
2538                } else {
2539                    true
2540                }
2541            }
2542        }
2543    }
2544
2545    fn to_lsp(
2546        &self,
2547        path: &Path,
2548        buffer: &Buffer,
2549        language_server: &Arc<LanguageServer>,
2550        _: &App,
2551    ) -> Result<lsp::CodeActionParams> {
2552        let mut relevant_diagnostics = Vec::new();
2553        for entry in buffer
2554            .snapshot()
2555            .diagnostics_in_range::<_, language::PointUtf16>(self.range.clone(), false)
2556        {
2557            relevant_diagnostics.push(entry.to_lsp_diagnostic_stub()?);
2558        }
2559
2560        let supported =
2561            Self::supported_code_action_kinds(language_server.adapter_server_capabilities());
2562
2563        let only = if let Some(requested) = &self.kinds {
2564            if let Some(supported_kinds) = supported {
2565                let server_supported = supported_kinds.into_iter().collect::<HashSet<_>>();
2566
2567                let filtered = requested
2568                    .iter()
2569                    .filter(|kind| server_supported.contains(kind))
2570                    .cloned()
2571                    .collect();
2572                Some(filtered)
2573            } else {
2574                Some(requested.clone())
2575            }
2576        } else {
2577            supported
2578        };
2579
2580        Ok(lsp::CodeActionParams {
2581            text_document: make_text_document_identifier(path)?,
2582            range: range_to_lsp(self.range.to_point_utf16(buffer))?,
2583            work_done_progress_params: Default::default(),
2584            partial_result_params: Default::default(),
2585            context: lsp::CodeActionContext {
2586                diagnostics: relevant_diagnostics,
2587                only,
2588                ..lsp::CodeActionContext::default()
2589            },
2590        })
2591    }
2592
2593    async fn response_from_lsp(
2594        self,
2595        actions: Option<lsp::CodeActionResponse>,
2596        lsp_store: Entity<LspStore>,
2597        _: Entity<Buffer>,
2598        server_id: LanguageServerId,
2599        cx: AsyncApp,
2600    ) -> Result<Vec<CodeAction>> {
2601        let requested_kinds_set = if let Some(kinds) = self.kinds {
2602            Some(kinds.into_iter().collect::<HashSet<_>>())
2603        } else {
2604            None
2605        };
2606
2607        let language_server = cx.update(|cx| {
2608            lsp_store
2609                .read(cx)
2610                .language_server_for_id(server_id)
2611                .with_context(|| {
2612                    format!("Missing the language server that just returned a response {server_id}")
2613                })
2614        })??;
2615
2616        let server_capabilities = language_server.capabilities();
2617        let available_commands = server_capabilities
2618            .execute_command_provider
2619            .as_ref()
2620            .map(|options| options.commands.as_slice())
2621            .unwrap_or_default();
2622        Ok(actions
2623            .unwrap_or_default()
2624            .into_iter()
2625            .filter_map(|entry| {
2626                let (lsp_action, resolved) = match entry {
2627                    lsp::CodeActionOrCommand::CodeAction(lsp_action) => {
2628                        if let Some(command) = lsp_action.command.as_ref() {
2629                            if !available_commands.contains(&command.command) {
2630                                return None;
2631                            }
2632                        }
2633                        (LspAction::Action(Box::new(lsp_action)), false)
2634                    }
2635                    lsp::CodeActionOrCommand::Command(command) => {
2636                        if available_commands.contains(&command.command) {
2637                            (LspAction::Command(command), true)
2638                        } else {
2639                            return None;
2640                        }
2641                    }
2642                };
2643
2644                if let Some((requested_kinds, kind)) =
2645                    requested_kinds_set.as_ref().zip(lsp_action.action_kind())
2646                {
2647                    if !requested_kinds.contains(&kind) {
2648                        return None;
2649                    }
2650                }
2651
2652                Some(CodeAction {
2653                    server_id,
2654                    range: self.range.clone(),
2655                    lsp_action,
2656                    resolved,
2657                })
2658            })
2659            .collect())
2660    }
2661
2662    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> proto::GetCodeActions {
2663        proto::GetCodeActions {
2664            project_id,
2665            buffer_id: buffer.remote_id().into(),
2666            start: Some(language::proto::serialize_anchor(&self.range.start)),
2667            end: Some(language::proto::serialize_anchor(&self.range.end)),
2668            version: serialize_version(&buffer.version()),
2669        }
2670    }
2671
2672    async fn from_proto(
2673        message: proto::GetCodeActions,
2674        _: Entity<LspStore>,
2675        buffer: Entity<Buffer>,
2676        mut cx: AsyncApp,
2677    ) -> Result<Self> {
2678        let start = message
2679            .start
2680            .and_then(language::proto::deserialize_anchor)
2681            .context("invalid start")?;
2682        let end = message
2683            .end
2684            .and_then(language::proto::deserialize_anchor)
2685            .context("invalid end")?;
2686        buffer
2687            .update(&mut cx, |buffer, _| {
2688                buffer.wait_for_version(deserialize_version(&message.version))
2689            })?
2690            .await?;
2691
2692        Ok(Self {
2693            range: start..end,
2694            kinds: None,
2695        })
2696    }
2697
2698    fn response_to_proto(
2699        code_actions: Vec<CodeAction>,
2700        _: &mut LspStore,
2701        _: PeerId,
2702        buffer_version: &clock::Global,
2703        _: &mut App,
2704    ) -> proto::GetCodeActionsResponse {
2705        proto::GetCodeActionsResponse {
2706            actions: code_actions
2707                .iter()
2708                .map(LspStore::serialize_code_action)
2709                .collect(),
2710            version: serialize_version(buffer_version),
2711        }
2712    }
2713
2714    async fn response_from_proto(
2715        self,
2716        message: proto::GetCodeActionsResponse,
2717        _: Entity<LspStore>,
2718        buffer: Entity<Buffer>,
2719        mut cx: AsyncApp,
2720    ) -> Result<Vec<CodeAction>> {
2721        buffer
2722            .update(&mut cx, |buffer, _| {
2723                buffer.wait_for_version(deserialize_version(&message.version))
2724            })?
2725            .await?;
2726        message
2727            .actions
2728            .into_iter()
2729            .map(LspStore::deserialize_code_action)
2730            .collect()
2731    }
2732
2733    fn buffer_id_from_proto(message: &proto::GetCodeActions) -> Result<BufferId> {
2734        BufferId::new(message.buffer_id)
2735    }
2736}
2737
2738impl GetCodeActions {
2739    fn supported_code_action_kinds(
2740        capabilities: AdapterServerCapabilities,
2741    ) -> Option<Vec<CodeActionKind>> {
2742        match capabilities.server_capabilities.code_action_provider {
2743            Some(lsp::CodeActionProviderCapability::Options(CodeActionOptions {
2744                code_action_kinds: Some(supported_action_kinds),
2745                ..
2746            })) => Some(supported_action_kinds.clone()),
2747            _ => capabilities.code_action_kinds,
2748        }
2749    }
2750
2751    pub fn can_resolve_actions(capabilities: &ServerCapabilities) -> bool {
2752        capabilities
2753            .code_action_provider
2754            .as_ref()
2755            .and_then(|options| match options {
2756                lsp::CodeActionProviderCapability::Simple(_is_supported) => None,
2757                lsp::CodeActionProviderCapability::Options(options) => options.resolve_provider,
2758            })
2759            .unwrap_or(false)
2760    }
2761}
2762
2763#[async_trait(?Send)]
2764impl LspCommand for OnTypeFormatting {
2765    type Response = Option<Transaction>;
2766    type LspRequest = lsp::request::OnTypeFormatting;
2767    type ProtoRequest = proto::OnTypeFormatting;
2768
2769    fn display_name(&self) -> &str {
2770        "Formatting on typing"
2771    }
2772
2773    fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
2774        let Some(on_type_formatting_options) = &capabilities
2775            .server_capabilities
2776            .document_on_type_formatting_provider
2777        else {
2778            return false;
2779        };
2780        on_type_formatting_options
2781            .first_trigger_character
2782            .contains(&self.trigger)
2783            || on_type_formatting_options
2784                .more_trigger_character
2785                .iter()
2786                .flatten()
2787                .any(|chars| chars.contains(&self.trigger))
2788    }
2789
2790    fn to_lsp(
2791        &self,
2792        path: &Path,
2793        _: &Buffer,
2794        _: &Arc<LanguageServer>,
2795        _: &App,
2796    ) -> Result<lsp::DocumentOnTypeFormattingParams> {
2797        Ok(lsp::DocumentOnTypeFormattingParams {
2798            text_document_position: make_lsp_text_document_position(path, self.position)?,
2799            ch: self.trigger.clone(),
2800            options: self.options.clone(),
2801        })
2802    }
2803
2804    async fn response_from_lsp(
2805        self,
2806        message: Option<Vec<lsp::TextEdit>>,
2807        lsp_store: Entity<LspStore>,
2808        buffer: Entity<Buffer>,
2809        server_id: LanguageServerId,
2810        mut cx: AsyncApp,
2811    ) -> Result<Option<Transaction>> {
2812        if let Some(edits) = message {
2813            let (lsp_adapter, lsp_server) =
2814                language_server_for_buffer(&lsp_store, &buffer, server_id, &mut cx)?;
2815            LocalLspStore::deserialize_text_edits(
2816                lsp_store,
2817                buffer,
2818                edits,
2819                self.push_to_history,
2820                lsp_adapter,
2821                lsp_server,
2822                &mut cx,
2823            )
2824            .await
2825        } else {
2826            Ok(None)
2827        }
2828    }
2829
2830    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> proto::OnTypeFormatting {
2831        proto::OnTypeFormatting {
2832            project_id,
2833            buffer_id: buffer.remote_id().into(),
2834            position: Some(language::proto::serialize_anchor(
2835                &buffer.anchor_before(self.position),
2836            )),
2837            trigger: self.trigger.clone(),
2838            version: serialize_version(&buffer.version()),
2839        }
2840    }
2841
2842    async fn from_proto(
2843        message: proto::OnTypeFormatting,
2844        _: Entity<LspStore>,
2845        buffer: Entity<Buffer>,
2846        mut cx: AsyncApp,
2847    ) -> Result<Self> {
2848        let position = message
2849            .position
2850            .and_then(deserialize_anchor)
2851            .context("invalid position")?;
2852        buffer
2853            .update(&mut cx, |buffer, _| {
2854                buffer.wait_for_version(deserialize_version(&message.version))
2855            })?
2856            .await?;
2857
2858        let options = buffer.update(&mut cx, |buffer, cx| {
2859            lsp_formatting_options(
2860                language_settings(buffer.language().map(|l| l.name()), buffer.file(), cx).as_ref(),
2861            )
2862        })?;
2863
2864        Ok(Self {
2865            position: buffer.read_with(&mut cx, |buffer, _| position.to_point_utf16(buffer))?,
2866            trigger: message.trigger.clone(),
2867            options,
2868            push_to_history: false,
2869        })
2870    }
2871
2872    fn response_to_proto(
2873        response: Option<Transaction>,
2874        _: &mut LspStore,
2875        _: PeerId,
2876        _: &clock::Global,
2877        _: &mut App,
2878    ) -> proto::OnTypeFormattingResponse {
2879        proto::OnTypeFormattingResponse {
2880            transaction: response
2881                .map(|transaction| language::proto::serialize_transaction(&transaction)),
2882        }
2883    }
2884
2885    async fn response_from_proto(
2886        self,
2887        message: proto::OnTypeFormattingResponse,
2888        _: Entity<LspStore>,
2889        _: Entity<Buffer>,
2890        _: AsyncApp,
2891    ) -> Result<Option<Transaction>> {
2892        let Some(transaction) = message.transaction else {
2893            return Ok(None);
2894        };
2895        Ok(Some(language::proto::deserialize_transaction(transaction)?))
2896    }
2897
2898    fn buffer_id_from_proto(message: &proto::OnTypeFormatting) -> Result<BufferId> {
2899        BufferId::new(message.buffer_id)
2900    }
2901}
2902
2903impl InlayHints {
2904    pub async fn lsp_to_project_hint(
2905        lsp_hint: lsp::InlayHint,
2906        buffer_handle: &Entity<Buffer>,
2907        server_id: LanguageServerId,
2908        resolve_state: ResolveState,
2909        force_no_type_left_padding: bool,
2910        cx: &mut AsyncApp,
2911    ) -> anyhow::Result<InlayHint> {
2912        let kind = lsp_hint.kind.and_then(|kind| match kind {
2913            lsp::InlayHintKind::TYPE => Some(InlayHintKind::Type),
2914            lsp::InlayHintKind::PARAMETER => Some(InlayHintKind::Parameter),
2915            _ => None,
2916        });
2917
2918        let position = buffer_handle.read_with(cx, |buffer, _| {
2919            let position = buffer.clip_point_utf16(point_from_lsp(lsp_hint.position), Bias::Left);
2920            if kind == Some(InlayHintKind::Parameter) {
2921                buffer.anchor_before(position)
2922            } else {
2923                buffer.anchor_after(position)
2924            }
2925        })?;
2926        let label = Self::lsp_inlay_label_to_project(lsp_hint.label, server_id)
2927            .await
2928            .context("lsp to project inlay hint conversion")?;
2929        let padding_left = if force_no_type_left_padding && kind == Some(InlayHintKind::Type) {
2930            false
2931        } else {
2932            lsp_hint.padding_left.unwrap_or(false)
2933        };
2934
2935        Ok(InlayHint {
2936            position,
2937            padding_left,
2938            padding_right: lsp_hint.padding_right.unwrap_or(false),
2939            label,
2940            kind,
2941            tooltip: lsp_hint.tooltip.map(|tooltip| match tooltip {
2942                lsp::InlayHintTooltip::String(s) => InlayHintTooltip::String(s),
2943                lsp::InlayHintTooltip::MarkupContent(markup_content) => {
2944                    InlayHintTooltip::MarkupContent(MarkupContent {
2945                        kind: match markup_content.kind {
2946                            lsp::MarkupKind::PlainText => HoverBlockKind::PlainText,
2947                            lsp::MarkupKind::Markdown => HoverBlockKind::Markdown,
2948                        },
2949                        value: markup_content.value,
2950                    })
2951                }
2952            }),
2953            resolve_state,
2954        })
2955    }
2956
2957    async fn lsp_inlay_label_to_project(
2958        lsp_label: lsp::InlayHintLabel,
2959        server_id: LanguageServerId,
2960    ) -> anyhow::Result<InlayHintLabel> {
2961        let label = match lsp_label {
2962            lsp::InlayHintLabel::String(s) => InlayHintLabel::String(s),
2963            lsp::InlayHintLabel::LabelParts(lsp_parts) => {
2964                let mut parts = Vec::with_capacity(lsp_parts.len());
2965                for lsp_part in lsp_parts {
2966                    parts.push(InlayHintLabelPart {
2967                        value: lsp_part.value,
2968                        tooltip: lsp_part.tooltip.map(|tooltip| match tooltip {
2969                            lsp::InlayHintLabelPartTooltip::String(s) => {
2970                                InlayHintLabelPartTooltip::String(s)
2971                            }
2972                            lsp::InlayHintLabelPartTooltip::MarkupContent(markup_content) => {
2973                                InlayHintLabelPartTooltip::MarkupContent(MarkupContent {
2974                                    kind: match markup_content.kind {
2975                                        lsp::MarkupKind::PlainText => HoverBlockKind::PlainText,
2976                                        lsp::MarkupKind::Markdown => HoverBlockKind::Markdown,
2977                                    },
2978                                    value: markup_content.value,
2979                                })
2980                            }
2981                        }),
2982                        location: Some(server_id).zip(lsp_part.location),
2983                    });
2984                }
2985                InlayHintLabel::LabelParts(parts)
2986            }
2987        };
2988
2989        Ok(label)
2990    }
2991
2992    pub fn project_to_proto_hint(response_hint: InlayHint) -> proto::InlayHint {
2993        let (state, lsp_resolve_state) = match response_hint.resolve_state {
2994            ResolveState::Resolved => (0, None),
2995            ResolveState::CanResolve(server_id, resolve_data) => (
2996                1,
2997                Some(proto::resolve_state::LspResolveState {
2998                    server_id: server_id.0 as u64,
2999                    value: resolve_data.map(|json_data| {
3000                        serde_json::to_string(&json_data)
3001                            .expect("failed to serialize resolve json data")
3002                    }),
3003                }),
3004            ),
3005            ResolveState::Resolving => (2, None),
3006        };
3007        let resolve_state = Some(proto::ResolveState {
3008            state,
3009            lsp_resolve_state,
3010        });
3011        proto::InlayHint {
3012            position: Some(language::proto::serialize_anchor(&response_hint.position)),
3013            padding_left: response_hint.padding_left,
3014            padding_right: response_hint.padding_right,
3015            label: Some(proto::InlayHintLabel {
3016                label: Some(match response_hint.label {
3017                    InlayHintLabel::String(s) => proto::inlay_hint_label::Label::Value(s),
3018                    InlayHintLabel::LabelParts(label_parts) => {
3019                        proto::inlay_hint_label::Label::LabelParts(proto::InlayHintLabelParts {
3020                            parts: label_parts.into_iter().map(|label_part| {
3021                                let location_url = label_part.location.as_ref().map(|(_, location)| location.uri.to_string());
3022                                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 });
3023                                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 });
3024                                proto::InlayHintLabelPart {
3025                                value: label_part.value,
3026                                tooltip: label_part.tooltip.map(|tooltip| {
3027                                    let proto_tooltip = match tooltip {
3028                                        InlayHintLabelPartTooltip::String(s) => proto::inlay_hint_label_part_tooltip::Content::Value(s),
3029                                        InlayHintLabelPartTooltip::MarkupContent(markup_content) => proto::inlay_hint_label_part_tooltip::Content::MarkupContent(proto::MarkupContent {
3030                                            is_markdown: markup_content.kind == HoverBlockKind::Markdown,
3031                                            value: markup_content.value,
3032                                        }),
3033                                    };
3034                                    proto::InlayHintLabelPartTooltip {content: Some(proto_tooltip)}
3035                                }),
3036                                location_url,
3037                                location_range_start,
3038                                location_range_end,
3039                                language_server_id: label_part.location.as_ref().map(|(server_id, _)| server_id.0 as u64),
3040                            }}).collect()
3041                        })
3042                    }
3043                }),
3044            }),
3045            kind: response_hint.kind.map(|kind| kind.name().to_string()),
3046            tooltip: response_hint.tooltip.map(|response_tooltip| {
3047                let proto_tooltip = match response_tooltip {
3048                    InlayHintTooltip::String(s) => proto::inlay_hint_tooltip::Content::Value(s),
3049                    InlayHintTooltip::MarkupContent(markup_content) => {
3050                        proto::inlay_hint_tooltip::Content::MarkupContent(proto::MarkupContent {
3051                            is_markdown: markup_content.kind == HoverBlockKind::Markdown,
3052                            value: markup_content.value,
3053                        })
3054                    }
3055                };
3056                proto::InlayHintTooltip {
3057                    content: Some(proto_tooltip),
3058                }
3059            }),
3060            resolve_state,
3061        }
3062    }
3063
3064    pub fn proto_to_project_hint(message_hint: proto::InlayHint) -> anyhow::Result<InlayHint> {
3065        let resolve_state = message_hint.resolve_state.as_ref().unwrap_or_else(|| {
3066            panic!("incorrect proto inlay hint message: no resolve state in hint {message_hint:?}",)
3067        });
3068        let resolve_state_data = resolve_state
3069            .lsp_resolve_state.as_ref()
3070            .map(|lsp_resolve_state| {
3071                let value = lsp_resolve_state.value.as_deref().map(|value| {
3072                    serde_json::from_str::<Option<lsp::LSPAny>>(value)
3073                        .with_context(|| format!("incorrect proto inlay hint message: non-json resolve state {lsp_resolve_state:?}"))
3074                }).transpose()?.flatten();
3075                anyhow::Ok((LanguageServerId(lsp_resolve_state.server_id as usize), value))
3076            })
3077            .transpose()?;
3078        let resolve_state = match resolve_state.state {
3079            0 => ResolveState::Resolved,
3080            1 => {
3081                let (server_id, lsp_resolve_state) = resolve_state_data.with_context(|| {
3082                    format!(
3083                        "No lsp resolve data for the hint that can be resolved: {message_hint:?}"
3084                    )
3085                })?;
3086                ResolveState::CanResolve(server_id, lsp_resolve_state)
3087            }
3088            2 => ResolveState::Resolving,
3089            invalid => {
3090                anyhow::bail!("Unexpected resolve state {invalid} for hint {message_hint:?}")
3091            }
3092        };
3093        Ok(InlayHint {
3094            position: message_hint
3095                .position
3096                .and_then(language::proto::deserialize_anchor)
3097                .context("invalid position")?,
3098            label: match message_hint
3099                .label
3100                .and_then(|label| label.label)
3101                .context("missing label")?
3102            {
3103                proto::inlay_hint_label::Label::Value(s) => InlayHintLabel::String(s),
3104                proto::inlay_hint_label::Label::LabelParts(parts) => {
3105                    let mut label_parts = Vec::new();
3106                    for part in parts.parts {
3107                        label_parts.push(InlayHintLabelPart {
3108                            value: part.value,
3109                            tooltip: part.tooltip.map(|tooltip| match tooltip.content {
3110                                Some(proto::inlay_hint_label_part_tooltip::Content::Value(s)) => {
3111                                    InlayHintLabelPartTooltip::String(s)
3112                                }
3113                                Some(
3114                                    proto::inlay_hint_label_part_tooltip::Content::MarkupContent(
3115                                        markup_content,
3116                                    ),
3117                                ) => InlayHintLabelPartTooltip::MarkupContent(MarkupContent {
3118                                    kind: if markup_content.is_markdown {
3119                                        HoverBlockKind::Markdown
3120                                    } else {
3121                                        HoverBlockKind::PlainText
3122                                    },
3123                                    value: markup_content.value,
3124                                }),
3125                                None => InlayHintLabelPartTooltip::String(String::new()),
3126                            }),
3127                            location: {
3128                                match part
3129                                    .location_url
3130                                    .zip(
3131                                        part.location_range_start.and_then(|start| {
3132                                            Some(start..part.location_range_end?)
3133                                        }),
3134                                    )
3135                                    .zip(part.language_server_id)
3136                                {
3137                                    Some(((uri, range), server_id)) => Some((
3138                                        LanguageServerId(server_id as usize),
3139                                        lsp::Location {
3140                                            uri: lsp::Url::parse(&uri)
3141                                                .context("invalid uri in hint part {part:?}")?,
3142                                            range: lsp::Range::new(
3143                                                point_to_lsp(PointUtf16::new(
3144                                                    range.start.row,
3145                                                    range.start.column,
3146                                                )),
3147                                                point_to_lsp(PointUtf16::new(
3148                                                    range.end.row,
3149                                                    range.end.column,
3150                                                )),
3151                                            ),
3152                                        },
3153                                    )),
3154                                    None => None,
3155                                }
3156                            },
3157                        });
3158                    }
3159
3160                    InlayHintLabel::LabelParts(label_parts)
3161                }
3162            },
3163            padding_left: message_hint.padding_left,
3164            padding_right: message_hint.padding_right,
3165            kind: message_hint
3166                .kind
3167                .as_deref()
3168                .and_then(InlayHintKind::from_name),
3169            tooltip: message_hint.tooltip.and_then(|tooltip| {
3170                Some(match tooltip.content? {
3171                    proto::inlay_hint_tooltip::Content::Value(s) => InlayHintTooltip::String(s),
3172                    proto::inlay_hint_tooltip::Content::MarkupContent(markup_content) => {
3173                        InlayHintTooltip::MarkupContent(MarkupContent {
3174                            kind: if markup_content.is_markdown {
3175                                HoverBlockKind::Markdown
3176                            } else {
3177                                HoverBlockKind::PlainText
3178                            },
3179                            value: markup_content.value,
3180                        })
3181                    }
3182                })
3183            }),
3184            resolve_state,
3185        })
3186    }
3187
3188    pub fn project_to_lsp_hint(hint: InlayHint, snapshot: &BufferSnapshot) -> lsp::InlayHint {
3189        lsp::InlayHint {
3190            position: point_to_lsp(hint.position.to_point_utf16(snapshot)),
3191            kind: hint.kind.map(|kind| match kind {
3192                InlayHintKind::Type => lsp::InlayHintKind::TYPE,
3193                InlayHintKind::Parameter => lsp::InlayHintKind::PARAMETER,
3194            }),
3195            text_edits: None,
3196            tooltip: hint.tooltip.and_then(|tooltip| {
3197                Some(match tooltip {
3198                    InlayHintTooltip::String(s) => lsp::InlayHintTooltip::String(s),
3199                    InlayHintTooltip::MarkupContent(markup_content) => {
3200                        lsp::InlayHintTooltip::MarkupContent(lsp::MarkupContent {
3201                            kind: match markup_content.kind {
3202                                HoverBlockKind::PlainText => lsp::MarkupKind::PlainText,
3203                                HoverBlockKind::Markdown => lsp::MarkupKind::Markdown,
3204                                HoverBlockKind::Code { .. } => return None,
3205                            },
3206                            value: markup_content.value,
3207                        })
3208                    }
3209                })
3210            }),
3211            label: match hint.label {
3212                InlayHintLabel::String(s) => lsp::InlayHintLabel::String(s),
3213                InlayHintLabel::LabelParts(label_parts) => lsp::InlayHintLabel::LabelParts(
3214                    label_parts
3215                        .into_iter()
3216                        .map(|part| lsp::InlayHintLabelPart {
3217                            value: part.value,
3218                            tooltip: part.tooltip.and_then(|tooltip| {
3219                                Some(match tooltip {
3220                                    InlayHintLabelPartTooltip::String(s) => {
3221                                        lsp::InlayHintLabelPartTooltip::String(s)
3222                                    }
3223                                    InlayHintLabelPartTooltip::MarkupContent(markup_content) => {
3224                                        lsp::InlayHintLabelPartTooltip::MarkupContent(
3225                                            lsp::MarkupContent {
3226                                                kind: match markup_content.kind {
3227                                                    HoverBlockKind::PlainText => {
3228                                                        lsp::MarkupKind::PlainText
3229                                                    }
3230                                                    HoverBlockKind::Markdown => {
3231                                                        lsp::MarkupKind::Markdown
3232                                                    }
3233                                                    HoverBlockKind::Code { .. } => return None,
3234                                                },
3235                                                value: markup_content.value,
3236                                            },
3237                                        )
3238                                    }
3239                                })
3240                            }),
3241                            location: part.location.map(|(_, location)| location),
3242                            command: None,
3243                        })
3244                        .collect(),
3245                ),
3246            },
3247            padding_left: Some(hint.padding_left),
3248            padding_right: Some(hint.padding_right),
3249            data: match hint.resolve_state {
3250                ResolveState::CanResolve(_, data) => data,
3251                ResolveState::Resolving | ResolveState::Resolved => None,
3252            },
3253        }
3254    }
3255
3256    pub fn can_resolve_inlays(capabilities: &ServerCapabilities) -> bool {
3257        capabilities
3258            .inlay_hint_provider
3259            .as_ref()
3260            .and_then(|options| match options {
3261                OneOf::Left(_is_supported) => None,
3262                OneOf::Right(capabilities) => match capabilities {
3263                    lsp::InlayHintServerCapabilities::Options(o) => o.resolve_provider,
3264                    lsp::InlayHintServerCapabilities::RegistrationOptions(o) => {
3265                        o.inlay_hint_options.resolve_provider
3266                    }
3267                },
3268            })
3269            .unwrap_or(false)
3270    }
3271}
3272
3273#[async_trait(?Send)]
3274impl LspCommand for InlayHints {
3275    type Response = Vec<InlayHint>;
3276    type LspRequest = lsp::InlayHintRequest;
3277    type ProtoRequest = proto::InlayHints;
3278
3279    fn display_name(&self) -> &str {
3280        "Inlay hints"
3281    }
3282
3283    fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
3284        let Some(inlay_hint_provider) = &capabilities.server_capabilities.inlay_hint_provider
3285        else {
3286            return false;
3287        };
3288        match inlay_hint_provider {
3289            lsp::OneOf::Left(enabled) => *enabled,
3290            lsp::OneOf::Right(inlay_hint_capabilities) => match inlay_hint_capabilities {
3291                lsp::InlayHintServerCapabilities::Options(_) => true,
3292                lsp::InlayHintServerCapabilities::RegistrationOptions(_) => false,
3293            },
3294        }
3295    }
3296
3297    fn to_lsp(
3298        &self,
3299        path: &Path,
3300        buffer: &Buffer,
3301        _: &Arc<LanguageServer>,
3302        _: &App,
3303    ) -> Result<lsp::InlayHintParams> {
3304        Ok(lsp::InlayHintParams {
3305            text_document: lsp::TextDocumentIdentifier {
3306                uri: file_path_to_lsp_url(path)?,
3307            },
3308            range: range_to_lsp(self.range.to_point_utf16(buffer))?,
3309            work_done_progress_params: Default::default(),
3310        })
3311    }
3312
3313    async fn response_from_lsp(
3314        self,
3315        message: Option<Vec<lsp::InlayHint>>,
3316        lsp_store: Entity<LspStore>,
3317        buffer: Entity<Buffer>,
3318        server_id: LanguageServerId,
3319        mut cx: AsyncApp,
3320    ) -> anyhow::Result<Vec<InlayHint>> {
3321        let (lsp_adapter, lsp_server) =
3322            language_server_for_buffer(&lsp_store, &buffer, server_id, &mut cx)?;
3323        // `typescript-language-server` adds padding to the left for type hints, turning
3324        // `const foo: boolean` into `const foo : boolean` which looks odd.
3325        // `rust-analyzer` does not have the padding for this case, and we have to accommodate both.
3326        //
3327        // We could trim the whole string, but being pessimistic on par with the situation above,
3328        // there might be a hint with multiple whitespaces at the end(s) which we need to display properly.
3329        // Hence let's use a heuristic first to handle the most awkward case and look for more.
3330        let force_no_type_left_padding =
3331            lsp_adapter.name.0.as_ref() == "typescript-language-server";
3332
3333        let hints = message.unwrap_or_default().into_iter().map(|lsp_hint| {
3334            let resolve_state = if InlayHints::can_resolve_inlays(&lsp_server.capabilities()) {
3335                ResolveState::CanResolve(lsp_server.server_id(), lsp_hint.data.clone())
3336            } else {
3337                ResolveState::Resolved
3338            };
3339
3340            let buffer = buffer.clone();
3341            cx.spawn(async move |cx| {
3342                InlayHints::lsp_to_project_hint(
3343                    lsp_hint,
3344                    &buffer,
3345                    server_id,
3346                    resolve_state,
3347                    force_no_type_left_padding,
3348                    cx,
3349                )
3350                .await
3351            })
3352        });
3353        future::join_all(hints)
3354            .await
3355            .into_iter()
3356            .collect::<anyhow::Result<_>>()
3357            .context("lsp to project inlay hints conversion")
3358    }
3359
3360    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> proto::InlayHints {
3361        proto::InlayHints {
3362            project_id,
3363            buffer_id: buffer.remote_id().into(),
3364            start: Some(language::proto::serialize_anchor(&self.range.start)),
3365            end: Some(language::proto::serialize_anchor(&self.range.end)),
3366            version: serialize_version(&buffer.version()),
3367        }
3368    }
3369
3370    async fn from_proto(
3371        message: proto::InlayHints,
3372        _: Entity<LspStore>,
3373        buffer: Entity<Buffer>,
3374        mut cx: AsyncApp,
3375    ) -> Result<Self> {
3376        let start = message
3377            .start
3378            .and_then(language::proto::deserialize_anchor)
3379            .context("invalid start")?;
3380        let end = message
3381            .end
3382            .and_then(language::proto::deserialize_anchor)
3383            .context("invalid end")?;
3384        buffer
3385            .update(&mut cx, |buffer, _| {
3386                buffer.wait_for_version(deserialize_version(&message.version))
3387            })?
3388            .await?;
3389
3390        Ok(Self { range: start..end })
3391    }
3392
3393    fn response_to_proto(
3394        response: Vec<InlayHint>,
3395        _: &mut LspStore,
3396        _: PeerId,
3397        buffer_version: &clock::Global,
3398        _: &mut App,
3399    ) -> proto::InlayHintsResponse {
3400        proto::InlayHintsResponse {
3401            hints: response
3402                .into_iter()
3403                .map(InlayHints::project_to_proto_hint)
3404                .collect(),
3405            version: serialize_version(buffer_version),
3406        }
3407    }
3408
3409    async fn response_from_proto(
3410        self,
3411        message: proto::InlayHintsResponse,
3412        _: Entity<LspStore>,
3413        buffer: Entity<Buffer>,
3414        mut cx: AsyncApp,
3415    ) -> anyhow::Result<Vec<InlayHint>> {
3416        buffer
3417            .update(&mut cx, |buffer, _| {
3418                buffer.wait_for_version(deserialize_version(&message.version))
3419            })?
3420            .await?;
3421
3422        let mut hints = Vec::new();
3423        for message_hint in message.hints {
3424            hints.push(InlayHints::proto_to_project_hint(message_hint)?);
3425        }
3426
3427        Ok(hints)
3428    }
3429
3430    fn buffer_id_from_proto(message: &proto::InlayHints) -> Result<BufferId> {
3431        BufferId::new(message.buffer_id)
3432    }
3433}
3434
3435#[async_trait(?Send)]
3436impl LspCommand for GetCodeLens {
3437    type Response = Vec<CodeAction>;
3438    type LspRequest = lsp::CodeLensRequest;
3439    type ProtoRequest = proto::GetCodeLens;
3440
3441    fn display_name(&self) -> &str {
3442        "Code Lens"
3443    }
3444
3445    fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
3446        capabilities
3447            .server_capabilities
3448            .code_lens_provider
3449            .as_ref()
3450            .map_or(false, |code_lens_options| {
3451                code_lens_options.resolve_provider.unwrap_or(false)
3452            })
3453    }
3454
3455    fn to_lsp(
3456        &self,
3457        path: &Path,
3458        _: &Buffer,
3459        _: &Arc<LanguageServer>,
3460        _: &App,
3461    ) -> Result<lsp::CodeLensParams> {
3462        Ok(lsp::CodeLensParams {
3463            text_document: lsp::TextDocumentIdentifier {
3464                uri: file_path_to_lsp_url(path)?,
3465            },
3466            work_done_progress_params: lsp::WorkDoneProgressParams::default(),
3467            partial_result_params: lsp::PartialResultParams::default(),
3468        })
3469    }
3470
3471    async fn response_from_lsp(
3472        self,
3473        message: Option<Vec<lsp::CodeLens>>,
3474        lsp_store: Entity<LspStore>,
3475        buffer: Entity<Buffer>,
3476        server_id: LanguageServerId,
3477        mut cx: AsyncApp,
3478    ) -> anyhow::Result<Vec<CodeAction>> {
3479        let snapshot = buffer.read_with(&mut cx, |buffer, _| buffer.snapshot())?;
3480        let language_server = cx.update(|cx| {
3481            lsp_store
3482                .read(cx)
3483                .language_server_for_id(server_id)
3484                .with_context(|| {
3485                    format!("Missing the language server that just returned a response {server_id}")
3486                })
3487        })??;
3488        let server_capabilities = language_server.capabilities();
3489        let available_commands = server_capabilities
3490            .execute_command_provider
3491            .as_ref()
3492            .map(|options| options.commands.as_slice())
3493            .unwrap_or_default();
3494        Ok(message
3495            .unwrap_or_default()
3496            .into_iter()
3497            .filter(|code_lens| {
3498                code_lens
3499                    .command
3500                    .as_ref()
3501                    .is_none_or(|command| available_commands.contains(&command.command))
3502            })
3503            .map(|code_lens| {
3504                let code_lens_range = range_from_lsp(code_lens.range);
3505                let start = snapshot.clip_point_utf16(code_lens_range.start, Bias::Left);
3506                let end = snapshot.clip_point_utf16(code_lens_range.end, Bias::Right);
3507                let range = snapshot.anchor_before(start)..snapshot.anchor_after(end);
3508                CodeAction {
3509                    server_id,
3510                    range,
3511                    lsp_action: LspAction::CodeLens(code_lens),
3512                    resolved: false,
3513                }
3514            })
3515            .collect())
3516    }
3517
3518    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> proto::GetCodeLens {
3519        proto::GetCodeLens {
3520            project_id,
3521            buffer_id: buffer.remote_id().into(),
3522            version: serialize_version(&buffer.version()),
3523        }
3524    }
3525
3526    async fn from_proto(
3527        message: proto::GetCodeLens,
3528        _: Entity<LspStore>,
3529        buffer: Entity<Buffer>,
3530        mut cx: AsyncApp,
3531    ) -> Result<Self> {
3532        buffer
3533            .update(&mut cx, |buffer, _| {
3534                buffer.wait_for_version(deserialize_version(&message.version))
3535            })?
3536            .await?;
3537        Ok(Self)
3538    }
3539
3540    fn response_to_proto(
3541        response: Vec<CodeAction>,
3542        _: &mut LspStore,
3543        _: PeerId,
3544        buffer_version: &clock::Global,
3545        _: &mut App,
3546    ) -> proto::GetCodeLensResponse {
3547        proto::GetCodeLensResponse {
3548            lens_actions: response
3549                .iter()
3550                .map(LspStore::serialize_code_action)
3551                .collect(),
3552            version: serialize_version(buffer_version),
3553        }
3554    }
3555
3556    async fn response_from_proto(
3557        self,
3558        message: proto::GetCodeLensResponse,
3559        _: Entity<LspStore>,
3560        buffer: Entity<Buffer>,
3561        mut cx: AsyncApp,
3562    ) -> anyhow::Result<Vec<CodeAction>> {
3563        buffer
3564            .update(&mut cx, |buffer, _| {
3565                buffer.wait_for_version(deserialize_version(&message.version))
3566            })?
3567            .await?;
3568        message
3569            .lens_actions
3570            .into_iter()
3571            .map(LspStore::deserialize_code_action)
3572            .collect::<Result<Vec<_>>>()
3573            .context("deserializing proto code lens response")
3574    }
3575
3576    fn buffer_id_from_proto(message: &proto::GetCodeLens) -> Result<BufferId> {
3577        BufferId::new(message.buffer_id)
3578    }
3579}
3580
3581#[async_trait(?Send)]
3582impl LspCommand for LinkedEditingRange {
3583    type Response = Vec<Range<Anchor>>;
3584    type LspRequest = lsp::request::LinkedEditingRange;
3585    type ProtoRequest = proto::LinkedEditingRange;
3586
3587    fn display_name(&self) -> &str {
3588        "Linked editing range"
3589    }
3590
3591    fn check_capabilities(&self, capabilities: AdapterServerCapabilities) -> bool {
3592        let Some(linked_editing_options) = &capabilities
3593            .server_capabilities
3594            .linked_editing_range_provider
3595        else {
3596            return false;
3597        };
3598        if let LinkedEditingRangeServerCapabilities::Simple(false) = linked_editing_options {
3599            return false;
3600        }
3601        true
3602    }
3603
3604    fn to_lsp(
3605        &self,
3606        path: &Path,
3607        buffer: &Buffer,
3608        _server: &Arc<LanguageServer>,
3609        _: &App,
3610    ) -> Result<lsp::LinkedEditingRangeParams> {
3611        let position = self.position.to_point_utf16(&buffer.snapshot());
3612        Ok(lsp::LinkedEditingRangeParams {
3613            text_document_position_params: make_lsp_text_document_position(path, position)?,
3614            work_done_progress_params: Default::default(),
3615        })
3616    }
3617
3618    async fn response_from_lsp(
3619        self,
3620        message: Option<lsp::LinkedEditingRanges>,
3621        _: Entity<LspStore>,
3622        buffer: Entity<Buffer>,
3623        _server_id: LanguageServerId,
3624        cx: AsyncApp,
3625    ) -> Result<Vec<Range<Anchor>>> {
3626        if let Some(lsp::LinkedEditingRanges { mut ranges, .. }) = message {
3627            ranges.sort_by_key(|range| range.start);
3628
3629            buffer.read_with(&cx, |buffer, _| {
3630                ranges
3631                    .into_iter()
3632                    .map(|range| {
3633                        let start =
3634                            buffer.clip_point_utf16(point_from_lsp(range.start), Bias::Left);
3635                        let end = buffer.clip_point_utf16(point_from_lsp(range.end), Bias::Left);
3636                        buffer.anchor_before(start)..buffer.anchor_after(end)
3637                    })
3638                    .collect()
3639            })
3640        } else {
3641            Ok(vec![])
3642        }
3643    }
3644
3645    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> proto::LinkedEditingRange {
3646        proto::LinkedEditingRange {
3647            project_id,
3648            buffer_id: buffer.remote_id().to_proto(),
3649            position: Some(serialize_anchor(&self.position)),
3650            version: serialize_version(&buffer.version()),
3651        }
3652    }
3653
3654    async fn from_proto(
3655        message: proto::LinkedEditingRange,
3656        _: Entity<LspStore>,
3657        buffer: Entity<Buffer>,
3658        mut cx: AsyncApp,
3659    ) -> Result<Self> {
3660        let position = message.position.context("invalid position")?;
3661        buffer
3662            .update(&mut cx, |buffer, _| {
3663                buffer.wait_for_version(deserialize_version(&message.version))
3664            })?
3665            .await?;
3666        let position = deserialize_anchor(position).context("invalid position")?;
3667        buffer
3668            .update(&mut cx, |buffer, _| buffer.wait_for_anchors([position]))?
3669            .await?;
3670        Ok(Self { position })
3671    }
3672
3673    fn response_to_proto(
3674        response: Vec<Range<Anchor>>,
3675        _: &mut LspStore,
3676        _: PeerId,
3677        buffer_version: &clock::Global,
3678        _: &mut App,
3679    ) -> proto::LinkedEditingRangeResponse {
3680        proto::LinkedEditingRangeResponse {
3681            items: response
3682                .into_iter()
3683                .map(|range| proto::AnchorRange {
3684                    start: Some(serialize_anchor(&range.start)),
3685                    end: Some(serialize_anchor(&range.end)),
3686                })
3687                .collect(),
3688            version: serialize_version(buffer_version),
3689        }
3690    }
3691
3692    async fn response_from_proto(
3693        self,
3694        message: proto::LinkedEditingRangeResponse,
3695        _: Entity<LspStore>,
3696        buffer: Entity<Buffer>,
3697        mut cx: AsyncApp,
3698    ) -> Result<Vec<Range<Anchor>>> {
3699        buffer
3700            .update(&mut cx, |buffer, _| {
3701                buffer.wait_for_version(deserialize_version(&message.version))
3702            })?
3703            .await?;
3704        let items: Vec<Range<Anchor>> = message
3705            .items
3706            .into_iter()
3707            .filter_map(|range| {
3708                let start = deserialize_anchor(range.start?)?;
3709                let end = deserialize_anchor(range.end?)?;
3710                Some(start..end)
3711            })
3712            .collect();
3713        for range in &items {
3714            buffer
3715                .update(&mut cx, |buffer, _| {
3716                    buffer.wait_for_anchors([range.start, range.end])
3717                })?
3718                .await?;
3719        }
3720        Ok(items)
3721    }
3722
3723    fn buffer_id_from_proto(message: &proto::LinkedEditingRange) -> Result<BufferId> {
3724        BufferId::new(message.buffer_id)
3725    }
3726}
3727
3728impl GetDocumentDiagnostics {
3729    pub fn diagnostics_from_proto(
3730        response: proto::GetDocumentDiagnosticsResponse,
3731    ) -> Vec<LspPullDiagnostics> {
3732        response
3733            .pulled_diagnostics
3734            .into_iter()
3735            .filter_map(|diagnostics| {
3736                Some(LspPullDiagnostics::Response {
3737                    server_id: LanguageServerId::from_proto(diagnostics.server_id),
3738                    uri: lsp::Url::from_str(diagnostics.uri.as_str()).log_err()?,
3739                    diagnostics: if diagnostics.changed {
3740                        PulledDiagnostics::Unchanged {
3741                            result_id: diagnostics.result_id?,
3742                        }
3743                    } else {
3744                        PulledDiagnostics::Changed {
3745                            result_id: diagnostics.result_id,
3746                            diagnostics: diagnostics
3747                                .diagnostics
3748                                .into_iter()
3749                                .filter_map(|diagnostic| {
3750                                    GetDocumentDiagnostics::deserialize_lsp_diagnostic(diagnostic)
3751                                        .context("deserializing diagnostics")
3752                                        .log_err()
3753                                })
3754                                .collect(),
3755                        }
3756                    },
3757                })
3758            })
3759            .collect()
3760    }
3761
3762    fn deserialize_lsp_diagnostic(diagnostic: proto::LspDiagnostic) -> Result<lsp::Diagnostic> {
3763        let start = diagnostic.start.context("invalid start range")?;
3764        let end = diagnostic.end.context("invalid end range")?;
3765
3766        let range = Range::<PointUtf16> {
3767            start: PointUtf16 {
3768                row: start.row,
3769                column: start.column,
3770            },
3771            end: PointUtf16 {
3772                row: end.row,
3773                column: end.column,
3774            },
3775        };
3776
3777        let data = diagnostic.data.and_then(|data| Value::from_str(&data).ok());
3778        let code = diagnostic.code.map(lsp::NumberOrString::String);
3779
3780        let related_information = diagnostic
3781            .related_information
3782            .into_iter()
3783            .map(|info| {
3784                let start = info.location_range_start.unwrap();
3785                let end = info.location_range_end.unwrap();
3786
3787                lsp::DiagnosticRelatedInformation {
3788                    location: lsp::Location {
3789                        range: lsp::Range {
3790                            start: point_to_lsp(PointUtf16::new(start.row, start.column)),
3791                            end: point_to_lsp(PointUtf16::new(end.row, end.column)),
3792                        },
3793                        uri: lsp::Url::parse(&info.location_url.unwrap()).unwrap(),
3794                    },
3795                    message: info.message.clone(),
3796                }
3797            })
3798            .collect::<Vec<_>>();
3799
3800        let tags = diagnostic
3801            .tags
3802            .into_iter()
3803            .filter_map(|tag| match proto::LspDiagnosticTag::from_i32(tag) {
3804                Some(proto::LspDiagnosticTag::Unnecessary) => Some(lsp::DiagnosticTag::UNNECESSARY),
3805                Some(proto::LspDiagnosticTag::Deprecated) => Some(lsp::DiagnosticTag::DEPRECATED),
3806                _ => None,
3807            })
3808            .collect::<Vec<_>>();
3809
3810        Ok(lsp::Diagnostic {
3811            range: language::range_to_lsp(range)?,
3812            severity: match proto::lsp_diagnostic::Severity::from_i32(diagnostic.severity).unwrap()
3813            {
3814                proto::lsp_diagnostic::Severity::Error => Some(lsp::DiagnosticSeverity::ERROR),
3815                proto::lsp_diagnostic::Severity::Warning => Some(lsp::DiagnosticSeverity::WARNING),
3816                proto::lsp_diagnostic::Severity::Information => {
3817                    Some(lsp::DiagnosticSeverity::INFORMATION)
3818                }
3819                proto::lsp_diagnostic::Severity::Hint => Some(lsp::DiagnosticSeverity::HINT),
3820                _ => None,
3821            },
3822            code,
3823            code_description: match diagnostic.code_description {
3824                Some(code_description) => Some(CodeDescription {
3825                    href: Some(lsp::Url::parse(&code_description).unwrap()),
3826                }),
3827                None => None,
3828            },
3829            related_information: Some(related_information),
3830            tags: Some(tags),
3831            source: diagnostic.source.clone(),
3832            message: diagnostic.message,
3833            data,
3834        })
3835    }
3836
3837    fn serialize_lsp_diagnostic(diagnostic: lsp::Diagnostic) -> Result<proto::LspDiagnostic> {
3838        let range = language::range_from_lsp(diagnostic.range);
3839        let related_information = diagnostic
3840            .related_information
3841            .unwrap_or_default()
3842            .into_iter()
3843            .map(|related_information| {
3844                let location_range_start =
3845                    point_from_lsp(related_information.location.range.start).0;
3846                let location_range_end = point_from_lsp(related_information.location.range.end).0;
3847
3848                Ok(proto::LspDiagnosticRelatedInformation {
3849                    location_url: Some(related_information.location.uri.to_string()),
3850                    location_range_start: Some(proto::PointUtf16 {
3851                        row: location_range_start.row,
3852                        column: location_range_start.column,
3853                    }),
3854                    location_range_end: Some(proto::PointUtf16 {
3855                        row: location_range_end.row,
3856                        column: location_range_end.column,
3857                    }),
3858                    message: related_information.message,
3859                })
3860            })
3861            .collect::<Result<Vec<_>>>()?;
3862
3863        let tags = diagnostic
3864            .tags
3865            .unwrap_or_default()
3866            .into_iter()
3867            .map(|tag| match tag {
3868                lsp::DiagnosticTag::UNNECESSARY => proto::LspDiagnosticTag::Unnecessary,
3869                lsp::DiagnosticTag::DEPRECATED => proto::LspDiagnosticTag::Deprecated,
3870                _ => proto::LspDiagnosticTag::None,
3871            } as i32)
3872            .collect();
3873
3874        Ok(proto::LspDiagnostic {
3875            start: Some(proto::PointUtf16 {
3876                row: range.start.0.row,
3877                column: range.start.0.column,
3878            }),
3879            end: Some(proto::PointUtf16 {
3880                row: range.end.0.row,
3881                column: range.end.0.column,
3882            }),
3883            severity: match diagnostic.severity {
3884                Some(lsp::DiagnosticSeverity::ERROR) => proto::lsp_diagnostic::Severity::Error,
3885                Some(lsp::DiagnosticSeverity::WARNING) => proto::lsp_diagnostic::Severity::Warning,
3886                Some(lsp::DiagnosticSeverity::INFORMATION) => {
3887                    proto::lsp_diagnostic::Severity::Information
3888                }
3889                Some(lsp::DiagnosticSeverity::HINT) => proto::lsp_diagnostic::Severity::Hint,
3890                _ => proto::lsp_diagnostic::Severity::None,
3891            } as i32,
3892            code: diagnostic.code.as_ref().map(|code| match code {
3893                lsp::NumberOrString::Number(code) => code.to_string(),
3894                lsp::NumberOrString::String(code) => code.clone(),
3895            }),
3896            source: diagnostic.source.clone(),
3897            related_information,
3898            tags,
3899            code_description: diagnostic
3900                .code_description
3901                .and_then(|desc| desc.href.map(|url| url.to_string())),
3902            message: diagnostic.message,
3903            data: diagnostic.data.as_ref().map(|data| data.to_string()),
3904        })
3905    }
3906
3907    pub fn deserialize_workspace_diagnostics_report(
3908        report: lsp::WorkspaceDiagnosticReportResult,
3909        server_id: LanguageServerId,
3910    ) -> Vec<WorkspaceLspPullDiagnostics> {
3911        let mut pulled_diagnostics = HashMap::default();
3912        match report {
3913            lsp::WorkspaceDiagnosticReportResult::Report(workspace_diagnostic_report) => {
3914                for report in workspace_diagnostic_report.items {
3915                    match report {
3916                        lsp::WorkspaceDocumentDiagnosticReport::Full(report) => {
3917                            process_full_workspace_diagnostics_report(
3918                                &mut pulled_diagnostics,
3919                                server_id,
3920                                report,
3921                            )
3922                        }
3923                        lsp::WorkspaceDocumentDiagnosticReport::Unchanged(report) => {
3924                            process_unchanged_workspace_diagnostics_report(
3925                                &mut pulled_diagnostics,
3926                                server_id,
3927                                report,
3928                            )
3929                        }
3930                    }
3931                }
3932            }
3933            lsp::WorkspaceDiagnosticReportResult::Partial(
3934                workspace_diagnostic_report_partial_result,
3935            ) => {
3936                for report in workspace_diagnostic_report_partial_result.items {
3937                    match report {
3938                        lsp::WorkspaceDocumentDiagnosticReport::Full(report) => {
3939                            process_full_workspace_diagnostics_report(
3940                                &mut pulled_diagnostics,
3941                                server_id,
3942                                report,
3943                            )
3944                        }
3945                        lsp::WorkspaceDocumentDiagnosticReport::Unchanged(report) => {
3946                            process_unchanged_workspace_diagnostics_report(
3947                                &mut pulled_diagnostics,
3948                                server_id,
3949                                report,
3950                            )
3951                        }
3952                    }
3953                }
3954            }
3955        }
3956        pulled_diagnostics.into_values().collect()
3957    }
3958}
3959
3960#[derive(Debug)]
3961pub struct WorkspaceLspPullDiagnostics {
3962    pub version: Option<i32>,
3963    pub diagnostics: LspPullDiagnostics,
3964}
3965
3966fn process_full_workspace_diagnostics_report(
3967    diagnostics: &mut HashMap<lsp::Url, WorkspaceLspPullDiagnostics>,
3968    server_id: LanguageServerId,
3969    report: lsp::WorkspaceFullDocumentDiagnosticReport,
3970) {
3971    let mut new_diagnostics = HashMap::default();
3972    process_full_diagnostics_report(
3973        &mut new_diagnostics,
3974        server_id,
3975        report.uri,
3976        report.full_document_diagnostic_report,
3977    );
3978    diagnostics.extend(new_diagnostics.into_iter().map(|(uri, diagnostics)| {
3979        (
3980            uri,
3981            WorkspaceLspPullDiagnostics {
3982                version: report.version.map(|v| v as i32),
3983                diagnostics,
3984            },
3985        )
3986    }));
3987}
3988
3989fn process_unchanged_workspace_diagnostics_report(
3990    diagnostics: &mut HashMap<lsp::Url, WorkspaceLspPullDiagnostics>,
3991    server_id: LanguageServerId,
3992    report: lsp::WorkspaceUnchangedDocumentDiagnosticReport,
3993) {
3994    let mut new_diagnostics = HashMap::default();
3995    process_unchanged_diagnostics_report(
3996        &mut new_diagnostics,
3997        server_id,
3998        report.uri,
3999        report.unchanged_document_diagnostic_report,
4000    );
4001    diagnostics.extend(new_diagnostics.into_iter().map(|(uri, diagnostics)| {
4002        (
4003            uri,
4004            WorkspaceLspPullDiagnostics {
4005                version: report.version.map(|v| v as i32),
4006                diagnostics,
4007            },
4008        )
4009    }));
4010}
4011
4012#[async_trait(?Send)]
4013impl LspCommand for GetDocumentDiagnostics {
4014    type Response = Vec<LspPullDiagnostics>;
4015    type LspRequest = lsp::request::DocumentDiagnosticRequest;
4016    type ProtoRequest = proto::GetDocumentDiagnostics;
4017
4018    fn display_name(&self) -> &str {
4019        "Get diagnostics"
4020    }
4021
4022    fn check_capabilities(&self, server_capabilities: AdapterServerCapabilities) -> bool {
4023        server_capabilities
4024            .server_capabilities
4025            .diagnostic_provider
4026            .is_some()
4027    }
4028
4029    fn to_lsp(
4030        &self,
4031        path: &Path,
4032        _: &Buffer,
4033        language_server: &Arc<LanguageServer>,
4034        _: &App,
4035    ) -> Result<lsp::DocumentDiagnosticParams> {
4036        let identifier = match language_server.capabilities().diagnostic_provider {
4037            Some(lsp::DiagnosticServerCapabilities::Options(options)) => options.identifier,
4038            Some(lsp::DiagnosticServerCapabilities::RegistrationOptions(options)) => {
4039                options.diagnostic_options.identifier
4040            }
4041            None => None,
4042        };
4043
4044        Ok(lsp::DocumentDiagnosticParams {
4045            text_document: lsp::TextDocumentIdentifier {
4046                uri: file_path_to_lsp_url(path)?,
4047            },
4048            identifier,
4049            previous_result_id: self.previous_result_id.clone(),
4050            partial_result_params: Default::default(),
4051            work_done_progress_params: Default::default(),
4052        })
4053    }
4054
4055    async fn response_from_lsp(
4056        self,
4057        message: lsp::DocumentDiagnosticReportResult,
4058        _: Entity<LspStore>,
4059        buffer: Entity<Buffer>,
4060        server_id: LanguageServerId,
4061        cx: AsyncApp,
4062    ) -> Result<Self::Response> {
4063        let url = buffer.read_with(&cx, |buffer, cx| {
4064            buffer
4065                .file()
4066                .and_then(|file| file.as_local())
4067                .map(|file| {
4068                    let abs_path = file.abs_path(cx);
4069                    file_path_to_lsp_url(&abs_path)
4070                })
4071                .transpose()?
4072                .with_context(|| format!("missing url on buffer {}", buffer.remote_id()))
4073        })??;
4074
4075        let mut pulled_diagnostics = HashMap::default();
4076        match message {
4077            lsp::DocumentDiagnosticReportResult::Report(report) => match report {
4078                lsp::DocumentDiagnosticReport::Full(report) => {
4079                    if let Some(related_documents) = report.related_documents {
4080                        process_related_documents(
4081                            &mut pulled_diagnostics,
4082                            server_id,
4083                            related_documents,
4084                        );
4085                    }
4086                    process_full_diagnostics_report(
4087                        &mut pulled_diagnostics,
4088                        server_id,
4089                        url,
4090                        report.full_document_diagnostic_report,
4091                    );
4092                }
4093                lsp::DocumentDiagnosticReport::Unchanged(report) => {
4094                    if let Some(related_documents) = report.related_documents {
4095                        process_related_documents(
4096                            &mut pulled_diagnostics,
4097                            server_id,
4098                            related_documents,
4099                        );
4100                    }
4101                    process_unchanged_diagnostics_report(
4102                        &mut pulled_diagnostics,
4103                        server_id,
4104                        url,
4105                        report.unchanged_document_diagnostic_report,
4106                    );
4107                }
4108            },
4109            lsp::DocumentDiagnosticReportResult::Partial(report) => {
4110                if let Some(related_documents) = report.related_documents {
4111                    process_related_documents(
4112                        &mut pulled_diagnostics,
4113                        server_id,
4114                        related_documents,
4115                    );
4116                }
4117            }
4118        }
4119
4120        Ok(pulled_diagnostics.into_values().collect())
4121    }
4122
4123    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> proto::GetDocumentDiagnostics {
4124        proto::GetDocumentDiagnostics {
4125            project_id,
4126            buffer_id: buffer.remote_id().into(),
4127            version: serialize_version(&buffer.version()),
4128        }
4129    }
4130
4131    async fn from_proto(
4132        _: proto::GetDocumentDiagnostics,
4133        _: Entity<LspStore>,
4134        _: Entity<Buffer>,
4135        _: AsyncApp,
4136    ) -> Result<Self> {
4137        anyhow::bail!(
4138            "proto::GetDocumentDiagnostics is not expected to be converted from proto directly, as it needs `previous_result_id` fetched first"
4139        )
4140    }
4141
4142    fn response_to_proto(
4143        response: Self::Response,
4144        _: &mut LspStore,
4145        _: PeerId,
4146        _: &clock::Global,
4147        _: &mut App,
4148    ) -> proto::GetDocumentDiagnosticsResponse {
4149        let pulled_diagnostics = response
4150            .into_iter()
4151            .filter_map(|diagnostics| match diagnostics {
4152                LspPullDiagnostics::Default => None,
4153                LspPullDiagnostics::Response {
4154                    server_id,
4155                    uri,
4156                    diagnostics,
4157                } => {
4158                    let mut changed = false;
4159                    let (diagnostics, result_id) = match diagnostics {
4160                        PulledDiagnostics::Unchanged { result_id } => (Vec::new(), Some(result_id)),
4161                        PulledDiagnostics::Changed {
4162                            result_id,
4163                            diagnostics,
4164                        } => {
4165                            changed = true;
4166                            (diagnostics, result_id)
4167                        }
4168                    };
4169                    Some(proto::PulledDiagnostics {
4170                        changed,
4171                        result_id,
4172                        uri: uri.to_string(),
4173                        server_id: server_id.to_proto(),
4174                        diagnostics: diagnostics
4175                            .into_iter()
4176                            .filter_map(|diagnostic| {
4177                                GetDocumentDiagnostics::serialize_lsp_diagnostic(diagnostic)
4178                                    .context("serializing diagnostics")
4179                                    .log_err()
4180                            })
4181                            .collect(),
4182                    })
4183                }
4184            })
4185            .collect();
4186
4187        proto::GetDocumentDiagnosticsResponse { pulled_diagnostics }
4188    }
4189
4190    async fn response_from_proto(
4191        self,
4192        response: proto::GetDocumentDiagnosticsResponse,
4193        _: Entity<LspStore>,
4194        _: Entity<Buffer>,
4195        _: AsyncApp,
4196    ) -> Result<Self::Response> {
4197        Ok(Self::diagnostics_from_proto(response))
4198    }
4199
4200    fn buffer_id_from_proto(message: &proto::GetDocumentDiagnostics) -> Result<BufferId> {
4201        BufferId::new(message.buffer_id)
4202    }
4203}
4204
4205#[async_trait(?Send)]
4206impl LspCommand for GetDocumentColor {
4207    type Response = Vec<DocumentColor>;
4208    type LspRequest = lsp::request::DocumentColor;
4209    type ProtoRequest = proto::GetDocumentColor;
4210
4211    fn display_name(&self) -> &str {
4212        "Document color"
4213    }
4214
4215    fn check_capabilities(&self, server_capabilities: AdapterServerCapabilities) -> bool {
4216        server_capabilities
4217            .server_capabilities
4218            .color_provider
4219            .is_some_and(|capability| match capability {
4220                lsp::ColorProviderCapability::Simple(supported) => supported,
4221                lsp::ColorProviderCapability::ColorProvider(..) => true,
4222                lsp::ColorProviderCapability::Options(..) => true,
4223            })
4224    }
4225
4226    fn to_lsp(
4227        &self,
4228        path: &Path,
4229        _: &Buffer,
4230        _: &Arc<LanguageServer>,
4231        _: &App,
4232    ) -> Result<lsp::DocumentColorParams> {
4233        Ok(lsp::DocumentColorParams {
4234            text_document: make_text_document_identifier(path)?,
4235            work_done_progress_params: Default::default(),
4236            partial_result_params: Default::default(),
4237        })
4238    }
4239
4240    async fn response_from_lsp(
4241        self,
4242        message: Vec<lsp::ColorInformation>,
4243        _: Entity<LspStore>,
4244        _: Entity<Buffer>,
4245        _: LanguageServerId,
4246        _: AsyncApp,
4247    ) -> Result<Self::Response> {
4248        Ok(message
4249            .into_iter()
4250            .map(|color| DocumentColor {
4251                lsp_range: color.range,
4252                color: color.color,
4253                resolved: false,
4254                color_presentations: Vec::new(),
4255            })
4256            .collect())
4257    }
4258
4259    fn to_proto(&self, project_id: u64, buffer: &Buffer) -> Self::ProtoRequest {
4260        proto::GetDocumentColor {
4261            project_id,
4262            buffer_id: buffer.remote_id().to_proto(),
4263            version: serialize_version(&buffer.version()),
4264        }
4265    }
4266
4267    async fn from_proto(
4268        _: Self::ProtoRequest,
4269        _: Entity<LspStore>,
4270        _: Entity<Buffer>,
4271        _: AsyncApp,
4272    ) -> Result<Self> {
4273        Ok(Self {})
4274    }
4275
4276    fn response_to_proto(
4277        response: Self::Response,
4278        _: &mut LspStore,
4279        _: PeerId,
4280        buffer_version: &clock::Global,
4281        _: &mut App,
4282    ) -> proto::GetDocumentColorResponse {
4283        proto::GetDocumentColorResponse {
4284            colors: response
4285                .into_iter()
4286                .map(|color| {
4287                    let start = point_from_lsp(color.lsp_range.start).0;
4288                    let end = point_from_lsp(color.lsp_range.end).0;
4289                    proto::ColorInformation {
4290                        red: color.color.red,
4291                        green: color.color.green,
4292                        blue: color.color.blue,
4293                        alpha: color.color.alpha,
4294                        lsp_range_start: Some(proto::PointUtf16 {
4295                            row: start.row,
4296                            column: start.column,
4297                        }),
4298                        lsp_range_end: Some(proto::PointUtf16 {
4299                            row: end.row,
4300                            column: end.column,
4301                        }),
4302                    }
4303                })
4304                .collect(),
4305            version: serialize_version(buffer_version),
4306        }
4307    }
4308
4309    async fn response_from_proto(
4310        self,
4311        message: proto::GetDocumentColorResponse,
4312        _: Entity<LspStore>,
4313        _: Entity<Buffer>,
4314        _: AsyncApp,
4315    ) -> Result<Self::Response> {
4316        Ok(message
4317            .colors
4318            .into_iter()
4319            .filter_map(|color| {
4320                let start = color.lsp_range_start?;
4321                let start = PointUtf16::new(start.row, start.column);
4322                let end = color.lsp_range_end?;
4323                let end = PointUtf16::new(end.row, end.column);
4324                Some(DocumentColor {
4325                    resolved: false,
4326                    color_presentations: Vec::new(),
4327                    lsp_range: lsp::Range {
4328                        start: point_to_lsp(start),
4329                        end: point_to_lsp(end),
4330                    },
4331                    color: lsp::Color {
4332                        red: color.red,
4333                        green: color.green,
4334                        blue: color.blue,
4335                        alpha: color.alpha,
4336                    },
4337                })
4338            })
4339            .collect())
4340    }
4341
4342    fn buffer_id_from_proto(message: &Self::ProtoRequest) -> Result<BufferId> {
4343        BufferId::new(message.buffer_id)
4344    }
4345}
4346
4347fn process_related_documents(
4348    diagnostics: &mut HashMap<lsp::Url, LspPullDiagnostics>,
4349    server_id: LanguageServerId,
4350    documents: impl IntoIterator<Item = (lsp::Url, lsp::DocumentDiagnosticReportKind)>,
4351) {
4352    for (url, report_kind) in documents {
4353        match report_kind {
4354            lsp::DocumentDiagnosticReportKind::Full(report) => {
4355                process_full_diagnostics_report(diagnostics, server_id, url, report)
4356            }
4357            lsp::DocumentDiagnosticReportKind::Unchanged(report) => {
4358                process_unchanged_diagnostics_report(diagnostics, server_id, url, report)
4359            }
4360        }
4361    }
4362}
4363
4364fn process_unchanged_diagnostics_report(
4365    diagnostics: &mut HashMap<lsp::Url, LspPullDiagnostics>,
4366    server_id: LanguageServerId,
4367    uri: lsp::Url,
4368    report: lsp::UnchangedDocumentDiagnosticReport,
4369) {
4370    let result_id = report.result_id;
4371    match diagnostics.entry(uri.clone()) {
4372        hash_map::Entry::Occupied(mut o) => match o.get_mut() {
4373            LspPullDiagnostics::Default => {
4374                o.insert(LspPullDiagnostics::Response {
4375                    server_id,
4376                    uri,
4377                    diagnostics: PulledDiagnostics::Unchanged { result_id },
4378                });
4379            }
4380            LspPullDiagnostics::Response {
4381                server_id: existing_server_id,
4382                uri: existing_uri,
4383                diagnostics: existing_diagnostics,
4384            } => {
4385                if server_id != *existing_server_id || &uri != existing_uri {
4386                    debug_panic!(
4387                        "Unexpected state: file {uri} has two different sets of diagnostics reported"
4388                    );
4389                }
4390                match existing_diagnostics {
4391                    PulledDiagnostics::Unchanged { .. } => {
4392                        *existing_diagnostics = PulledDiagnostics::Unchanged { result_id };
4393                    }
4394                    PulledDiagnostics::Changed { .. } => {}
4395                }
4396            }
4397        },
4398        hash_map::Entry::Vacant(v) => {
4399            v.insert(LspPullDiagnostics::Response {
4400                server_id,
4401                uri,
4402                diagnostics: PulledDiagnostics::Unchanged { result_id },
4403            });
4404        }
4405    }
4406}
4407
4408fn process_full_diagnostics_report(
4409    diagnostics: &mut HashMap<lsp::Url, LspPullDiagnostics>,
4410    server_id: LanguageServerId,
4411    uri: lsp::Url,
4412    report: lsp::FullDocumentDiagnosticReport,
4413) {
4414    let result_id = report.result_id;
4415    match diagnostics.entry(uri.clone()) {
4416        hash_map::Entry::Occupied(mut o) => match o.get_mut() {
4417            LspPullDiagnostics::Default => {
4418                o.insert(LspPullDiagnostics::Response {
4419                    server_id,
4420                    uri,
4421                    diagnostics: PulledDiagnostics::Changed {
4422                        result_id,
4423                        diagnostics: report.items,
4424                    },
4425                });
4426            }
4427            LspPullDiagnostics::Response {
4428                server_id: existing_server_id,
4429                uri: existing_uri,
4430                diagnostics: existing_diagnostics,
4431            } => {
4432                if server_id != *existing_server_id || &uri != existing_uri {
4433                    debug_panic!(
4434                        "Unexpected state: file {uri} has two different sets of diagnostics reported"
4435                    );
4436                }
4437                match existing_diagnostics {
4438                    PulledDiagnostics::Unchanged { .. } => {
4439                        *existing_diagnostics = PulledDiagnostics::Changed {
4440                            result_id,
4441                            diagnostics: report.items,
4442                        };
4443                    }
4444                    PulledDiagnostics::Changed {
4445                        result_id: existing_result_id,
4446                        diagnostics: existing_diagnostics,
4447                    } => {
4448                        if result_id.is_some() {
4449                            *existing_result_id = result_id;
4450                        }
4451                        existing_diagnostics.extend(report.items);
4452                    }
4453                }
4454            }
4455        },
4456        hash_map::Entry::Vacant(v) => {
4457            v.insert(LspPullDiagnostics::Response {
4458                server_id,
4459                uri,
4460                diagnostics: PulledDiagnostics::Changed {
4461                    result_id,
4462                    diagnostics: report.items,
4463                },
4464            });
4465        }
4466    }
4467}
4468
4469#[cfg(test)]
4470mod tests {
4471    use super::*;
4472    use lsp::{DiagnosticSeverity, DiagnosticTag};
4473    use serde_json::json;
4474
4475    #[test]
4476    fn test_serialize_lsp_diagnostic() {
4477        let lsp_diagnostic = lsp::Diagnostic {
4478            range: lsp::Range {
4479                start: lsp::Position::new(0, 1),
4480                end: lsp::Position::new(2, 3),
4481            },
4482            severity: Some(DiagnosticSeverity::ERROR),
4483            code: Some(lsp::NumberOrString::String("E001".to_string())),
4484            source: Some("test-source".to_string()),
4485            message: "Test error message".to_string(),
4486            related_information: None,
4487            tags: Some(vec![DiagnosticTag::DEPRECATED]),
4488            code_description: None,
4489            data: Some(json!({"detail": "test detail"})),
4490        };
4491
4492        let proto_diagnostic =
4493            GetDocumentDiagnostics::serialize_lsp_diagnostic(lsp_diagnostic.clone())
4494                .expect("Failed to serialize diagnostic");
4495
4496        let start = proto_diagnostic.start.unwrap();
4497        let end = proto_diagnostic.end.unwrap();
4498        assert_eq!(start.row, 0);
4499        assert_eq!(start.column, 1);
4500        assert_eq!(end.row, 2);
4501        assert_eq!(end.column, 3);
4502        assert_eq!(
4503            proto_diagnostic.severity,
4504            proto::lsp_diagnostic::Severity::Error as i32
4505        );
4506        assert_eq!(proto_diagnostic.code, Some("E001".to_string()));
4507        assert_eq!(proto_diagnostic.source, Some("test-source".to_string()));
4508        assert_eq!(proto_diagnostic.message, "Test error message");
4509    }
4510
4511    #[test]
4512    fn test_deserialize_lsp_diagnostic() {
4513        let proto_diagnostic = proto::LspDiagnostic {
4514            start: Some(proto::PointUtf16 { row: 0, column: 1 }),
4515            end: Some(proto::PointUtf16 { row: 2, column: 3 }),
4516            severity: proto::lsp_diagnostic::Severity::Warning as i32,
4517            code: Some("ERR".to_string()),
4518            source: Some("Prism".to_string()),
4519            message: "assigned but unused variable - a".to_string(),
4520            related_information: vec![],
4521            tags: vec![],
4522            code_description: None,
4523            data: None,
4524        };
4525
4526        let lsp_diagnostic = GetDocumentDiagnostics::deserialize_lsp_diagnostic(proto_diagnostic)
4527            .expect("Failed to deserialize diagnostic");
4528
4529        assert_eq!(lsp_diagnostic.range.start.line, 0);
4530        assert_eq!(lsp_diagnostic.range.start.character, 1);
4531        assert_eq!(lsp_diagnostic.range.end.line, 2);
4532        assert_eq!(lsp_diagnostic.range.end.character, 3);
4533        assert_eq!(lsp_diagnostic.severity, Some(DiagnosticSeverity::WARNING));
4534        assert_eq!(
4535            lsp_diagnostic.code,
4536            Some(lsp::NumberOrString::String("ERR".to_string()))
4537        );
4538        assert_eq!(lsp_diagnostic.source, Some("Prism".to_string()));
4539        assert_eq!(lsp_diagnostic.message, "assigned but unused variable - a");
4540    }
4541
4542    #[test]
4543    fn test_related_information() {
4544        let related_info = lsp::DiagnosticRelatedInformation {
4545            location: lsp::Location {
4546                uri: lsp::Url::parse("file:///test.rs").unwrap(),
4547                range: lsp::Range {
4548                    start: lsp::Position::new(1, 1),
4549                    end: lsp::Position::new(1, 5),
4550                },
4551            },
4552            message: "Related info message".to_string(),
4553        };
4554
4555        let lsp_diagnostic = lsp::Diagnostic {
4556            range: lsp::Range {
4557                start: lsp::Position::new(0, 0),
4558                end: lsp::Position::new(0, 1),
4559            },
4560            severity: Some(DiagnosticSeverity::INFORMATION),
4561            code: None,
4562            source: Some("Prism".to_string()),
4563            message: "assigned but unused variable - a".to_string(),
4564            related_information: Some(vec![related_info]),
4565            tags: None,
4566            code_description: None,
4567            data: None,
4568        };
4569
4570        let proto_diagnostic = GetDocumentDiagnostics::serialize_lsp_diagnostic(lsp_diagnostic)
4571            .expect("Failed to serialize diagnostic");
4572
4573        assert_eq!(proto_diagnostic.related_information.len(), 1);
4574        let related = &proto_diagnostic.related_information[0];
4575        assert_eq!(related.location_url, Some("file:///test.rs".to_string()));
4576        assert_eq!(related.message, "Related info message");
4577    }
4578
4579    #[test]
4580    fn test_invalid_ranges() {
4581        let proto_diagnostic = proto::LspDiagnostic {
4582            start: None,
4583            end: Some(proto::PointUtf16 { row: 2, column: 3 }),
4584            severity: proto::lsp_diagnostic::Severity::Error as i32,
4585            code: None,
4586            source: None,
4587            message: "Test message".to_string(),
4588            related_information: vec![],
4589            tags: vec![],
4590            code_description: None,
4591            data: None,
4592        };
4593
4594        let result = GetDocumentDiagnostics::deserialize_lsp_diagnostic(proto_diagnostic);
4595        assert!(result.is_err());
4596    }
4597}