diagnostic_set.rs

  1use crate::{range_to_lsp, Diagnostic};
  2use anyhow::Result;
  3use collections::HashMap;
  4use lsp::LanguageServerId;
  5use std::{
  6    cmp::{Ordering, Reverse},
  7    iter,
  8    ops::Range,
  9};
 10use sum_tree::{self, Bias, SumTree};
 11use text::{Anchor, FromAnchor, PointUtf16, ToOffset};
 12
 13/// A set of diagnostics associated with a given buffer, provided
 14/// by a single language server.
 15///
 16/// The diagnostics are stored in a [`SumTree`], which allows this struct
 17/// to be cheaply copied, and allows for efficient retrieval of the
 18/// diagnostics that intersect a given range of the buffer.
 19#[derive(Clone, Debug)]
 20pub struct DiagnosticSet {
 21    diagnostics: SumTree<DiagnosticEntry<Anchor>>,
 22}
 23
 24/// A single diagnostic in a set. Generic over its range type, because
 25/// the diagnostics are stored internally as [`Anchor`]s, but can be
 26/// resolved to different coordinates types like [`usize`] byte offsets or
 27/// [`Point`](gpui::Point)s.
 28#[derive(Clone, Debug, PartialEq, Eq)]
 29pub struct DiagnosticEntry<T> {
 30    /// The range of the buffer where the diagnostic applies.
 31    pub range: Range<T>,
 32    /// The information about the diagnostic.
 33    pub diagnostic: Diagnostic,
 34}
 35
 36/// A group of related diagnostics, ordered by their start position
 37/// in the buffer.
 38#[derive(Debug)]
 39pub struct DiagnosticGroup<T> {
 40    /// The diagnostics.
 41    pub entries: Vec<DiagnosticEntry<T>>,
 42    /// The index into `entries` where the primary diagnostic is stored.
 43    pub primary_ix: usize,
 44}
 45
 46#[derive(Clone, Debug)]
 47pub struct Summary {
 48    start: Anchor,
 49    end: Anchor,
 50    min_start: Anchor,
 51    max_end: Anchor,
 52    count: usize,
 53}
 54
 55impl DiagnosticEntry<PointUtf16> {
 56    /// Returns a raw LSP diagnostic used to provide diagnostic context to LSP
 57    /// codeAction request
 58    pub fn to_lsp_diagnostic_stub(&self) -> Result<lsp::Diagnostic> {
 59        let range = range_to_lsp(self.range.clone())?;
 60
 61        Ok(lsp::Diagnostic {
 62            range,
 63            code: self.diagnostic.code.clone(),
 64            severity: Some(self.diagnostic.severity),
 65            source: self.diagnostic.source.clone(),
 66            message: self.diagnostic.message.clone(),
 67            data: self.diagnostic.data.clone(),
 68            ..Default::default()
 69        })
 70    }
 71}
 72
 73impl DiagnosticSet {
 74    /// Constructs a [DiagnosticSet] from a sequence of entries, ordered by
 75    /// their position in the buffer.
 76    pub fn from_sorted_entries<I>(iter: I, buffer: &text::BufferSnapshot) -> Self
 77    where
 78        I: IntoIterator<Item = DiagnosticEntry<Anchor>>,
 79    {
 80        Self {
 81            diagnostics: SumTree::from_iter(iter, buffer),
 82        }
 83    }
 84
 85    /// Constructs a [DiagnosticSet] from a sequence of entries in an arbitrary order.
 86    pub fn new<I>(iter: I, buffer: &text::BufferSnapshot) -> Self
 87    where
 88        I: IntoIterator<Item = DiagnosticEntry<PointUtf16>>,
 89    {
 90        let mut entries = iter.into_iter().collect::<Vec<_>>();
 91        entries.sort_unstable_by_key(|entry| (entry.range.start, Reverse(entry.range.end)));
 92        Self {
 93            diagnostics: SumTree::from_iter(
 94                entries.into_iter().map(|entry| DiagnosticEntry {
 95                    range: buffer.anchor_before(entry.range.start)
 96                        ..buffer.anchor_before(entry.range.end),
 97                    diagnostic: entry.diagnostic,
 98                }),
 99                buffer,
100            ),
101        }
102    }
103
104    /// Returns the number of diagnostics in the set.
105    pub fn len(&self) -> usize {
106        self.diagnostics.summary().count
107    }
108    /// Returns true when there are no diagnostics in this diagnostic set
109    pub fn is_empty(&self) -> bool {
110        self.len() == 0
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::<_, ()>(buffer, {
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, _cx: &text::BufferSnapshot) -> 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 zero(_cx: &Self::Context) -> Self {
260        Default::default()
261    }
262
263    fn add_summary(&mut self, other: &Self, buffer: &Self::Context) {
264        if other.min_start.cmp(&self.min_start, buffer).is_lt() {
265            self.min_start = other.min_start;
266        }
267        if other.max_end.cmp(&self.max_end, buffer).is_gt() {
268            self.max_end = other.max_end;
269        }
270        self.start = other.start;
271        self.end = other.end;
272        self.count += other.count;
273    }
274}