cairo_lang_diagnostics/
diagnostics.rs

1use std::fmt;
2use std::hash::Hash;
3use std::sync::Arc;
4
5use cairo_lang_debug::debug::DebugWithDb;
6use cairo_lang_filesystem::db::{FilesGroup, get_originating_location};
7use cairo_lang_filesystem::ids::FileId;
8use cairo_lang_filesystem::span::TextSpan;
9use cairo_lang_utils::Upcast;
10use cairo_lang_utils::ordered_hash_map::OrderedHashMap;
11use itertools::Itertools;
12
13use crate::error_code::{ErrorCode, OptionErrorCodeExt};
14use crate::location_marks::get_location_marks;
15
16#[cfg(test)]
17#[path = "diagnostics_test.rs"]
18mod test;
19
20/// The severity of a diagnostic.
21#[derive(Eq, PartialEq, Hash, Ord, PartialOrd, Clone, Copy, Debug)]
22pub enum Severity {
23    Error,
24    Warning,
25}
26impl fmt::Display for Severity {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        match self {
29            Severity::Error => write!(f, "error"),
30            Severity::Warning => write!(f, "warning"),
31        }
32    }
33}
34
35/// A trait for diagnostics (i.e., errors and warnings) across the compiler.
36/// Meant to be implemented by each module that may produce diagnostics.
37pub trait DiagnosticEntry: Clone + fmt::Debug + Eq + Hash {
38    type DbType: Upcast<dyn FilesGroup> + ?Sized;
39    fn format(&self, db: &Self::DbType) -> String;
40    fn location(&self, db: &Self::DbType) -> DiagnosticLocation;
41    fn notes(&self, _db: &Self::DbType) -> &[DiagnosticNote] {
42        &[]
43    }
44    fn severity(&self) -> Severity {
45        Severity::Error
46    }
47    fn error_code(&self) -> Option<ErrorCode> {
48        None
49    }
50    /// Returns true if the two should be regarded as the same kind when filtering duplicate
51    /// diagnostics.
52    fn is_same_kind(&self, other: &Self) -> bool;
53
54    // TODO(spapini): Add a way to inspect the diagnostic programmatically, e.g, downcast.
55}
56
57/// Diagnostic notes for diagnostics originating in the plugin generated files identified by
58/// [`FileId`].
59pub type PluginFileDiagnosticNotes = OrderedHashMap<FileId, DiagnosticNote>;
60
61// The representation of a source location inside a diagnostic.
62#[derive(Clone, Debug, Eq, Hash, PartialEq)]
63pub struct DiagnosticLocation {
64    pub file_id: FileId,
65    pub span: TextSpan,
66}
67impl DiagnosticLocation {
68    /// Get the location of right after this diagnostic's location (with width 0).
69    pub fn after(&self) -> Self {
70        Self { file_id: self.file_id, span: self.span.after() }
71    }
72
73    /// Get the location of the originating user code.
74    pub fn user_location(&self, db: &dyn FilesGroup) -> Self {
75        let (file_id, span) = get_originating_location(db, self.file_id, self.span, None);
76        Self { file_id, span }
77    }
78
79    /// Get the location of the originating user code,
80    /// along with [`DiagnosticNote`]s for this translation.
81    /// The notes are collected from the parent files of the originating location.
82    pub fn user_location_with_plugin_notes(
83        &self,
84        db: &dyn FilesGroup,
85        file_notes: &PluginFileDiagnosticNotes,
86    ) -> (Self, Vec<DiagnosticNote>) {
87        let mut parent_files = Vec::new();
88        let (file_id, span) =
89            get_originating_location(db, self.file_id, self.span, Some(&mut parent_files));
90        let diagnostic_notes = parent_files
91            .into_iter()
92            .rev()
93            .filter_map(|file_id| file_notes.get(&file_id).cloned())
94            .collect_vec();
95        (Self { file_id, span }, diagnostic_notes)
96    }
97
98    /// Helper function to format the location of a diagnostic.
99    pub fn fmt_location(&self, f: &mut fmt::Formatter<'_>, db: &dyn FilesGroup) -> fmt::Result {
100        let user_location = self.user_location(db);
101        let file_path = user_location.file_id.full_path(db);
102        let start = match user_location.span.start.position_in_file(db, user_location.file_id) {
103            Some(pos) => format!("{}:{}", pos.line + 1, pos.col + 1),
104            None => "?".into(),
105        };
106
107        let end = match user_location.span.end.position_in_file(db, user_location.file_id) {
108            Some(pos) => format!("{}:{}", pos.line + 1, pos.col + 1),
109            None => "?".into(),
110        };
111        write!(f, "{file_path}:{start}: {end}")
112    }
113}
114
115impl DebugWithDb<dyn FilesGroup> for DiagnosticLocation {
116    fn fmt(&self, f: &mut fmt::Formatter<'_>, db: &dyn FilesGroup) -> fmt::Result {
117        let user_location = self.user_location(db);
118        let file_path = user_location.file_id.full_path(db);
119        let mut marks = String::new();
120        let mut ending_pos = String::new();
121        let starting_pos =
122            match user_location.span.start.position_in_file(db, user_location.file_id) {
123                Some(starting_text_pos) => {
124                    if let Some(ending_text_pos) =
125                        user_location.span.end.position_in_file(db, user_location.file_id)
126                    {
127                        if starting_text_pos.line != ending_text_pos.line {
128                            ending_pos =
129                                format!("-{}:{}", ending_text_pos.line + 1, ending_text_pos.col);
130                        }
131                    }
132                    marks = get_location_marks(db, &user_location, true);
133                    format!("{}:{}", starting_text_pos.line + 1, starting_text_pos.col + 1)
134                }
135                None => "?".into(),
136            };
137        write!(f, "{file_path}:{starting_pos}{ending_pos}\n{marks}")
138    }
139}
140
141/// A note about a diagnostic.
142/// May include a relevant diagnostic location.
143#[derive(Clone, Debug, Eq, Hash, PartialEq)]
144pub struct DiagnosticNote {
145    pub text: String,
146    pub location: Option<DiagnosticLocation>,
147}
148impl DiagnosticNote {
149    pub fn text_only(text: String) -> Self {
150        Self { text, location: None }
151    }
152
153    pub fn with_location(text: String, location: DiagnosticLocation) -> Self {
154        Self { text, location: Some(location) }
155    }
156}
157
158impl DebugWithDb<dyn FilesGroup> for DiagnosticNote {
159    fn fmt(&self, f: &mut fmt::Formatter<'_>, db: &(dyn FilesGroup + 'static)) -> fmt::Result {
160        write!(f, "{}", self.text)?;
161        if let Some(location) = &self.location {
162            write!(f, ":\n  --> ")?;
163            location.user_location(db).fmt(f, db)?;
164        }
165        Ok(())
166    }
167}
168
169/// This struct is used to ensure that when an error occurs, a diagnostic is properly reported.
170///
171/// It must not be constructed directly. Instead, it is returned by [DiagnosticsBuilder::add]
172/// when a diagnostic is reported.
173#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
174pub struct DiagnosticAdded;
175
176pub fn skip_diagnostic() -> DiagnosticAdded {
177    // TODO(lior): Consider adding a log here.
178    DiagnosticAdded
179}
180
181/// Represents an arbitrary type T or a missing output due to an error whose diagnostic was properly
182/// reported.
183pub type Maybe<T> = Result<T, DiagnosticAdded>;
184
185/// Temporary trait to allow conversions from the old `Option<T>` mechanism to `Maybe<T>`.
186// TODO(lior): Remove this trait after converting all the functions.
187pub trait ToMaybe<T> {
188    fn to_maybe(self) -> Maybe<T>;
189}
190impl<T> ToMaybe<T> for Option<T> {
191    fn to_maybe(self) -> Maybe<T> {
192        match self {
193            Some(val) => Ok(val),
194            None => Err(skip_diagnostic()),
195        }
196    }
197}
198
199/// Temporary trait to allow conversions from `Maybe<T>` to `Option<T>`.
200///
201/// The behavior is identical to [Result::ok]. It is used to mark all the location where there
202/// is a conversion between the two mechanisms.
203// TODO(lior): Remove this trait after converting all the functions.
204pub trait ToOption<T> {
205    fn to_option(self) -> Option<T>;
206}
207impl<T> ToOption<T> for Maybe<T> {
208    fn to_option(self) -> Option<T> {
209        self.ok()
210    }
211}
212
213/// A builder for Diagnostics, accumulating multiple diagnostic entries.
214#[derive(Clone, Debug, Eq, Hash, PartialEq)]
215pub struct DiagnosticsBuilder<TEntry: DiagnosticEntry> {
216    pub error_count: usize,
217    pub leaves: Vec<TEntry>,
218    pub subtrees: Vec<Diagnostics<TEntry>>,
219}
220impl<TEntry: DiagnosticEntry> DiagnosticsBuilder<TEntry> {
221    pub fn add(&mut self, diagnostic: TEntry) -> DiagnosticAdded {
222        if diagnostic.severity() == Severity::Error {
223            self.error_count += 1;
224        }
225        self.leaves.push(diagnostic);
226        DiagnosticAdded
227    }
228    pub fn extend(&mut self, diagnostics: Diagnostics<TEntry>) {
229        self.error_count += diagnostics.0.error_count;
230        self.subtrees.push(diagnostics);
231    }
232    pub fn build(self) -> Diagnostics<TEntry> {
233        Diagnostics(self.into())
234    }
235}
236impl<TEntry: DiagnosticEntry> From<Diagnostics<TEntry>> for DiagnosticsBuilder<TEntry> {
237    fn from(diagnostics: Diagnostics<TEntry>) -> Self {
238        let mut new_self = Self::default();
239        new_self.extend(diagnostics);
240        new_self
241    }
242}
243impl<TEntry: DiagnosticEntry> Default for DiagnosticsBuilder<TEntry> {
244    fn default() -> Self {
245        Self { leaves: Default::default(), subtrees: Default::default(), error_count: 0 }
246    }
247}
248
249pub fn format_diagnostics(
250    db: &(dyn FilesGroup + 'static),
251    message: &str,
252    location: DiagnosticLocation,
253) -> String {
254    format!("{message}\n --> {:?}\n", location.debug(db))
255}
256
257#[derive(Debug)]
258pub struct FormattedDiagnosticEntry {
259    severity: Severity,
260    error_code: Option<ErrorCode>,
261    message: String,
262}
263
264impl FormattedDiagnosticEntry {
265    pub fn new(severity: Severity, error_code: Option<ErrorCode>, message: String) -> Self {
266        Self { severity, error_code, message }
267    }
268
269    pub fn is_empty(&self) -> bool {
270        self.message().is_empty()
271    }
272
273    pub fn severity(&self) -> Severity {
274        self.severity
275    }
276
277    pub fn error_code(&self) -> Option<ErrorCode> {
278        self.error_code
279    }
280
281    pub fn message(&self) -> &str {
282        &self.message
283    }
284}
285
286impl fmt::Display for FormattedDiagnosticEntry {
287    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
288        write!(
289            f,
290            "{severity}{code}: {message}",
291            severity = self.severity,
292            message = self.message,
293            code = self.error_code.display_bracketed()
294        )
295    }
296}
297
298/// A set of diagnostic entries that arose during a computation.
299#[derive(Clone, Debug, Eq, Hash, PartialEq)]
300pub struct Diagnostics<TEntry: DiagnosticEntry>(pub Arc<DiagnosticsBuilder<TEntry>>);
301impl<TEntry: DiagnosticEntry> Diagnostics<TEntry> {
302    pub fn new() -> Self {
303        Self(DiagnosticsBuilder::default().into())
304    }
305
306    /// Returns Ok if there are no errors, or DiagnosticAdded if there are.
307    pub fn check_error_free(&self) -> Maybe<()> {
308        if self.0.error_count == 0 { Ok(()) } else { Err(DiagnosticAdded) }
309    }
310
311    /// Checks if there are no entries inside `Diagnostics`
312    pub fn is_empty(&self) -> bool {
313        self.0.leaves.is_empty() && self.0.subtrees.iter().all(|subtree| subtree.is_empty())
314    }
315
316    /// Format entries to pairs of severity and message.
317    pub fn format_with_severity(
318        &self,
319        db: &TEntry::DbType,
320        file_notes: &OrderedHashMap<FileId, DiagnosticNote>,
321    ) -> Vec<FormattedDiagnosticEntry> {
322        let mut res: Vec<FormattedDiagnosticEntry> = Vec::new();
323
324        let files_db = db.upcast();
325        for entry in &self.get_diagnostics_without_duplicates(db) {
326            let mut msg = String::new();
327            let diag_location = entry.location(db);
328            let (user_location, parent_file_notes) =
329                diag_location.user_location_with_plugin_notes(files_db, file_notes);
330            msg += &format_diagnostics(files_db, &entry.format(db), user_location);
331            for note in entry.notes(db) {
332                msg += &format!("note: {:?}\n", note.debug(files_db))
333            }
334            for note in parent_file_notes {
335                msg += &format!("note: {:?}\n", note.debug(files_db))
336            }
337            msg += "\n";
338
339            let formatted =
340                FormattedDiagnosticEntry::new(entry.severity(), entry.error_code(), msg);
341            res.push(formatted);
342        }
343        res
344    }
345
346    /// Format entries to a [`String`] with messages prefixed by severity.
347    pub fn format(&self, db: &TEntry::DbType) -> String {
348        self.format_with_severity(db, &Default::default()).iter().map(ToString::to_string).join("")
349    }
350
351    /// Asserts that no diagnostic has occurred, panicking with an error message on failure.
352    pub fn expect(&self, error_message: &str) {
353        assert!(self.is_empty(), "{error_message}\n{self:?}");
354    }
355
356    /// Same as [Self::expect], except that the diagnostics are formatted.
357    pub fn expect_with_db(&self, db: &TEntry::DbType, error_message: &str) {
358        assert!(self.is_empty(), "{}\n{}", error_message, self.format(db));
359    }
360
361    // TODO(spapini): This is temporary. Remove once the logic in language server doesn't use this.
362    /// Get all diagnostics.
363    pub fn get_all(&self) -> Vec<TEntry> {
364        let mut res = self.0.leaves.clone();
365        for subtree in &self.0.subtrees {
366            res.extend(subtree.get_all())
367        }
368        res
369    }
370
371    /// Get diagnostics without duplication.
372    ///
373    /// Two diagnostics are considered duplicated if both point to
374    /// the same location in the user code, and are of the same kind.
375    pub fn get_diagnostics_without_duplicates(&self, db: &TEntry::DbType) -> Vec<TEntry> {
376        let diagnostic_with_dup = self.get_all();
377        if diagnostic_with_dup.is_empty() {
378            return diagnostic_with_dup;
379        }
380        let files_db = db.upcast();
381        let mut indexed_dup_diagnostic =
382            diagnostic_with_dup.iter().enumerate().sorted_by_cached_key(|(idx, diag)| {
383                (diag.location(db).user_location(files_db).span, diag.format(db), *idx)
384            });
385        let mut prev_diagnostic_indexed = indexed_dup_diagnostic.next().unwrap();
386        let mut diagnostic_without_dup = vec![prev_diagnostic_indexed];
387
388        for diag in indexed_dup_diagnostic {
389            if prev_diagnostic_indexed.1.is_same_kind(diag.1)
390                && prev_diagnostic_indexed.1.location(db).user_location(files_db).span
391                    == diag.1.location(db).user_location(files_db).span
392            {
393                continue;
394            }
395            diagnostic_without_dup.push(diag);
396            prev_diagnostic_indexed = diag;
397        }
398        diagnostic_without_dup.sort_by_key(|(idx, _)| *idx);
399        diagnostic_without_dup.into_iter().map(|(_, diag)| diag.clone()).collect()
400    }
401}
402impl<TEntry: DiagnosticEntry> Default for Diagnostics<TEntry> {
403    fn default() -> Self {
404        Self::new()
405    }
406}
407impl<TEntry: DiagnosticEntry> FromIterator<TEntry> for Diagnostics<TEntry> {
408    fn from_iter<T: IntoIterator<Item = TEntry>>(diags_iter: T) -> Self {
409        let mut builder = DiagnosticsBuilder::<TEntry>::default();
410        for diag in diags_iter {
411            builder.add(diag);
412        }
413        builder.build()
414    }
415}