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