diagnostic_set.rs

  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            ..Default::default()
 73        }
 74    }
 75}
 76
 77impl DiagnosticSet {
 78    /// Constructs a [DiagnosticSet] from a sequence of entries, ordered by
 79    /// their position in the buffer.
 80    pub fn from_sorted_entries<I>(iter: I, buffer: &text::BufferSnapshot) -> Self
 81    where
 82        I: IntoIterator<Item = DiagnosticEntry<Anchor>>,
 83    {
 84        Self {
 85            diagnostics: SumTree::from_iter(iter, buffer),
 86        }
 87    }
 88
 89    /// Constructs a [DiagnosticSet] from a sequence of entries in an arbitrary order.
 90    pub fn new<I>(iter: I, buffer: &text::BufferSnapshot) -> Self
 91    where
 92        I: IntoIterator<Item = DiagnosticEntry<PointUtf16>>,
 93    {
 94        let mut entries = iter.into_iter().collect::<Vec<_>>();
 95        entries.sort_unstable_by_key(|entry| (entry.range.start, Reverse(entry.range.end)));
 96        Self {
 97            diagnostics: SumTree::from_iter(
 98                entries.into_iter().map(|entry| DiagnosticEntry {
 99                    range: buffer.anchor_before(entry.range.start)
100                        ..buffer.anchor_before(entry.range.end),
101                    diagnostic: entry.diagnostic,
102                }),
103                buffer,
104            ),
105        }
106    }
107
108    /// Returns the number of diagnostics in the set.
109    pub fn len(&self) -> usize {
110        self.diagnostics.summary().count
111    }
112
113    /// Returns an iterator over the diagnostic entries in the set.
114    pub fn iter(&self) -> impl Iterator<Item = &DiagnosticEntry<Anchor>> {
115        self.diagnostics.iter()
116    }
117
118    /// Returns an iterator over the diagnostic entries that intersect the
119    /// given range of the buffer.
120    pub fn range<'a, T, O>(
121        &'a self,
122        range: Range<T>,
123        buffer: &'a text::BufferSnapshot,
124        inclusive: bool,
125        reversed: bool,
126    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>>
127    where
128        T: 'a + ToOffset,
129        O: FromAnchor,
130    {
131        let end_bias = if inclusive { Bias::Right } else { Bias::Left };
132        let range = buffer.anchor_before(range.start)..buffer.anchor_at(range.end, end_bias);
133        let mut cursor = self.diagnostics.filter::<_, ()>({
134            move |summary: &Summary| {
135                let start_cmp = range.start.cmp(&summary.max_end, buffer);
136                let end_cmp = range.end.cmp(&summary.min_start, buffer);
137                if inclusive {
138                    start_cmp <= Ordering::Equal && end_cmp >= Ordering::Equal
139                } else {
140                    start_cmp == Ordering::Less && end_cmp == Ordering::Greater
141                }
142            }
143        });
144
145        if reversed {
146            cursor.prev(buffer);
147        } else {
148            cursor.next(buffer);
149        }
150        iter::from_fn({
151            move || {
152                if let Some(diagnostic) = cursor.item() {
153                    if reversed {
154                        cursor.prev(buffer);
155                    } else {
156                        cursor.next(buffer);
157                    }
158                    Some(diagnostic.resolve(buffer))
159                } else {
160                    None
161                }
162            }
163        })
164    }
165
166    /// Adds all of this set's diagnostic groups to the given output vector.
167    pub fn groups(
168        &self,
169        language_server_id: LanguageServerId,
170        output: &mut Vec<(LanguageServerId, DiagnosticGroup<Anchor>)>,
171        buffer: &text::BufferSnapshot,
172    ) {
173        let mut groups = HashMap::default();
174        for entry in self.diagnostics.iter() {
175            groups
176                .entry(entry.diagnostic.group_id)
177                .or_insert(Vec::new())
178                .push(entry.clone());
179        }
180
181        let start_ix = output.len();
182        output.extend(groups.into_values().filter_map(|mut entries| {
183            entries.sort_unstable_by(|a, b| a.range.start.cmp(&b.range.start, buffer));
184            entries
185                .iter()
186                .position(|entry| entry.diagnostic.is_primary)
187                .map(|primary_ix| {
188                    (
189                        language_server_id,
190                        DiagnosticGroup {
191                            entries,
192                            primary_ix,
193                        },
194                    )
195                })
196        }));
197        output[start_ix..].sort_unstable_by(|(id_a, group_a), (id_b, group_b)| {
198            group_a.entries[group_a.primary_ix]
199                .range
200                .start
201                .cmp(&group_b.entries[group_b.primary_ix].range.start, buffer)
202                .then_with(|| id_a.cmp(id_b))
203        });
204    }
205
206    /// Returns all of the diagnostics in a particular diagnostic group,
207    /// in order of their position in the buffer.
208    pub fn group<'a, O: FromAnchor>(
209        &'a self,
210        group_id: usize,
211        buffer: &'a text::BufferSnapshot,
212    ) -> impl 'a + Iterator<Item = DiagnosticEntry<O>> {
213        self.iter()
214            .filter(move |entry| entry.diagnostic.group_id == group_id)
215            .map(|entry| entry.resolve(buffer))
216    }
217}
218
219impl sum_tree::Item for DiagnosticEntry<Anchor> {
220    type Summary = Summary;
221
222    fn summary(&self) -> Self::Summary {
223        Summary {
224            start: self.range.start,
225            end: self.range.end,
226            min_start: self.range.start,
227            max_end: self.range.end,
228            count: 1,
229        }
230    }
231}
232
233impl DiagnosticEntry<Anchor> {
234    /// Converts the [DiagnosticEntry] to a different buffer coordinate type.
235    pub fn resolve<O: FromAnchor>(&self, buffer: &text::BufferSnapshot) -> DiagnosticEntry<O> {
236        DiagnosticEntry {
237            range: O::from_anchor(&self.range.start, buffer)
238                ..O::from_anchor(&self.range.end, buffer),
239            diagnostic: self.diagnostic.clone(),
240        }
241    }
242}
243
244impl Default for Summary {
245    fn default() -> Self {
246        Self {
247            start: Anchor::MIN,
248            end: Anchor::MAX,
249            min_start: Anchor::MAX,
250            max_end: Anchor::MIN,
251            count: 0,
252        }
253    }
254}
255
256impl sum_tree::Summary for Summary {
257    type Context = text::BufferSnapshot;
258
259    fn add_summary(&mut self, other: &Self, buffer: &Self::Context) {
260        if other.min_start.cmp(&self.min_start, buffer).is_lt() {
261            self.min_start = other.min_start;
262        }
263        if other.max_end.cmp(&self.max_end, buffer).is_gt() {
264            self.max_end = other.max_end;
265        }
266        self.start = other.start;
267        self.end = other.end;
268        self.count += other.count;
269    }
270}