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.

project: Anchor diagnostic related information that points into the buffer (#62805)

Buyun Xu3624a5bfda8a
diff --git a/crates/collab/tests/integration/integration_tests.rs b/crates/collab/tests/integration/integration_tests.rs
index 165ffa94cfa..77e6872d01f 100644
--- a/crates/collab/tests/integration/integration_tests.rs
+++ b/crates/collab/tests/integration/integration_tests.rs
@@ -4395,9 +4395,9 @@ async fn test_collaborating_with_diagnostics(
.diagnostics_in_range::<_, Point>(0..buffer.len(), false)
.collect::<Vec<_>>(),
&[
- DiagnosticEntry {
- range: Point::new(0, 4)..Point::new(0, 7),
- diagnostic: Diagnostic {
+ DiagnosticEntry::new(
+ Point::new(0, 4)..Point::new(0, 7),
+ Diagnostic {
group_id: 2,
message: "message 1".to_string(),
severity: lsp::DiagnosticSeverity::ERROR,
@@ -4405,10 +4405,10 @@ async fn test_collaborating_with_diagnostics(
source_kind: DiagnosticSourceKind::Pushed,
..Diagnostic::default()
}
- },
- DiagnosticEntry {
- range: Point::new(0, 10)..Point::new(0, 13),
- diagnostic: Diagnostic {
+ ),
+ DiagnosticEntry::new(
+ Point::new(0, 10)..Point::new(0, 13),
+ Diagnostic {
group_id: 3,
severity: lsp::DiagnosticSeverity::WARNING,
message: "message 2".to_string(),
@@ -4416,7 +4416,7 @@ async fn test_collaborating_with_diagnostics(
source_kind: DiagnosticSourceKind::Pushed,
..Diagnostic::default()
}
- }
+ )
]
);
});
diff --git a/crates/edit_prediction/src/edit_prediction_tests.rs b/crates/edit_prediction/src/edit_prediction_tests.rs
index bdc268ea2d7..ba78459d30b 100644
--- a/crates/edit_prediction/src/edit_prediction_tests.rs
+++ b/crates/edit_prediction/src/edit_prediction_tests.rs
@@ -2280,13 +2280,11 @@ fn test_active_buffer_diagnostics_fetching(cx: &mut TestAppContext) {
buffer.update(cx, |buffer, cx| {
let snapshot = buffer.snapshot();
let diagnostics = DiagnosticSet::new(
- diagnostic_ranges
- .iter()
- .enumerate()
- .map(|(index, range)| DiagnosticEntry {
- range: snapshot.offset_to_point_utf16(range.start)
+ diagnostic_ranges.iter().enumerate().map(|(index, range)| {
+ DiagnosticEntry::new(
+ snapshot.offset_to_point_utf16(range.start)
..snapshot.offset_to_point_utf16(range.end),
- diagnostic: Diagnostic {
+ Diagnostic {
severity: match index {
0 => DiagnosticSeverity::WARNING,
1 => DiagnosticSeverity::ERROR,
@@ -2302,7 +2300,8 @@ fn test_active_buffer_diagnostics_fetching(cx: &mut TestAppContext) {
source_kind: language::DiagnosticSourceKind::Pushed,
..Diagnostic::default()
},
- }),
+ )
+ }),
&snapshot,
);
buffer.update_diagnostics(LanguageServerId(0), diagnostics, cx);
@@ -2371,9 +2370,9 @@ fn test_active_buffer_diagnostics_fetching(cx: &mut TestAppContext) {
let snapshot = buffer.snapshot();
let diagnostics = DiagnosticSet::new(
vec![
- DiagnosticEntry {
- range: text::PointUtf16::new(0, 0)..text::PointUtf16::new(0, 3),
- diagnostic: Diagnostic {
+ DiagnosticEntry::new(
+ text::PointUtf16::new(0, 0)..text::PointUtf16::new(0, 3),
+ Diagnostic {
severity: DiagnosticSeverity::ERROR,
message: "row zero".to_string(),
group_id: 1,
@@ -2381,10 +2380,10 @@ fn test_active_buffer_diagnostics_fetching(cx: &mut TestAppContext) {
source_kind: language::DiagnosticSourceKind::Pushed,
..Diagnostic::default()
},
- },
- DiagnosticEntry {
- range: text::PointUtf16::new(2, 0)..text::PointUtf16::new(2, 5),
- diagnostic: Diagnostic {
+ ),
+ DiagnosticEntry::new(
+ text::PointUtf16::new(2, 0)..text::PointUtf16::new(2, 5),
+ Diagnostic {
severity: DiagnosticSeverity::WARNING,
message: "row two".to_string(),
group_id: 2,
@@ -2392,10 +2391,10 @@ fn test_active_buffer_diagnostics_fetching(cx: &mut TestAppContext) {
source_kind: language::DiagnosticSourceKind::Pushed,
..Diagnostic::default()
},
- },
- DiagnosticEntry {
- range: text::PointUtf16::new(4, 0)..text::PointUtf16::new(4, 4),
- diagnostic: Diagnostic {
+ ),
+ DiagnosticEntry::new(
+ text::PointUtf16::new(4, 0)..text::PointUtf16::new(4, 4),
+ Diagnostic {
severity: DiagnosticSeverity::INFORMATION,
message: "row four".to_string(),
group_id: 3,
@@ -2403,7 +2402,7 @@ fn test_active_buffer_diagnostics_fetching(cx: &mut TestAppContext) {
source_kind: language::DiagnosticSourceKind::Pushed,
..Diagnostic::default()
},
- },
+ ),
],
&snapshot,
);
@@ -2456,16 +2455,18 @@ fn test_active_buffer_diagnostics_collection_limits(cx: &mut TestAppContext) {
let snapshot = buffer.snapshot();
let diagnostics = DiagnosticSet::new(
(0..25)
- .map(|row| DiagnosticEntry {
- range: text::PointUtf16::new(row, 0)..text::PointUtf16::new(row, 4),
- diagnostic: Diagnostic {
- severity: DiagnosticSeverity::ERROR,
- message: format!("row {row}"),
- group_id: row as usize,
- is_primary: true,
- source_kind: language::DiagnosticSourceKind::Pushed,
- ..Diagnostic::default()
- },
+ .map(|row| {
+ DiagnosticEntry::new(
+ text::PointUtf16::new(row, 0)..text::PointUtf16::new(row, 4),
+ Diagnostic {
+ severity: DiagnosticSeverity::ERROR,
+ message: format!("row {row}"),
+ group_id: row as usize,
+ is_primary: true,
+ source_kind: language::DiagnosticSourceKind::Pushed,
+ ..Diagnostic::default()
+ },
+ )
})
.collect::<Vec<_>>(),
&snapshot,
@@ -2498,9 +2499,9 @@ fn test_active_buffer_diagnostics_collection_limits(cx: &mut TestAppContext) {
buffer.update(cx, |buffer, cx| {
let snapshot = buffer.snapshot();
let diagnostics = DiagnosticSet::new(
- vec![DiagnosticEntry {
- range: text::PointUtf16::new(150, 0)..text::PointUtf16::new(150, 4),
- diagnostic: Diagnostic {
+ vec![DiagnosticEntry::new(
+ text::PointUtf16::new(150, 0)..text::PointUtf16::new(150, 4),
+ Diagnostic {
severity: DiagnosticSeverity::ERROR,
message: long_message.clone(),
group_id: 1,
@@ -2508,7 +2509,7 @@ fn test_active_buffer_diagnostics_collection_limits(cx: &mut TestAppContext) {
source_kind: language::DiagnosticSourceKind::Pushed,
..Diagnostic::default()
},
- }],
+ )],
&snapshot,
);
buffer.update_diagnostics(LanguageServerId(0), diagnostics, cx);
diff --git a/crates/editor/src/display_map.rs b/crates/editor/src/display_map.rs
index 21a44c28711..1d937ad0578 100644
--- a/crates/editor/src/display_map.rs
+++ b/crates/editor/src/display_map.rs
@@ -3470,15 +3470,15 @@ pub mod tests {
buffer.update_diagnostics(
LanguageServerId(0),
DiagnosticSet::new(
- [DiagnosticEntry {
- range: PointUtf16::new(0, 0)..PointUtf16::new(2, 1),
- diagnostic: Diagnostic {
+ [DiagnosticEntry::new(
+ PointUtf16::new(0, 0)..PointUtf16::new(2, 1),
+ Diagnostic {
severity: lsp::DiagnosticSeverity::ERROR,
group_id: 1,
message: "hi".into(),
..Default::default()
},
- }],
+ )],
buffer,
),
cx,
diff --git a/crates/editor/src/hover_popover.rs b/crates/editor/src/hover_popover.rs
index 861016c6fff..ae7bd9312b8 100644
--- a/crates/editor/src/hover_popover.rs
+++ b/crates/editor/src/hover_popover.rs
@@ -407,15 +407,15 @@ fn show_hover(
let subscription =
this.update(cx, |_, cx| cx.observe(&markdown, |_, _, cx| cx.notify()))?;
- let local_diagnostic = DiagnosticEntry {
- diagnostic: local_diagnostic.diagnostic.to_owned(),
- range: snapshot
+ let local_diagnostic = DiagnosticEntry::new(
+ snapshot
.buffer_snapshot()
.anchor_before(local_diagnostic.range.start)
..snapshot
.buffer_snapshot()
.anchor_after(local_diagnostic.range.end),
- };
+ local_diagnostic.diagnostic.to_owned(),
+ );
let scroll_handle = ScrollHandle::new();
diff --git a/crates/editor/src/semantic_tokens.rs b/crates/editor/src/semantic_tokens.rs
index b15ec323a34..34f955760da 100644
--- a/crates/editor/src/semantic_tokens.rs
+++ b/crates/editor/src/semantic_tokens.rs
@@ -2839,15 +2839,15 @@ mod tests {
buffer.update_diagnostics(
LanguageServerId(0),
DiagnosticSet::new(
- [DiagnosticEntry {
- range: PointUtf16::new(0, 3)..PointUtf16::new(0, 7),
- diagnostic: Diagnostic {
+ [DiagnosticEntry::new(
+ PointUtf16::new(0, 3)..PointUtf16::new(0, 7),
+ Diagnostic {
severity: lsp::DiagnosticSeverity::ERROR,
group_id: 1,
message: "unused function".into(),
..Default::default()
},
- }],
+ )],
buffer,
),
cx,
diff --git a/crates/inspector_ui/src/div_inspector.rs b/crates/inspector_ui/src/div_inspector.rs
index b78df2254e8..d80a15623c9 100644
--- a/crates/inspector_ui/src/div_inspector.rs
+++ b/crates/inspector_ui/src/div_inspector.rs
@@ -441,15 +441,17 @@ impl DivInspector {
let diagnostic_entries = unrecognized_ranges
.into_iter()
.enumerate()
- .map(|(ix, range)| DiagnosticEntry {
- range,
- diagnostic: Diagnostic {
- message: "unrecognized".to_string(),
- severity: DiagnosticSeverity::WARNING,
- is_primary: true,
- group_id: ix,
- ..Default::default()
- },
+ .map(|(ix, range)| {
+ DiagnosticEntry::new(
+ range,
+ Diagnostic {
+ message: "unrecognized".to_string(),
+ severity: DiagnosticSeverity::WARNING,
+ is_primary: true,
+ group_id: ix,
+ ..Default::default()
+ },
+ )
});
let diagnostics = DiagnosticSet::from_sorted_entries(diagnostic_entries, snapshot);
rust_style_buffer.update_diagnostics(LanguageServerId(0), diagnostics, cx);
diff --git a/crates/language/src/buffer.rs b/crates/language/src/buffer.rs
index 2f30033dae9..da493e400b6 100644
--- a/crates/language/src/buffer.rs
+++ b/crates/language/src/buffer.rs
@@ -5093,13 +5093,27 @@ impl BufferSnapshot {
where
T: 'a + Clone + ToOffset,
O: 'a + FromAnchor,
+ {
+ self.diagnostic_entries_in_range(search_range, reversed)
+ .map(|entry| entry.resolve(self))
+ }
+
+ /// Returns the stored entries that intersect the given range, with their ranges
+ /// and related information left in the buffer's own coordinates.
+ pub fn diagnostic_entries_in_range<'a, T>(
+ &'a self,
+ search_range: Range<T>,
+ reversed: bool,
+ ) -> impl 'a + Iterator<Item = &'a DiagnosticEntry<Anchor>>
+ where
+ T: 'a + Clone + ToOffset,
{
let mut iterators: Vec<_> = self
.diagnostics
.iter()
.map(|(_, collection)| {
collection
- .range::<T, text::Anchor>(search_range.clone(), self, true, reversed)
+ .entries_in_range::<T>(search_range.clone(), self, true, reversed)
.peekable()
})
.collect();
@@ -5120,15 +5134,7 @@ impl BufferSnapshot {
.then(a.diagnostic.group_id.cmp(&b.diagnostic.group_id));
if reversed { cmp.reverse() } else { cmp }
})?;
- iterators[next_ix]
- .next()
- .map(
- |DiagnosticEntryRef { range, diagnostic }| DiagnosticEntryRef {
- diagnostic,
- range: FromAnchor::from_anchor(&range.start, self)
- ..FromAnchor::from_anchor(&range.end, self),
- },
- )
+ iterators[next_ix].next()
})
}
diff --git a/crates/language/src/buffer_tests.rs b/crates/language/src/buffer_tests.rs
index 43162527088..26e856ac189 100644
--- a/crates/language/src/buffer_tests.rs
+++ b/crates/language/src/buffer_tests.rs
@@ -4112,13 +4112,13 @@ fn test_random_collaboration(cx: &mut App, mut rng: StdRng) {
let range = buffer.random_byte_range(0, &mut rng);
let range = range.to_point_utf16(buffer);
let range = range.start..range.end;
- DiagnosticEntry {
+ DiagnosticEntry::new(
range,
- diagnostic: Diagnostic {
+ Diagnostic {
message: post_inc(&mut next_diagnostic_id).to_string(),
..Default::default()
},
- }
+ )
}),
buffer,
);
diff --git a/crates/language/src/diagnostic.rs b/crates/language/src/diagnostic.rs
index 010039760aa..236d4cc7294 100644
--- a/crates/language/src/diagnostic.rs
+++ b/crates/language/src/diagnostic.rs
@@ -1,8 +1,8 @@
use gpui::SharedString;
-use lsp::{DiagnosticRelatedInformation, DiagnosticSeverity, NumberOrString};
+use lsp::{DiagnosticSeverity, NumberOrString};
use serde::{Deserialize, Serialize};
use serde_json::Value;
-use std::sync::Arc;
+use std::ops::Range;
/// A diagnostic associated with a certain range of a buffer.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
@@ -46,10 +46,47 @@ pub struct Diagnostic {
pub data: Option<Value>,
/// Whether to underline the corresponding text range in the editor.
pub underline: bool,
- /// Related information from the language server that produced this diagnostic. Passed back to the LS when we request code actions for this diagnostic.
- ///
- /// Kept as sent, since flattening it into non-primary entries is lossy.
- pub related_information: Option<Arc<[DiagnosticRelatedInformation]>>,
+}
+
+/// A location and message the language server attached to a diagnostic.
+///
+/// Kept as the server sent it, since flattening it into non-primary entries is lossy,
+/// and passed back to the LS when we request code actions for the diagnostic.
+#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
+pub struct RelatedInformation<T> {
+ /// The location the diagnostic points at.
+ pub location: RelatedLocation<T>,
+ /// The message as the language server sent it.
+ pub message: String,
+}
+
+/// Where a [`RelatedInformation`] points.
+#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
+pub enum RelatedLocation<T> {
+ /// A range of the buffer the diagnostic belongs to, in the same coordinates as the
+ /// diagnostic's own range, so that it follows edits the same way.
+ InBuffer(Range<T>),
+ /// A location in another file, as the language server published it. There is
+ /// nothing in this buffer to anchor it to.
+ InAnotherFile(lsp::Location),
+}
+
+impl<T: Clone> RelatedInformation<T> {
+ /// Converts the coordinates of this related information to a different type.
+ pub(crate) fn map_location<O>(
+ &self,
+ map: impl FnOnce(&Range<T>) -> Range<O>,
+ ) -> RelatedInformation<O> {
+ RelatedInformation {
+ location: match &self.location {
+ RelatedLocation::InBuffer(range) => RelatedLocation::InBuffer(map(range)),
+ RelatedLocation::InAnotherFile(location) => {
+ RelatedLocation::InAnotherFile(location.clone())
+ }
+ },
+ message: self.message.clone(),
+ }
+ }
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
@@ -76,7 +113,6 @@ impl Default for Diagnostic {
underline: true,
data: None,
registration_id: None,
- related_information: None,
}
}
}
diff --git a/crates/language/src/diagnostic_set.rs b/crates/language/src/diagnostic_set.rs
index 42e764f07ab..04618fb1a43 100644
--- a/crates/language/src/diagnostic_set.rs
+++ b/crates/language/src/diagnostic_set.rs
@@ -1,4 +1,4 @@
-use crate::{Diagnostic, range_to_lsp};
+use crate::{Diagnostic, RelatedInformation, RelatedLocation, range_to_lsp};
use anyhow::Result;
use collections::HashMap;
use lsp::LanguageServerId;
@@ -7,6 +7,7 @@ use std::{
cmp::{Ordering, Reverse},
iter,
ops::Range,
+ sync::Arc,
};
use sum_tree::{self, Bias, SumTree};
use text::{Anchor, FromAnchor, PointUtf16, ToOffset};
@@ -32,6 +33,40 @@ pub struct DiagnosticEntry<T> {
pub range: Range<T>,
/// The information about the diagnostic.
pub diagnostic: Diagnostic,
+ /// The related information the language server attached to the diagnostic. Its
+ /// locations are in the same coordinates as `range`, so that they are converted
+ /// and followed the same way.
+ pub related_information: Option<Arc<[RelatedInformation<T>]>>,
+}
+
+impl<T> DiagnosticEntry<T> {
+ pub fn new(range: Range<T>, diagnostic: Diagnostic) -> Self {
+ Self {
+ range,
+ diagnostic,
+ related_information: None,
+ }
+ }
+}
+
+impl<T: Clone> DiagnosticEntry<T> {
+ /// Converts the entry to a different buffer coordinate type, taking the related
+ /// information with it so that its locations stay in the same space as the range.
+ pub fn map_coordinates<O>(
+ self,
+ mut map: impl FnMut(&Range<T>) -> Range<O>,
+ ) -> DiagnosticEntry<O> {
+ DiagnosticEntry {
+ range: map(&self.range),
+ related_information: self.related_information.as_ref().map(|information| {
+ information
+ .iter()
+ .map(|information| information.map_location(&mut map))
+ .collect()
+ }),
+ diagnostic: self.diagnostic,
+ }
+ }
}
/// A single diagnostic in a set. Generic over its range type, because
@@ -59,11 +94,10 @@ impl<T: PartialEq> PartialEq<DiagnosticEntryRef<'_, T>> for DiagnosticEntry<T> {
}
impl<T: Clone> DiagnosticEntryRef<'_, T> {
+ /// The related information is not part of a reference, so the entry is returned
+ /// without it.
pub fn to_owned(&self) -> DiagnosticEntry<T> {
- DiagnosticEntry {
- range: self.range.clone(),
- diagnostic: self.diagnostic.clone(),
- }
+ DiagnosticEntry::new(self.range.clone(), self.diagnostic.clone())
}
}
@@ -116,21 +150,29 @@ pub struct Summary {
impl DiagnosticEntry<PointUtf16> {
/// Returns a raw LSP diagnostic used to provide diagnostic context to LSP
- /// codeAction request
- pub fn to_lsp_diagnostic_stub(&self) -> Result<lsp::Diagnostic> {
- DiagnosticEntryRef {
- range: self.range.clone(),
- diagnostic: &self.diagnostic,
- }
- .to_lsp_diagnostic_stub()
- }
-}
-impl DiagnosticEntryRef<'_, PointUtf16> {
- /// Returns a raw LSP diagnostic used to provide diagnostic context to LSP
- /// codeAction request
- pub fn to_lsp_diagnostic_stub(&self) -> Result<lsp::Diagnostic> {
+ /// codeAction request. `uri` names the file this entry belongs to, which the
+ /// related information of that same file is reported against.
+ pub fn to_lsp_diagnostic_stub(&self, uri: &lsp::Uri) -> Result<lsp::Diagnostic> {
let range = range_to_lsp(self.range.clone())?;
+ let mut related_information = None;
+ if let Some(information) = &self.related_information {
+ let mut locations = Vec::with_capacity(information.len());
+ for information in information.iter() {
+ locations.push(lsp::DiagnosticRelatedInformation {
+ location: match &information.location {
+ RelatedLocation::InBuffer(range) => lsp::Location {
+ uri: uri.clone(),
+ range: range_to_lsp(range.clone())?,
+ },
+ RelatedLocation::InAnotherFile(location) => location.clone(),
+ },
+ message: information.message.clone(),
+ });
+ }
+ related_information = Some(locations);
+ }
+
Ok(lsp::Diagnostic {
range,
code: self.diagnostic.code.clone(),
@@ -138,11 +180,7 @@ impl DiagnosticEntryRef<'_, PointUtf16> {
source: self.diagnostic.source.clone(),
message: self.diagnostic.message.clone(),
data: self.diagnostic.data.clone(),
- related_information: self
- .diagnostic
- .related_information
- .as_ref()
- .map(|related_information| related_information.to_vec()),
+ related_information,
..Default::default()
})
}
@@ -169,10 +207,10 @@ impl DiagnosticSet {
entries.sort_unstable_by_key(|entry| (entry.range.start, Reverse(entry.range.end)));
Self {
diagnostics: SumTree::from_iter(
- entries.into_iter().map(|entry| DiagnosticEntry {
- range: buffer.anchor_before(entry.range.start)
- ..buffer.anchor_before(entry.range.end),
- diagnostic: entry.diagnostic,
+ entries.into_iter().map(|entry| {
+ entry.map_coordinates(|range| {
+ buffer.anchor_before(range.start)..buffer.anchor_before(range.end)
+ })
}),
buffer,
),
@@ -205,6 +243,22 @@ impl DiagnosticSet {
where
T: 'a + ToOffset,
O: FromAnchor,
+ {
+ self.entries_in_range(range, buffer, inclusive, reversed)
+ .map(|entry| entry.resolve(buffer))
+ }
+
+ /// Returns an iterator over the stored entries that intersect the given range of
+ /// the buffer, with their ranges left in the buffer's own coordinates.
+ pub fn entries_in_range<'a, T>(
+ &'a self,
+ range: Range<T>,
+ buffer: &'a text::BufferSnapshot,
+ inclusive: bool,
+ reversed: bool,
+ ) -> impl 'a + Iterator<Item = &'a DiagnosticEntry<Anchor>>
+ where
+ T: 'a + ToOffset,
{
let end_bias = if inclusive { Bias::Right } else { Bias::Left };
let range = buffer.anchor_before(range.start)..buffer.anchor_at(range.end, end_bias);
@@ -227,16 +281,13 @@ impl DiagnosticSet {
}
iter::from_fn({
move || {
- if let Some(diagnostic) = cursor.item() {
- if reversed {
- cursor.prev();
- } else {
- cursor.next();
- }
- Some(diagnostic.resolve(buffer))
+ let entry = cursor.item()?;
+ if reversed {
+ cursor.prev();
} else {
- None
+ cursor.next();
}
+ Some(entry)
}
})
}
diff --git a/crates/language/src/language.rs b/crates/language/src/language.rs
index bf794425e2a..ea41bd6f0cf 100644
--- a/crates/language/src/language.rs
+++ b/crates/language/src/language.rs
@@ -100,7 +100,7 @@ use util::rel_path::RelPath;
pub use available_languages::AvailableLanguage;
pub use buffer::Operation;
pub use buffer::*;
-pub use diagnostic::{Diagnostic, DiagnosticSourceKind};
+pub use diagnostic::{Diagnostic, DiagnosticSourceKind, RelatedInformation, RelatedLocation};
pub use diagnostic_set::{DiagnosticEntry, DiagnosticEntryRef, DiagnosticGroup};
pub use file_content::{
ByteContent, DecodedText, FILE_ANALYSIS_BYTES, analyze_byte_content, decode_text, encode_text,
diff --git a/crates/language/src/proto.rs b/crates/language/src/proto.rs
index 4e5731d23e4..1bc19f42325 100644
--- a/crates/language/src/proto.rs
+++ b/crates/language/src/proto.rs
@@ -442,9 +442,9 @@ pub fn deserialize_diagnostics(
} else {
None
};
- Some(DiagnosticEntry {
- range: deserialize_anchor(diagnostic.start?)?..deserialize_anchor(diagnostic.end?)?,
- diagnostic: Diagnostic {
+ Some(DiagnosticEntry::new(
+ deserialize_anchor(diagnostic.start?)?..deserialize_anchor(diagnostic.end?)?,
+ Diagnostic {
source: diagnostic.source,
severity: match proto::diagnostic::Severity::from_i32(diagnostic.severity)? {
proto::diagnostic::Severity::Error => DiagnosticSeverity::ERROR,
@@ -473,10 +473,8 @@ pub fn deserialize_diagnostics(
proto::diagnostic::SourceKind::Other => DiagnosticSourceKind::Other,
},
data,
- // Not serialized: only the peer talking to the language server sends these back.
- related_information: None,
},
- })
+ ))
})
.collect()
}
diff --git a/crates/project/src/lsp_command.rs b/crates/project/src/lsp_command.rs
index db7c3a0ab10..ec0c8777b53 100644
--- a/crates/project/src/lsp_command.rs
+++ b/crates/project/src/lsp_command.rs
@@ -2949,12 +2949,14 @@ impl LspCommand for GetCodeActions {
language_server: &Arc<LanguageServer>,
_: &App,
) -> Result<lsp::CodeActionParams> {
+ let text_document = make_text_document_identifier(path)?;
+ let snapshot = buffer.snapshot();
let mut relevant_diagnostics = Vec::new();
- for entry in buffer
- .snapshot()
- .diagnostics_in_range::<_, language::PointUtf16>(self.range.clone(), false)
- {
- relevant_diagnostics.push(entry.to_lsp_diagnostic_stub()?);
+ for entry in snapshot.diagnostic_entries_in_range(self.range.clone(), false) {
+ let entry = entry.clone().map_coordinates(|range| {
+ range.start.to_point_utf16(&snapshot)..range.end.to_point_utf16(&snapshot)
+ });
+ relevant_diagnostics.push(entry.to_lsp_diagnostic_stub(&text_document.uri)?);
}
let only = if let Some(requested) = &self.kinds {
diff --git a/crates/project/src/lsp_store.rs b/crates/project/src/lsp_store.rs
index cb23d01fb68..74074f6a54c 100644
--- a/crates/project/src/lsp_store.rs
+++ b/crates/project/src/lsp_store.rs
@@ -79,8 +79,8 @@ use language::{
CodeLabelExt, Diagnostic, DiagnosticEntry, DiagnosticSet, DiagnosticSourceKind, Diff,
File as _, Language, LanguageAwareStyling, LanguageName, LanguageRegistry, LocalFile,
LspAdapter, LspAdapterDelegate, LspInstaller, ManifestDelegate, ManifestName, ModelineSettings,
- OffsetUtf16, Patch, PointUtf16, TextBufferSnapshot, ToOffset, ToOffsetUtf16, ToPointUtf16,
- Toolchain, Transaction, Unclipped,
+ OffsetUtf16, Patch, PointUtf16, RelatedInformation, RelatedLocation, TextBufferSnapshot,
+ ToOffset, ToOffsetUtf16, ToPointUtf16, Toolchain, Transaction, Unclipped,
language_settings::{
AllLanguageSettings, FormatOnSave, Formatter, LanguageSettings, LineEndingSetting,
all_language_settings,
@@ -2798,39 +2798,38 @@ impl LocalLspStore {
let mut sanitized_diagnostics = Vec::with_capacity(diagnostics.len());
for (new_diagnostic, entry) in diagnostics {
- let start;
- let end;
- if new_diagnostic && entry.diagnostic.is_disk_based {
- // Some diagnostics are based on files on disk instead of buffers'
- // current contents. Adjust these diagnostics' ranges to reflect
- // any unsaved edits.
- // Do not alter the reused ones though, as their coordinates were stored as anchors
- // and were properly adjusted on reuse.
- start = Unclipped((*edits_since_save).old_to_new(entry.range.start.0));
- end = Unclipped((*edits_since_save).old_to_new(entry.range.end.0));
- } else {
- start = entry.range.start;
- end = entry.range.end;
- }
-
- let mut range = snapshot.clip_point_utf16(start, Bias::Left)
- ..snapshot.clip_point_utf16(end, Bias::Right);
+ // Some diagnostics are based on files on disk instead of buffers'
+ // current contents. Adjust these diagnostics' ranges to reflect
+ // any unsaved edits.
+ // Do not alter the reused ones though, as their coordinates were stored as anchors
+ // and were properly adjusted on reuse.
+ let is_disk_based = new_diagnostic && entry.diagnostic.is_disk_based;
+ let mut entry = entry.map_coordinates(|range| {
+ let range = if is_disk_based {
+ Unclipped((*edits_since_save).old_to_new(range.start.0))
+ ..Unclipped((*edits_since_save).old_to_new(range.end.0))
+ } else {
+ range.clone()
+ };
+ snapshot.clip_point_utf16(range.start, Bias::Left)
+ ..snapshot.clip_point_utf16(range.end, Bias::Right)
+ });
- // Expand empty ranges by one codepoint
- if range.start == range.end {
+ // Expand empty ranges by one codepoint. Only the diagnostic's own range is
+ // widened: the related locations are reported back as the server framed them.
+ if entry.range.start == entry.range.end {
// This will be go to the next boundary when being clipped
- range.end.column += 1;
- range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Right);
- if range.start == range.end && range.end.column > 0 {
- range.start.column -= 1;
- range.start = snapshot.clip_point_utf16(Unclipped(range.start), Bias::Left);
+ entry.range.end.column += 1;
+ entry.range.end =
+ snapshot.clip_point_utf16(Unclipped(entry.range.end), Bias::Right);
+ if entry.range.start == entry.range.end && entry.range.end.column > 0 {
+ entry.range.start.column -= 1;
+ entry.range.start =
+ snapshot.clip_point_utf16(Unclipped(entry.range.start), Bias::Left);
}
}
- sanitized_diagnostics.push(DiagnosticEntry {
- range,
- diagnostic: entry.diagnostic,
- });
+ sanitized_diagnostics.push(entry);
}
drop(edits_since_save);
@@ -9172,12 +9171,10 @@ impl LspStore {
.iter()
.filter(|v| merge(&document_uri, &v.diagnostic, cx))
.map(|v| {
- let start = Unclipped(v.range.start.to_point_utf16(&snapshot));
- let end = Unclipped(v.range.end.to_point_utf16(&snapshot));
- DiagnosticEntry {
- range: start..end,
- diagnostic: v.diagnostic.clone(),
- }
+ (*v).clone().map_coordinates(|range| {
+ Unclipped(range.start.to_point_utf16(&snapshot))
+ ..Unclipped(range.end.to_point_utf16(&snapshot))
+ })
})
.collect::<Vec<_>>();
@@ -12191,10 +12188,7 @@ impl LspStore {
(
diagnostic.severity,
is_unnecessary,
- diagnostic
- .related_information
- .as_ref()
- .map(|infos| Arc::from(infos.as_slice())),
+ related_information_from_lsp(diagnostic, &lsp_diagnostics.uri),
),
);
} else {
@@ -12208,6 +12202,10 @@ impl LspStore {
diagnostics.push(DiagnosticEntry {
range,
+ related_information: related_information_from_lsp(
+ diagnostic,
+ &lsp_diagnostics.uri,
+ ),
diagnostic: Diagnostic {
source: diagnostic.source.clone(),
source_kind,
@@ -12228,10 +12226,6 @@ impl LspStore {
underline,
data: diagnostic.data.clone(),
registration_id: registration_id.clone(),
- related_information: diagnostic
- .related_information
- .as_ref()
- .map(|infos| Arc::from(infos.as_slice())),
},
});
if let Some(infos) = &diagnostic.related_information {
@@ -12240,6 +12234,7 @@ impl LspStore {
let range = range_from_lsp(info.location.range);
diagnostics.push(DiagnosticEntry {
range,
+ related_information: None,
diagnostic: Diagnostic {
source: diagnostic.source.clone(),
source_kind,
@@ -12260,7 +12255,6 @@ impl LspStore {
underline,
data: diagnostic.data.clone(),
registration_id: registration_id.clone(),
- related_information: None,
},
});
}
@@ -12270,21 +12264,20 @@ impl LspStore {
}
for entry in &mut diagnostics {
- let diagnostic = &mut entry.diagnostic;
- if !diagnostic.is_primary {
- let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
+ if !entry.diagnostic.is_primary {
+ let source = *sources_by_group_id.get(&entry.diagnostic.group_id).unwrap();
if let Some((severity, is_unnecessary, related_information)) =
supporting_diagnostics.get(&(
source,
- diagnostic.code.clone(),
+ entry.diagnostic.code.clone(),
entry.range.clone(),
))
{
if let Some(severity) = severity {
- diagnostic.severity = *severity;
+ entry.diagnostic.severity = *severity;
}
- diagnostic.is_unnecessary = *is_unnecessary;
- diagnostic.related_information = related_information.clone();
+ entry.diagnostic.is_unnecessary = *is_unnecessary;
+ entry.related_information = related_information.clone();
}
}
}
@@ -14987,6 +14980,32 @@ pub(crate) fn collapse_newlines(text: &str, separator: &str) -> String {
.join(separator)
}
+/// Converts the related information of a published diagnostic, putting the locations
+/// of the document it was published for into that document's coordinates so that they
+/// are converted and followed like the diagnostic's own range.
+fn related_information_from_lsp(
+ diagnostic: &lsp::Diagnostic,
+ document_uri: &lsp::Uri,
+) -> Option<Arc<[RelatedInformation<Unclipped<PointUtf16>>]>> {
+ let infos = diagnostic.related_information.as_ref()?;
+ if infos.is_empty() {
+ return None;
+ }
+ Some(
+ infos
+ .iter()
+ .map(|info| RelatedInformation {
+ location: if &info.location.uri == document_uri {
+ RelatedLocation::InBuffer(range_from_lsp(info.location.range))
+ } else {
+ RelatedLocation::InAnotherFile(info.location.clone())
+ },
+ message: info.message.clone(),
+ })
+ .collect(),
+ )
+}
+
fn include_text(server: &lsp::LanguageServer) -> Option<bool> {
match server.capabilities().text_document_sync.as_ref()? {
lsp::TextDocumentSyncCapability::Options(opts) => match opts.save.as_ref()? {
diff --git a/crates/project/tests/integration/project_tests.rs b/crates/project/tests/integration/project_tests.rs
index 9f9ebeef876..2c744ef4a9c 100644
--- a/crates/project/tests/integration/project_tests.rs
+++ b/crates/project/tests/integration/project_tests.rs
@@ -1830,10 +1830,10 @@ async fn test_managing_language_servers(cx: &mut gpui::TestAppContext) {
buffer.update_diagnostics(
LanguageServerId(0),
DiagnosticSet::from_sorted_entries(
- vec![DiagnosticEntry {
- diagnostic: Default::default(),
- range: Anchor::min_max_range_for_buffer(buffer.remote_id()),
- }],
+ vec![DiagnosticEntry::new(
+ Anchor::min_max_range_for_buffer(buffer.remote_id()),
+ Default::default(),
+ )],
&buffer.snapshot(),
),
cx,
@@ -3666,9 +3666,9 @@ async fn test_transforming_diagnostics(cx: &mut gpui::TestAppContext) {
.diagnostics_in_range::<_, Point>(Point::new(3, 0)..Point::new(5, 0), false)
.collect::<Vec<_>>(),
&[
- DiagnosticEntry {
- range: Point::new(3, 9)..Point::new(3, 11),
- diagnostic: Diagnostic {
+ DiagnosticEntry::new(
+ Point::new(3, 9)..Point::new(3, 11),
+ Diagnostic {
source: Some("disk".into()),
severity: DiagnosticSeverity::ERROR,
message: "undefined variable 'BB'".to_string(),
@@ -3677,11 +3677,11 @@ async fn test_transforming_diagnostics(cx: &mut gpui::TestAppContext) {
is_primary: true,
source_kind: DiagnosticSourceKind::Pushed,
..Diagnostic::default()
- },
- },
- DiagnosticEntry {
- range: Point::new(4, 9)..Point::new(4, 12),
- diagnostic: Diagnostic {
+ }
+ ),
+ DiagnosticEntry::new(
+ Point::new(4, 9)..Point::new(4, 12),
+ Diagnostic {
source: Some("disk".into()),
severity: DiagnosticSeverity::ERROR,
message: "undefined variable 'CCC'".to_string(),
@@ -3691,7 +3691,7 @@ async fn test_transforming_diagnostics(cx: &mut gpui::TestAppContext) {
source_kind: DiagnosticSourceKind::Pushed,
..Diagnostic::default()
}
- }
+ )
]
);
assert_eq!(
@@ -3746,9 +3746,9 @@ async fn test_transforming_diagnostics(cx: &mut gpui::TestAppContext) {
.diagnostics_in_range::<_, Point>(Point::new(2, 0)..Point::new(3, 0), false)
.collect::<Vec<_>>(),
&[
- DiagnosticEntry {
- range: Point::new(2, 9)..Point::new(2, 12),
- diagnostic: Diagnostic {
+ DiagnosticEntry::new(
+ Point::new(2, 9)..Point::new(2, 12),
+ Diagnostic {
source: Some("disk".into()),
severity: DiagnosticSeverity::WARNING,
message: "unreachable statement".to_string(),
@@ -3758,10 +3758,10 @@ async fn test_transforming_diagnostics(cx: &mut gpui::TestAppContext) {
source_kind: DiagnosticSourceKind::Pushed,
..Diagnostic::default()
}
- },
- DiagnosticEntry {
- range: Point::new(2, 9)..Point::new(2, 10),
- diagnostic: Diagnostic {
+ ),
+ DiagnosticEntry::new(
+ Point::new(2, 9)..Point::new(2, 10),
+ Diagnostic {
source: Some("disk".into()),
severity: DiagnosticSeverity::ERROR,
message: "undefined variable 'A'".to_string(),
@@ -3770,8 +3770,8 @@ async fn test_transforming_diagnostics(cx: &mut gpui::TestAppContext) {
is_primary: true,
source_kind: DiagnosticSourceKind::Pushed,
..Diagnostic::default()
- },
- }
+ }
+ )
]
);
assert_eq!(
@@ -3840,9 +3840,9 @@ async fn test_transforming_diagnostics(cx: &mut gpui::TestAppContext) {
.diagnostics_in_range::<_, Point>(0..buffer.len(), false)
.collect::<Vec<_>>(),
&[
- DiagnosticEntry {
- range: Point::new(2, 21)..Point::new(2, 22),
- diagnostic: Diagnostic {
+ DiagnosticEntry::new(
+ Point::new(2, 21)..Point::new(2, 22),
+ Diagnostic {
source: Some("disk".into()),
severity: DiagnosticSeverity::WARNING,
message: "undefined variable 'A'".to_string(),
@@ -3852,10 +3852,10 @@ async fn test_transforming_diagnostics(cx: &mut gpui::TestAppContext) {
source_kind: DiagnosticSourceKind::Pushed,
..Diagnostic::default()
}
- },
- DiagnosticEntry {
- range: Point::new(3, 9)..Point::new(3, 14),
- diagnostic: Diagnostic {
+ ),
+ DiagnosticEntry::new(
+ Point::new(3, 9)..Point::new(3, 14),
+ Diagnostic {
source: Some("disk".into()),
severity: DiagnosticSeverity::ERROR,
message: "undefined variable 'BB'".to_string(),
@@ -3864,8 +3864,8 @@ async fn test_transforming_diagnostics(cx: &mut gpui::TestAppContext) {
is_primary: true,
source_kind: DiagnosticSourceKind::Pushed,
..Diagnostic::default()
- },
- }
+ }
+ )
]
);
});
@@ -3901,26 +3901,24 @@ async fn test_empty_diagnostic_ranges(cx: &mut gpui::TestAppContext) {
None,
None,
vec![
- DiagnosticEntry {
- range: Unclipped(PointUtf16::new(0, 10))
- ..Unclipped(PointUtf16::new(0, 10)),
- diagnostic: Diagnostic {
+ DiagnosticEntry::new(
+ Unclipped(PointUtf16::new(0, 10))..Unclipped(PointUtf16::new(0, 10)),
+ Diagnostic {
severity: DiagnosticSeverity::ERROR,
message: "syntax error 1".to_string(),
source_kind: DiagnosticSourceKind::Pushed,
..Diagnostic::default()
},
- },
- DiagnosticEntry {
- range: Unclipped(PointUtf16::new(1, 10))
- ..Unclipped(PointUtf16::new(1, 10)),
- diagnostic: Diagnostic {
+ ),
+ DiagnosticEntry::new(
+ Unclipped(PointUtf16::new(1, 10))..Unclipped(PointUtf16::new(1, 10)),
+ Diagnostic {
severity: DiagnosticSeverity::ERROR,
message: "syntax error 2".to_string(),
source_kind: DiagnosticSourceKind::Pushed,
..Diagnostic::default()
},
- },
+ ),
],
cx,
)
@@ -3967,16 +3965,16 @@ async fn test_diagnostics_from_multiple_language_servers(cx: &mut gpui::TestAppC
Path::new(path!("/dir/a.rs")).to_owned(),
None,
None,
- vec![DiagnosticEntry {
- range: Unclipped(PointUtf16::new(0, 0))..Unclipped(PointUtf16::new(0, 3)),
- diagnostic: Diagnostic {
+ vec![DiagnosticEntry::new(
+ Unclipped(PointUtf16::new(0, 0))..Unclipped(PointUtf16::new(0, 3)),
+ Diagnostic {
severity: DiagnosticSeverity::ERROR,
is_primary: true,
message: "syntax error a1".to_string(),
source_kind: DiagnosticSourceKind::Pushed,
..Diagnostic::default()
},
- }],
+ )],
cx,
)
.unwrap();
@@ -3986,16 +3984,16 @@ async fn test_diagnostics_from_multiple_language_servers(cx: &mut gpui::TestAppC
Path::new(path!("/dir/a.rs")).to_owned(),
None,
None,
- vec![DiagnosticEntry {
- range: Unclipped(PointUtf16::new(0, 0))..Unclipped(PointUtf16::new(0, 3)),
- diagnostic: Diagnostic {
+ vec![DiagnosticEntry::new(
+ Unclipped(PointUtf16::new(0, 0))..Unclipped(PointUtf16::new(0, 3)),
+ Diagnostic {
severity: DiagnosticSeverity::ERROR,
is_primary: true,
message: "syntax error b1".to_string(),
source_kind: DiagnosticSourceKind::Pushed,
..Diagnostic::default()
},
- }],
+ )],
cx,
)
.unwrap();
@@ -4030,16 +4028,16 @@ async fn test_diagnostic_summaries_cleared_on_worktree_entry_removal(
Path::new(path!("/dir/a.rs")).to_owned(),
None,
None,
- vec![DiagnosticEntry {
- range: Unclipped(PointUtf16::new(0, 0))..Unclipped(PointUtf16::new(0, 3)),
- diagnostic: Diagnostic {
+ vec![DiagnosticEntry::new(
+ Unclipped(PointUtf16::new(0, 0))..Unclipped(PointUtf16::new(0, 3)),
+ Diagnostic {
severity: DiagnosticSeverity::ERROR,
is_primary: true,
message: "error in a".to_string(),
source_kind: DiagnosticSourceKind::Pushed,
..Diagnostic::default()
},
- }],
+ )],
cx,
)
.unwrap();
@@ -4049,16 +4047,16 @@ async fn test_diagnostic_summaries_cleared_on_worktree_entry_removal(
Path::new(path!("/dir/b.rs")).to_owned(),
None,
None,
- vec![DiagnosticEntry {
- range: Unclipped(PointUtf16::new(0, 0))..Unclipped(PointUtf16::new(0, 3)),
- diagnostic: Diagnostic {
+ vec![DiagnosticEntry::new(
+ Unclipped(PointUtf16::new(0, 0))..Unclipped(PointUtf16::new(0, 3)),
+ Diagnostic {
severity: DiagnosticSeverity::WARNING,
is_primary: true,
message: "warning in b".to_string(),
source_kind: DiagnosticSourceKind::Pushed,
..Diagnostic::default()
},
- }],
+ )],
cx,
)
.unwrap();
@@ -7707,68 +7705,77 @@ async fn test_grouped_diagnostics(cx: &mut gpui::TestAppContext) {
assert_eq!(
buffer
- .diagnostics_in_range::<_, Point>(0..buffer.len(), false)
+ .diagnostic_entries_in_range(0..buffer.len(), false)
+ .map(|entry| entry.clone().map_coordinates(|range| {
+ range.start.to_point(&buffer)..range.end.to_point(&buffer)
+ }))
.collect::<Vec<_>>(),
&[
DiagnosticEntry {
range: Point::new(1, 8)..Point::new(1, 9),
+ related_information: expected_related_information(&error_1_related_information),
diagnostic: Diagnostic {
severity: DiagnosticSeverity::WARNING,
message: "error 1".to_string(),
group_id: 1,
is_primary: true,
source_kind: DiagnosticSourceKind::Pushed,
- related_information: Some(error_1_related_information.clone()),
..Diagnostic::default()
- }
+ },
},
DiagnosticEntry {
range: Point::new(1, 8)..Point::new(1, 9),
+ related_information: expected_related_information(
+ &error_1_hint_related_information
+ ),
diagnostic: Diagnostic {
severity: DiagnosticSeverity::HINT,
message: "error 1 hint 1".to_string(),
group_id: 1,
is_primary: false,
source_kind: DiagnosticSourceKind::Pushed,
- related_information: Some(error_1_hint_related_information.clone()),
..Diagnostic::default()
- }
+ },
},
DiagnosticEntry {
range: Point::new(1, 13)..Point::new(1, 15),
+ related_information: expected_related_information(
+ &error_2_hint_related_information
+ ),
diagnostic: Diagnostic {
severity: DiagnosticSeverity::HINT,
message: "error 2 hint 1".to_string(),
group_id: 0,
is_primary: false,
source_kind: DiagnosticSourceKind::Pushed,
- related_information: Some(error_2_hint_related_information.clone()),
..Diagnostic::default()
- }
+ },
},
DiagnosticEntry {
range: Point::new(1, 13)..Point::new(1, 15),
+ related_information: expected_related_information(
+ &error_2_hint_related_information
+ ),
diagnostic: Diagnostic {
severity: DiagnosticSeverity::HINT,
message: "error 2 hint 2".to_string(),
group_id: 0,
is_primary: false,
source_kind: DiagnosticSourceKind::Pushed,
- related_information: Some(error_2_hint_related_information.clone()),
..Diagnostic::default()
- }
+ },
},
DiagnosticEntry {
range: Point::new(2, 8)..Point::new(2, 17),
+ related_information: expected_related_information(&error_2_related_information),
diagnostic: Diagnostic {
severity: DiagnosticSeverity::ERROR,
message: "error 2".to_string(),
group_id: 0,
is_primary: true,
source_kind: DiagnosticSourceKind::Pushed,
- related_information: Some(error_2_related_information.clone()),
..Diagnostic::default()
- }
+ },
}
]
);
@@ -7778,39 +7785,43 @@ async fn test_grouped_diagnostics(cx: &mut gpui::TestAppContext) {
&[
DiagnosticEntry {
range: Point::new(1, 13)..Point::new(1, 15),
+ related_information: expected_related_information(
+ &error_2_hint_related_information
+ ),
diagnostic: Diagnostic {
severity: DiagnosticSeverity::HINT,
message: "error 2 hint 1".to_string(),
group_id: 0,
is_primary: false,
source_kind: DiagnosticSourceKind::Pushed,
- related_information: Some(error_2_hint_related_information.clone()),
..Diagnostic::default()
- }
+ },
},
DiagnosticEntry {
range: Point::new(1, 13)..Point::new(1, 15),
+ related_information: expected_related_information(
+ &error_2_hint_related_information
+ ),
diagnostic: Diagnostic {
severity: DiagnosticSeverity::HINT,
message: "error 2 hint 2".to_string(),
group_id: 0,
is_primary: false,
source_kind: DiagnosticSourceKind::Pushed,
- related_information: Some(error_2_hint_related_information),
..Diagnostic::default()
- }
+ },
},
DiagnosticEntry {
range: Point::new(2, 8)..Point::new(2, 17),
+ related_information: expected_related_information(&error_2_related_information),
diagnostic: Diagnostic {
severity: DiagnosticSeverity::ERROR,
message: "error 2".to_string(),
group_id: 0,
is_primary: true,
source_kind: DiagnosticSourceKind::Pushed,
- related_information: Some(error_2_related_information),
..Diagnostic::default()
- }
+ },
}
]
);
@@ -7820,27 +7831,29 @@ async fn test_grouped_diagnostics(cx: &mut gpui::TestAppContext) {
&[
DiagnosticEntry {
range: Point::new(1, 8)..Point::new(1, 9),
+ related_information: expected_related_information(&error_1_related_information),
diagnostic: Diagnostic {
severity: DiagnosticSeverity::WARNING,
message: "error 1".to_string(),
group_id: 1,
is_primary: true,
source_kind: DiagnosticSourceKind::Pushed,
- related_information: Some(error_1_related_information),
..Diagnostic::default()
- }
+ },
},
DiagnosticEntry {
range: Point::new(1, 8)..Point::new(1, 9),
+ related_information: expected_related_information(
+ &error_1_hint_related_information
+ ),
diagnostic: Diagnostic {
severity: DiagnosticSeverity::HINT,
message: "error 1 hint 1".to_string(),
group_id: 1,
is_primary: false,
source_kind: DiagnosticSourceKind::Pushed,
- related_information: Some(error_1_hint_related_information),
..Diagnostic::default()
- }
+ },
},
]
);
@@ -10042,6 +10055,294 @@ async fn test_code_actions_preserve_supporting_diagnostic_entry(cx: &mut gpui::T
assert!(code_actions_task.await.unwrap().unwrap().is_empty());
}
+#[gpui::test]
+async fn test_code_actions_related_information_follows_edits(cx: &mut gpui::TestAppContext) {
+ let (project, buffer, _handle, fake_server) = code_action_project_with(
+ FakeLspAdapter {
+ name: "test-language-server",
+ capabilities: lsp::ServerCapabilities {
+ code_action_provider: Some(lsp::CodeActionProviderCapability::Simple(true)),
+ ..lsp::ServerCapabilities::default()
+ },
+ ..FakeLspAdapter::default()
+ },
+ cx,
+ )
+ .await;
+
+ let uri = Uri::from_file_path(path!("/dir/a.ts")).unwrap();
+ let note_line = 5;
+ fake_server.notify::<lsp::notification::PublishDiagnostics>(lsp::PublishDiagnosticsParams {
+ uri: uri.clone(),
+ version: None,
+ diagnostics: vec![lsp::Diagnostic {
+ range: lsp::Range::new(lsp::Position::new(1, 0), lsp::Position::new(1, 3)),
+ severity: Some(DiagnosticSeverity::ERROR),
+ source: Some("test-language-server".to_string()),
+ message: "primary diagnostic".to_string(),
+ related_information: Some(vec![lsp::DiagnosticRelatedInformation {
+ location: lsp::Location {
+ uri,
+ range: lsp::Range::new(
+ lsp::Position::new(note_line, 0),
+ lsp::Position::new(note_line, 3),
+ ),
+ },
+ message: "note".to_string(),
+ }]),
+ ..Default::default()
+ }],
+ });
+ cx.executor().run_until_parked();
+
+ let inserted_lines = 2;
+ buffer.update(cx, |buffer, cx| {
+ buffer.edit([(0..0, "zzz\nzzz\n")], None, cx);
+ });
+ cx.executor().run_until_parked();
+
+ let mut request_handled = fake_server
+ .set_request_handler::<lsp::request::CodeActionRequest, _, _>(
+ move |params, _| async move {
+ let primary = &params.context.diagnostics[0];
+ let flattened_note = &params.context.diagnostics[1];
+ let related_note = &primary
+ .related_information
+ .as_ref()
+ .expect("the primary diagnostic carries its related information")[0];
+
+ // Both entries are anchored, so they followed the edit.
+ assert_eq!(primary.range.start.line, 1 + inserted_lines);
+ assert_eq!(flattened_note.range.start.line, note_line + inserted_lines);
+
+ // The related information of the primary points at the same note as the
+ // flattened entry, so it should have followed it.
+ assert_eq!(
+ related_note.location.range.start.line, flattened_note.range.start.line,
+ "the same note is reported at two different lines in one request"
+ );
+ Ok(Some(Vec::new()))
+ },
+ );
+
+ let buffer_length = buffer.read_with(cx, |buffer, _| buffer.len());
+ let code_actions_task = project.update(cx, |project, cx| {
+ project.code_actions(&buffer, 0..buffer_length, None, cx)
+ });
+
+ request_handled
+ .next()
+ .await
+ .expect("The code action request should have been triggered");
+ assert!(code_actions_task.await.unwrap().unwrap().is_empty());
+}
+
+#[gpui::test]
+async fn test_code_actions_related_information_of_disk_based_diagnostics(
+ cx: &mut gpui::TestAppContext,
+) {
+ let (project, buffer, _handle, fake_server) = code_action_project_with(
+ FakeLspAdapter {
+ name: "test-language-server",
+ disk_based_diagnostics_sources: vec!["disk".into()],
+ capabilities: lsp::ServerCapabilities {
+ code_action_provider: Some(lsp::CodeActionProviderCapability::Simple(true)),
+ ..lsp::ServerCapabilities::default()
+ },
+ ..FakeLspAdapter::default()
+ },
+ cx,
+ )
+ .await;
+
+ // The diagnostic below is computed against the file on disk, so its positions have
+ // to be moved by this edit, which the buffer has not saved.
+ let unsaved_lines = 1;
+ buffer.update(cx, |buffer, cx| {
+ buffer.edit([(0..0, "zzz\n")], None, cx);
+ });
+ cx.executor().run_until_parked();
+
+ let uri = Uri::from_file_path(path!("/dir/a.ts")).unwrap();
+ let note_line = 5;
+ fake_server.notify::<lsp::notification::PublishDiagnostics>(lsp::PublishDiagnosticsParams {
+ uri: uri.clone(),
+ version: None,
+ diagnostics: vec![lsp::Diagnostic {
+ range: lsp::Range::new(lsp::Position::new(1, 0), lsp::Position::new(1, 3)),
+ severity: Some(DiagnosticSeverity::ERROR),
+ source: Some("disk".to_string()),
+ message: "primary diagnostic".to_string(),
+ related_information: Some(vec![lsp::DiagnosticRelatedInformation {
+ location: lsp::Location {
+ uri,
+ range: lsp::Range::new(
+ lsp::Position::new(note_line, 0),
+ lsp::Position::new(note_line, 3),
+ ),
+ },
+ message: "note".to_string(),
+ }]),
+ ..Default::default()
+ }],
+ });
+ cx.executor().run_until_parked();
+
+ let mut request_handled = fake_server
+ .set_request_handler::<lsp::request::CodeActionRequest, _, _>(
+ move |params, _| async move {
+ let primary = &params.context.diagnostics[0];
+ let flattened_note = &params.context.diagnostics[1];
+ let related_note = &primary
+ .related_information
+ .as_ref()
+ .expect("the primary diagnostic carries its related information")[0];
+
+ assert_eq!(primary.range.start.line, 1 + unsaved_lines);
+ assert_eq!(flattened_note.range.start.line, note_line + unsaved_lines);
+ assert_eq!(
+ related_note.location.range.start.line, flattened_note.range.start.line,
+ "the related information is moved by the unsaved edits like the rest"
+ );
+ Ok(Some(Vec::new()))
+ },
+ );
+
+ let buffer_length = buffer.read_with(cx, |buffer, _| buffer.len());
+ let code_actions_task = project.update(cx, |project, cx| {
+ project.code_actions(&buffer, 0..buffer_length, None, cx)
+ });
+
+ request_handled
+ .next()
+ .await
+ .expect("The code action request should have been triggered");
+ assert!(code_actions_task.await.unwrap().unwrap().is_empty());
+}
+
+#[gpui::test]
+async fn test_code_actions_related_information_drifts_across_merges(cx: &mut gpui::TestAppContext) {
+ let (project, buffer, _handle, fake_server) = code_action_project_with(
+ FakeLspAdapter {
+ name: "test-language-server",
+ capabilities: lsp::ServerCapabilities {
+ code_action_provider: Some(lsp::CodeActionProviderCapability::Simple(true)),
+ diagnostic_provider: Some(lsp::DiagnosticServerCapabilities::Options(
+ lsp::DiagnosticOptions {
+ identifier: Some("test-pull".to_string()),
+ inter_file_dependencies: true,
+ workspace_diagnostics: false,
+ work_done_progress_options: Default::default(),
+ },
+ )),
+ ..lsp::ServerCapabilities::default()
+ },
+ initializer: Some(Box::new(|fake_server| {
+ fake_server.set_request_handler::<lsp::request::DocumentDiagnosticRequest, _, _>(
+ |_, _| async move {
+ Ok(lsp::DocumentDiagnosticReportResult::Report(
+ lsp::DocumentDiagnosticReport::Full(
+ lsp::RelatedFullDocumentDiagnosticReport {
+ related_documents: None,
+ full_document_diagnostic_report:
+ lsp::FullDocumentDiagnosticReport {
+ result_id: None,
+ items: Vec::new(),
+ },
+ },
+ ),
+ ))
+ },
+ );
+ })),
+ ..FakeLspAdapter::default()
+ },
+ cx,
+ )
+ .await;
+ let lsp_store = project.read_with(cx, |project, _| project.lsp_store());
+
+ let uri = Uri::from_file_path(path!("/dir/a.ts")).unwrap();
+ let note_line = 5;
+ fake_server.notify::<lsp::notification::PublishDiagnostics>(lsp::PublishDiagnosticsParams {
+ uri: uri.clone(),
+ version: None,
+ diagnostics: vec![lsp::Diagnostic {
+ range: lsp::Range::new(lsp::Position::new(1, 0), lsp::Position::new(1, 3)),
+ severity: Some(DiagnosticSeverity::ERROR),
+ source: Some("test-language-server".to_string()),
+ message: "primary diagnostic".to_string(),
+ related_information: Some(vec![lsp::DiagnosticRelatedInformation {
+ location: lsp::Location {
+ uri,
+ range: lsp::Range::new(
+ lsp::Position::new(note_line, 0),
+ lsp::Position::new(note_line, 3),
+ ),
+ },
+ message: "note".to_string(),
+ }]),
+ ..Default::default()
+ }],
+ });
+ cx.executor().run_until_parked();
+
+ // Each round edits the buffer and then pulls diagnostics. The pull reports nothing,
+ // so the pushed diagnostic is not replaced but merged: it is re-collected from its
+ // anchors, which is what keeps its own range current.
+ let mut inserted_lines = 0;
+ for lines in ["zzz\nzzz\n", "zzz\nzzz\nzzz\n"] {
+ buffer.update(cx, |buffer, cx| {
+ buffer.edit([(0..0, lines)], None, cx);
+ });
+ cx.executor().run_until_parked();
+
+ let pull = lsp_store.update(cx, |lsp_store, cx| {
+ lsp_store.pull_diagnostics_for_buffer(buffer.clone(), cx)
+ });
+ pull.await.unwrap();
+ cx.executor().run_until_parked();
+
+ inserted_lines += lines.lines().count() as u32;
+ }
+
+ let mut request_handled = fake_server
+ .set_request_handler::<lsp::request::CodeActionRequest, _, _>(
+ move |params, _| async move {
+ let primary = &params.context.diagnostics[0];
+ let flattened_note = &params.context.diagnostics[1];
+ let related_note = &primary
+ .related_information
+ .as_ref()
+ .expect("the primary diagnostic carries its related information")[0];
+
+ // The diagnostic survived both merges, and both of its entries were
+ // brought up to date each time.
+ assert_eq!(primary.range.start.line, 1 + inserted_lines);
+ assert_eq!(flattened_note.range.start.line, note_line + inserted_lines);
+
+ // The related information was cloned as it was published, so the two
+ // positions for the same note are now apart by every line inserted since.
+ assert_eq!(
+ related_note.location.range.start.line, flattened_note.range.start.line,
+ "the same note is reported at two different lines, {inserted_lines} apart"
+ );
+ Ok(Some(Vec::new()))
+ },
+ );
+
+ let buffer_length = buffer.read_with(cx, |buffer, _| buffer.len());
+ let code_actions_task = project.update(cx, |project, cx| {
+ project.code_actions(&buffer, 0..buffer_length, None, cx)
+ });
+
+ request_handled
+ .next()
+ .await
+ .expect("The code action request should have been triggered");
+ assert!(code_actions_task.await.unwrap().unwrap().is_empty());
+}
+
#[gpui::test]
async fn test_code_actions_with_related_information_from_multiple_servers(
cx: &mut gpui::TestAppContext,
@@ -17315,6 +17616,66 @@ async fn test_staging_hunks_with_ambiguous_placement(cx: &mut gpui::TestAppConte
);
}
+fn expected_related_information(
+ infos: &[lsp::DiagnosticRelatedInformation],
+) -> Option<Arc<[language::RelatedInformation<Point>]>> {
+ Some(
+ infos
+ .iter()
+ .map(|info| language::RelatedInformation {
+ location: language::RelatedLocation::InBuffer(
+ Point::new(
+ info.location.range.start.line,
+ info.location.range.start.character,
+ )
+ ..Point::new(
+ info.location.range.end.line,
+ info.location.range.end.character,
+ ),
+ ),
+ message: info.message.clone(),
+ })
+ .collect(),
+ )
+}
+
+async fn code_action_project_with(
+ adapter: FakeLspAdapter,
+ cx: &mut gpui::TestAppContext,
+) -> (
+ Entity<Project>,
+ Entity<Buffer>,
+ project::lsp_store::OpenLspBufferHandle,
+ lsp::FakeLanguageServer,
+) {
+ init_test(cx);
+
+ let fs = FakeFs::new(cx.executor());
+ fs.insert_tree(
+ path!("/dir"),
+ json!({
+ "a.ts": "aaa\nbbb\nccc\nddd\neee\nfff\nggg\nhhh\n",
+ }),
+ )
+ .await;
+
+ let project = Project::test(fs, [path!("/dir").as_ref()], cx).await;
+ let language_registry = project.read_with(cx, |project, _| project.languages().clone());
+ language_registry.add(typescript_lang());
+ let mut fake_language_servers = language_registry.register_fake_lsp("TypeScript", adapter);
+
+ let (buffer, handle) = project
+ .update(cx, |project, cx| {
+ project.open_local_buffer_with_lsp(path!("/dir/a.ts"), cx)
+ })
+ .await
+ .unwrap();
+ let fake_server = fake_language_servers.next().await.unwrap();
+ cx.executor().run_until_parked();
+
+ (project, buffer, handle, fake_server)
+}
+
async fn code_action_project(
server_names: &[&'static str],
cx: &mut gpui::TestAppContext,