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