1use crate::{range_to_lsp, Diagnostic};
2use collections::HashMap;
3use lsp::LanguageServerId;
4use std::{
5 cmp::{Ordering, Reverse},
6 iter,
7 ops::Range,
8};
9use sum_tree::{self, Bias, SumTree};
10use text::{Anchor, FromAnchor, PointUtf16, ToOffset};
11
12/// A set of diagnostics associated with a given buffer, provided
13/// by a single language server.
14///
15/// The diagnostics are stored in a [`SumTree`], which allows this struct
16/// to be cheaply copied, and allows for efficient retrieval of the
17/// diagnostics that intersect a given range of the buffer.
18#[derive(Clone, Debug, Default)]
19pub struct DiagnosticSet {
20 diagnostics: SumTree<DiagnosticEntry<Anchor>>,
21}
22
23/// A single diagnostic in a set. Generic over its range type, because
24/// the diagnostics are stored internally as [`Anchor`]s, but can be
25/// resolved to different coordinates types like [`usize`] byte offsets or
26/// [`Point`](gpui::Point)s.
27#[derive(Clone, Debug, PartialEq, Eq)]
28pub struct DiagnosticEntry<T> {
29 /// The range of the buffer where the diagnostic applies.
30 pub range: Range<T>,
31 /// The information about the diagnostic.
32 pub diagnostic: Diagnostic,
33}
34
35/// A group of related diagnostics, ordered by their start position
36/// in the buffer.
37#[derive(Debug)]
38pub struct DiagnosticGroup<T> {
39 /// The diagnostics.
40 pub entries: Vec<DiagnosticEntry<T>>,
41 /// The index into `entries` where the primary diagnostic is stored.
42 pub primary_ix: usize,
43}
44
45#[derive(Clone, Debug)]
46pub struct Summary {
47 start: Anchor,
48 end: Anchor,
49 min_start: Anchor,
50 max_end: Anchor,
51 count: usize,
52}
53
54impl DiagnosticEntry<PointUtf16> {
55 /// Returns a raw LSP diagnostic ssed to provide diagnostic context to LSP
56 /// codeAction request
57 pub fn to_lsp_diagnostic_stub(&self) -> lsp::Diagnostic {
58 let code = self
59 .diagnostic
60 .code
61 .clone()
62 .map(lsp::NumberOrString::String);
63
64 let range = range_to_lsp(self.range.clone());
65
66 lsp::Diagnostic {
67 code,
68 range,
69 severity: Some(self.diagnostic.severity),
70 source: self.diagnostic.source.clone(),
71 message: self.diagnostic.message.clone(),
72 data: self.diagnostic.data.clone(),
73 ..Default::default()
74 }
75 }
76}
77
78impl DiagnosticSet {
79 /// Constructs a [DiagnosticSet] from a sequence of entries, ordered by
80 /// their position in the buffer.
81 pub fn from_sorted_entries<I>(iter: I, buffer: &text::BufferSnapshot) -> Self
82 where
83 I: IntoIterator<Item = DiagnosticEntry<Anchor>>,
84 {
85 Self {
86 diagnostics: SumTree::from_iter(iter, buffer),
87 }
88 }
89
90 /// Constructs a [DiagnosticSet] from a sequence of entries in an arbitrary order.
91 pub fn new<I>(iter: I, buffer: &text::BufferSnapshot) -> Self
92 where
93 I: IntoIterator<Item = DiagnosticEntry<PointUtf16>>,
94 {
95 let mut entries = iter.into_iter().collect::<Vec<_>>();
96 entries.sort_unstable_by_key(|entry| (entry.range.start, Reverse(entry.range.end)));
97 Self {
98 diagnostics: SumTree::from_iter(
99 entries.into_iter().map(|entry| DiagnosticEntry {
100 range: buffer.anchor_before(entry.range.start)
101 ..buffer.anchor_before(entry.range.end),
102 diagnostic: entry.diagnostic,
103 }),
104 buffer,
105 ),
106 }
107 }
108
109 /// Returns the number of diagnostics in the set.
110 pub fn len(&self) -> usize {
111 self.diagnostics.summary().count
112 }
113
114 /// Returns an iterator over the diagnostic entries in the set.
115 pub fn iter(&self) -> impl Iterator<Item = &DiagnosticEntry<Anchor>> {
116 self.diagnostics.iter()
117 }
118
119 /// Returns an iterator over the diagnostic entries that intersect the
120 /// given range of the buffer.
121 pub fn range<'a, T, O>(
122 &'a self,
123 range: Range<T>,
124 buffer: &'a text::BufferSnapshot,
125 inclusive: bool,
126 reversed: bool,
127 ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
128 where
129 T: 'a + ToOffset,
130 O: FromAnchor,
131 {
132 let end_bias = if inclusive { Bias::Right } else { Bias::Left };
133 let range = buffer.anchor_before(range.start)..buffer.anchor_at(range.end, end_bias);
134 let mut cursor = self.diagnostics.filter::<_, ()>({
135 move |summary: &Summary| {
136 let start_cmp = range.start.cmp(&summary.max_end, buffer);
137 let end_cmp = range.end.cmp(&summary.min_start, buffer);
138 if inclusive {
139 start_cmp <= Ordering::Equal && end_cmp >= Ordering::Equal
140 } else {
141 start_cmp == Ordering::Less && end_cmp == Ordering::Greater
142 }
143 }
144 });
145
146 if reversed {
147 cursor.prev(buffer);
148 } else {
149 cursor.next(buffer);
150 }
151 iter::from_fn({
152 move || {
153 if let Some(diagnostic) = cursor.item() {
154 if reversed {
155 cursor.prev(buffer);
156 } else {
157 cursor.next(buffer);
158 }
159 Some(diagnostic.resolve(buffer))
160 } else {
161 None
162 }
163 }
164 })
165 }
166
167 /// Adds all of this set's diagnostic groups to the given output vector.
168 pub fn groups(
169 &self,
170 language_server_id: LanguageServerId,
171 output: &mut Vec<(LanguageServerId, DiagnosticGroup<Anchor>)>,
172 buffer: &text::BufferSnapshot,
173 ) {
174 let mut groups = HashMap::default();
175 for entry in self.diagnostics.iter() {
176 groups
177 .entry(entry.diagnostic.group_id)
178 .or_insert(Vec::new())
179 .push(entry.clone());
180 }
181
182 let start_ix = output.len();
183 output.extend(groups.into_values().filter_map(|mut entries| {
184 entries.sort_unstable_by(|a, b| a.range.start.cmp(&b.range.start, buffer));
185 entries
186 .iter()
187 .position(|entry| entry.diagnostic.is_primary)
188 .map(|primary_ix| {
189 (
190 language_server_id,
191 DiagnosticGroup {
192 entries,
193 primary_ix,
194 },
195 )
196 })
197 }));
198 output[start_ix..].sort_unstable_by(|(id_a, group_a), (id_b, group_b)| {
199 group_a.entries[group_a.primary_ix]
200 .range
201 .start
202 .cmp(&group_b.entries[group_b.primary_ix].range.start, buffer)
203 .then_with(|| id_a.cmp(id_b))
204 });
205 }
206
207 /// Returns all of the diagnostics in a particular diagnostic group,
208 /// in order of their position in the buffer.
209 pub fn group<'a, O: FromAnchor>(
210 &'a self,
211 group_id: usize,
212 buffer: &'a text::BufferSnapshot,
213 ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>> {
214 self.iter()
215 .filter(move |entry| entry.diagnostic.group_id == group_id)
216 .map(|entry| entry.resolve(buffer))
217 }
218}
219
220impl sum_tree::Item for DiagnosticEntry<Anchor> {
221 type Summary = Summary;
222
223 fn summary(&self) -> Self::Summary {
224 Summary {
225 start: self.range.start,
226 end: self.range.end,
227 min_start: self.range.start,
228 max_end: self.range.end,
229 count: 1,
230 }
231 }
232}
233
234impl DiagnosticEntry<Anchor> {
235 /// Converts the [DiagnosticEntry] to a different buffer coordinate type.
236 pub fn resolve<O: FromAnchor>(&self, buffer: &text::BufferSnapshot) -> DiagnosticEntry<O> {
237 DiagnosticEntry {
238 range: O::from_anchor(&self.range.start, buffer)
239 ..O::from_anchor(&self.range.end, buffer),
240 diagnostic: self.diagnostic.clone(),
241 }
242 }
243}
244
245impl Default for Summary {
246 fn default() -> Self {
247 Self {
248 start: Anchor::MIN,
249 end: Anchor::MAX,
250 min_start: Anchor::MAX,
251 max_end: Anchor::MIN,
252 count: 0,
253 }
254 }
255}
256
257impl sum_tree::Summary for Summary {
258 type Context = text::BufferSnapshot;
259
260 fn add_summary(&mut self, other: &Self, buffer: &Self::Context) {
261 if other.min_start.cmp(&self.min_start, buffer).is_lt() {
262 self.min_start = other.min_start;
263 }
264 if other.max_end.cmp(&self.max_end, buffer).is_gt() {
265 self.max_end = other.max_end;
266 }
267 self.start = other.start;
268 self.end = other.end;
269 self.count += other.count;
270 }
271}