Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

lsp: Filter out-of-bounds inlay hints (#64659)

HuaGu-Dragon532532bb804f
diff --git a/crates/collab/tests/integration/editor_tests.rs b/crates/collab/tests/integration/editor_tests.rs
index 737800833af..b759961e545 100644
--- a/crates/collab/tests/integration/editor_tests.rs
+++ b/crates/collab/tests/integration/editor_tests.rs
@@ -3315,6 +3315,18 @@ async fn test_inlay_hint_refresh_is_forwarded(
padding_right: None,
data: None,
},
+ lsp::InlayHint {
+ position: lsp::Position::new(1091, 1091),
+ label: lsp::InlayHintLabel::String(
+ "out-of-bounds parameter hint".to_string(),
+ ),
+ kind: Some(lsp::InlayHintKind::PARAMETER),
+ text_edits: None,
+ tooltip: None,
+ padding_left: None,
+ padding_right: None,
+ data: None,
+ },
]))
}
})
diff --git a/crates/editor/src/inlays/inlay_hints.rs b/crates/editor/src/inlays/inlay_hints.rs
index d206af52677..520e493e49f 100644
--- a/crates/editor/src/inlays/inlay_hints.rs
+++ b/crates/editor/src/inlays/inlay_hints.rs
@@ -1115,11 +1115,12 @@ pub mod tests {
use crate::inlays::inlay_hints::InlayHintRefreshReason;
use crate::scroll::Autoscroll;
use crate::scroll::ScrollAmount;
+ use crate::test::editor_lsp_test_context::EditorLspTestContext;
use crate::{Editor, SelectionEffects};
use collections::HashSet;
use futures::channel::oneshot;
use futures::{StreamExt, future};
- use gpui::{AppContext as _, Context, TestAppContext, WindowHandle};
+ use gpui::{AppContext as _, Context, TestAppContext, UpdateGlobal, WindowHandle};
use itertools::Itertools as _;
use language::language_settings::{InlayHintKind, InlayHintSettings};
use language::{Capability, FakeLspAdapter};
@@ -1131,7 +1132,9 @@ pub mod tests {
use pretty_assertions::assert_eq;
use project::{CodeAction, FakeFs, InlayId, InvalidationStrategy, LspAction, Project};
use serde_json::json;
- use settings::{AllLanguageSettingsContent, InlayHintSettingsContent, SettingsStore};
+ use settings::{
+ AllLanguageSettingsContent, InlayHintSettingsContent, SettingsContent, SettingsStore,
+ };
use std::ops::Range;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering};
@@ -5313,6 +5316,57 @@ let c = 3;"#
.unwrap();
}
+ #[gpui::test]
+ async fn test_inlay_hints_at_buffer_bounds(cx: &mut TestAppContext) {
+ let mut cx = EditorLspTestContext::new_rust(
+ lsp::ServerCapabilities {
+ inlay_hint_provider: Some(lsp::OneOf::Left(true)),
+ ..lsp::ServerCapabilities::default()
+ },
+ cx,
+ )
+ .await;
+
+ cx.update(|_, cx| {
+ SettingsStore::update_global(cx, |store, cx| {
+ store.update_user_settings(cx, &|settings: &mut SettingsContent| {
+ settings.project.all_languages.defaults.inlay_hints =
+ Some(InlayHintSettingsContent {
+ enabled: Some(true),
+ edit_debounce_ms: Some(0),
+ scroll_debounce_ms: Some(0),
+ ..InlayHintSettingsContent::default()
+ })
+ });
+ });
+ });
+
+ cx.set_state("ˇfoo\nbar");
+
+ cx.lsp
+ .set_request_handler::<lsp::request::InlayHintRequest, _, _>(|_, _| async move {
+ let hint = |line, character, kind, label: &str| lsp::InlayHint {
+ position: lsp::Position::new(line, character),
+ label: lsp::InlayHintLabel::String(label.to_string()),
+ kind: Some(kind),
+ text_edits: None,
+ tooltip: None,
+ padding_left: None,
+ padding_right: None,
+ data: None,
+ };
+ Ok(Some(vec![
+ hint(1090, 1090, lsp::InlayHintKind::PARAMETER, "row_overflow"),
+ hint(1090, 0, lsp::InlayHintKind::TYPE, "row_overflow"),
+ hint(0, 1090, lsp::InlayHintKind::PARAMETER, "clipped_column"),
+ hint(1, 3, lsp::InlayHintKind::TYPE, "buffer_end"),
+ ]))
+ });
+ cx.background_executor.run_until_parked();
+
+ cx.assert_display_state("ˇfooclipped_column\nbarbuffer_end");
+ }
+
pub(crate) fn init_test(cx: &mut TestAppContext, f: &dyn Fn(&mut AllLanguageSettingsContent)) {
cx.update(|cx| {
let settings_store = SettingsStore::test(cx);
diff --git a/crates/project/src/lsp_command.rs b/crates/project/src/lsp_command.rs
index eba7ab4861f..7bf3b78e771 100644
--- a/crates/project/src/lsp_command.rs
+++ b/crates/project/src/lsp_command.rs
@@ -13,7 +13,6 @@ use async_trait::async_trait;
use client::proto::{self, PeerId};
use clock::Global;
use collections::HashMap;
-use futures::future;
use gpui::{App, AsyncApp, Entity, SharedString, Task, TaskExt, prelude::FluentBuilder};
use language::{
Anchor, Bias, Buffer, BufferSnapshot, CachedLspAdapter, CharKind, CharScopeContext,
@@ -3887,38 +3886,34 @@ impl LspCommand for OnTypeFormatting {
}
impl InlayHints {
- pub async fn lsp_to_project_hint(
+ pub fn lsp_to_project_hint(
lsp_hint: lsp::InlayHint,
- buffer_handle: &Entity<Buffer>,
+ snapshot: &BufferSnapshot,
server_id: LanguageServerId,
resolve_state: ResolveState,
force_no_type_left_padding: bool,
- cx: &mut AsyncApp,
- ) -> anyhow::Result<InlayHint> {
+ ) -> InlayHint {
let kind = lsp_hint.kind.and_then(|kind| match kind {
lsp::InlayHintKind::TYPE => Some(InlayHintKind::Type),
lsp::InlayHintKind::PARAMETER => Some(InlayHintKind::Parameter),
_ => None,
});
- let position = buffer_handle.read_with(cx, |buffer, _| {
- let position = buffer.clip_point_utf16(point_from_lsp(lsp_hint.position), Bias::Left);
- if kind == Some(InlayHintKind::Parameter) {
- buffer.anchor_before(position)
- } else {
- buffer.anchor_after(position)
- }
- });
- let label = Self::lsp_inlay_label_to_project(lsp_hint.label, server_id)
- .await
- .context("lsp to project inlay hint conversion")?;
+ let position = snapshot.clip_point_utf16(point_from_lsp(lsp_hint.position), Bias::Left);
+ let position = if kind == Some(InlayHintKind::Parameter) {
+ snapshot.anchor_before(position)
+ } else {
+ snapshot.anchor_after(position)
+ };
+
+ let label = Self::lsp_inlay_label_to_project(lsp_hint.label, server_id);
let padding_left = if force_no_type_left_padding && kind == Some(InlayHintKind::Type) {
false
} else {
lsp_hint.padding_left.unwrap_or(false)
};
- Ok(InlayHint {
+ InlayHint {
position,
padding_left,
padding_right: lsp_hint.padding_right.unwrap_or(false),
@@ -3937,13 +3932,13 @@ impl InlayHints {
}
}),
resolve_state,
- })
+ }
}
- async fn lsp_inlay_label_to_project(
+ fn lsp_inlay_label_to_project(
lsp_label: lsp::InlayHintLabel,
server_id: LanguageServerId,
- ) -> anyhow::Result<InlayHintLabel> {
+ ) -> InlayHintLabel {
let label = match lsp_label {
lsp::InlayHintLabel::String(s) => InlayHintLabel::String(s),
lsp::InlayHintLabel::LabelParts(lsp_parts) => {
@@ -3973,7 +3968,7 @@ impl InlayHints {
}
};
- Ok(label)
+ label
}
pub fn project_to_proto_hint(response_hint: InlayHint) -> proto::InlayHint {
@@ -4351,31 +4346,30 @@ impl LspCommand for InlayHints {
)
});
- let hints = message.unwrap_or_default().into_iter().map(|lsp_hint| {
- let resolve_state = if can_resolve {
- ResolveState::CanResolve(lsp_server.server_id(), lsp_hint.data.clone())
- } else {
- ResolveState::Resolved
- };
+ let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
+ let last_row = snapshot.max_point().row;
+ let hints = message
+ .unwrap_or_default()
+ .into_iter()
+ .filter(|lsp_hint| lsp_hint.position.line <= last_row)
+ .map(|lsp_hint| {
+ let resolve_state = if can_resolve {
+ ResolveState::CanResolve(lsp_server.server_id(), lsp_hint.data.clone())
+ } else {
+ ResolveState::Resolved
+ };
- let buffer = buffer.clone();
- cx.spawn(async move |cx| {
InlayHints::lsp_to_project_hint(
lsp_hint,
- &buffer,
+ &snapshot,
server_id,
resolve_state,
force_no_type_left_padding,
- cx,
)
- .await
})
- });
- future::join_all(hints)
- .await
- .into_iter()
- .collect::<anyhow::Result<_>>()
- .context("lsp to project inlay hints conversion")
+ .collect();
+
+ Ok(hints)
}
fn to_proto(&self, project_id: u64, buffer: &Buffer) -> proto::InlayHints {
diff --git a/crates/project/src/lsp_store.rs b/crates/project/src/lsp_store.rs
index 912d3db6e1f..e53216805b5 100644
--- a/crates/project/src/lsp_store.rs
+++ b/crates/project/src/lsp_store.rs
@@ -8898,15 +8898,11 @@ impl LspStore {
None
}
})
- .map(|(server_id, mut new_hints)| {
- new_hints.retain(|hint| {
- hint.position.is_valid(&buffer_snapshot)
- && range.start.is_valid(&buffer_snapshot)
- && range.end.is_valid(&buffer_snapshot)
- && hint.position.cmp(&range.start, &buffer_snapshot).is_ge()
- && hint.position.cmp(&range.end, &buffer_snapshot).is_lt()
- });
- (server_id, new_hints)
+ .map(|(server_id, new_hints)| {
+ (
+ server_id,
+ inlay_hints::hints_in_range(new_hints, &range, &buffer_snapshot),
+ )
})
.collect::<HashMap<_, _>>();
anyhow::ensure!(
@@ -8928,15 +8924,11 @@ impl LspStore {
Ok(inlay_hints_task
.await
.into_iter()
- .map(|(server_id, mut new_hints)| {
- new_hints.retain(|hint| {
- hint.position.is_valid(&buffer_snapshot)
- && range.start.is_valid(&buffer_snapshot)
- && range.end.is_valid(&buffer_snapshot)
- && hint.position.cmp(&range.start, &buffer_snapshot).is_ge()
- && hint.position.cmp(&range.end, &buffer_snapshot).is_lt()
- });
- (server_id, new_hints)
+ .map(|(server_id, new_hints)| {
+ (
+ server_id,
+ inlay_hints::hints_in_range(new_hints, &range, &buffer_snapshot),
+ )
})
.collect())
})
diff --git a/crates/project/src/lsp_store/inlay_hints.rs b/crates/project/src/lsp_store/inlay_hints.rs
index 29800a21a5a..1439e34ac41 100644
--- a/crates/project/src/lsp_store/inlay_hints.rs
+++ b/crates/project/src/lsp_store/inlay_hints.rs
@@ -11,7 +11,7 @@ use language::{
use lsp::LanguageServerId;
use rpc::{TypedEnvelope, proto};
use settings::Settings as _;
-use text::{BufferId, Point};
+use text::{Anchor, BufferId, BufferSnapshot, Point, ToOffset as _};
use util::ResultExt as _;
use crate::{
@@ -22,6 +22,32 @@ use crate::{
pub type CacheInlayHints = HashMap<LanguageServerId, Vec<(InlayId, InlayHint)>>;
pub type CacheInlayHintsTask = Shared<Task<Result<CacheInlayHints, Arc<anyhow::Error>>>>;
+pub(super) fn hints_in_range(
+ mut hints: Vec<InlayHint>,
+ range: &Range<Anchor>,
+ snapshot: &BufferSnapshot,
+) -> Vec<InlayHint> {
+ if !range.start.is_valid(snapshot) || !range.end.is_valid(snapshot) {
+ return Vec::new();
+ }
+ let start = range.start.to_offset(snapshot);
+ let end = range.end.to_offset(snapshot);
+ let inclusive_end = end == snapshot.len();
+ hints.retain(|hint| {
+ if !hint.position.is_valid(snapshot) {
+ return false;
+ }
+ let offset = hint.position.to_offset(snapshot);
+ let before_end = if inclusive_end {
+ offset <= end
+ } else {
+ offset < end
+ };
+ offset >= start && before_end
+ });
+ hints
+}
+
/// A logic to apply when querying for new inlay hints and deciding what to do with the old entries in the cache in case of conflicts.
#[derive(Debug, Clone, Copy)]
pub enum InvalidationStrategy {
@@ -298,7 +324,7 @@ impl LspStore {
let request_timeout = ProjectSettings::get_global(cx)
.global_lsp_settings
.get_request_timeout();
- cx.spawn(async move |_, cx| {
+ cx.background_spawn(async move {
let resolve_task = lang_server.request::<lsp::request::InlayHintResolveRequest>(
InlayHints::project_to_lsp_hint(hint, &buffer_snapshot),
request_timeout,
@@ -307,16 +333,13 @@ impl LspStore {
.await
.into_response()
.context("inlay hint resolve LSP request")?;
- let resolved_hint = InlayHints::lsp_to_project_hint(
+ Ok(InlayHints::lsp_to_project_hint(
resolved_hint,
- &buffer,
+ &buffer_snapshot,
server_id,
ResolveState::Resolved,
false,
- cx,
- )
- .await?;
- Ok(resolved_hint)
+ ))
})
}
}