Skip to main content

runic_diagnostics/
diagnostic.rs

1use core::fmt;
2
3use crate::{DiagnosticCodeRef, DiagnosticDescriptor, DiagnosticTag, Severity, SourceSpan};
4
5/// An object-safe semantic diagnostic occurrence.
6pub trait Diagnostic: fmt::Debug {
7    /// Write the message for this diagnostic to `out`
8    fn message(&self, out: &mut dyn fmt::Write) -> fmt::Result;
9
10    /// An optional descriptor for this diagnostic
11    fn descriptor(&self) -> Option<&'static DiagnosticDescriptor> {
12        None
13    }
14
15    /// An optional diagnostic code
16    fn code(&self) -> Option<DiagnosticCodeRef<'_>> {
17        self.descriptor().map(|descriptor| descriptor.code.as_ref())
18    }
19
20    /// The severity of this diagnostic.
21    ///
22    /// Defaults to `Error` if unimplemented, unless `descriptor` is implemented and provides a
23    /// different default severity.
24    fn severity(&self) -> Severity {
25        self.descriptor()
26            .map_or(Severity::Error, |descriptor| descriptor.default_severity)
27    }
28
29    /// Tags associated with this diagnostic
30    fn tags(&self) -> &[DiagnosticTag] {
31        self.descriptor().map_or(&[], |descriptor| descriptor.tags)
32    }
33
34    /// Visit the structured children of this diagnostic (e.g. labels, notes, etc.)
35    fn visit(&self, _visitor: &mut dyn VisitDiagnostic) {}
36
37    /// Returns the associated [`core::error::Error`] type, if this diagnostic has one
38    fn cause(&self) -> Option<&(dyn core::error::Error + 'static)> {
39        None
40    }
41
42    /// Returns a source [`Diagnostic`] type, if this diagnostic is derived from another
43    fn diagnostic_source(&self) -> Option<&dyn Diagnostic> {
44        None
45    }
46}
47
48/// A synchronous visitor over one diagnostic's structured children.
49pub trait VisitDiagnostic {
50    fn label(&mut self, _label: Label<'_>) {}
51
52    fn note(&mut self, _note: Note<'_>) {}
53
54    fn suggestion(&mut self, _suggestion: Suggestion<'_>) {}
55
56    fn related(&mut self, _diagnostic: &dyn Diagnostic) {}
57}
58
59#[derive(Clone, Copy, Debug, Eq, PartialEq)]
60pub enum LabelStyle {
61    Primary,
62    Context,
63}
64
65pub struct Label<'a> {
66    pub span: SourceSpan,
67    pub style: LabelStyle,
68    pub message: Option<fmt::Arguments<'a>>,
69}
70
71#[derive(Clone, Copy, Debug, Eq, PartialEq)]
72pub enum NoteKind {
73    Note,
74    Help,
75}
76
77pub struct Note<'a> {
78    pub kind: NoteKind,
79    pub message: fmt::Arguments<'a>,
80}
81
82#[derive(Clone, Copy, Debug, Eq, PartialEq)]
83pub enum Applicability {
84    MachineApplicable,
85    MaybeIncorrect,
86    HasPlaceholders,
87    Unspecified,
88}
89
90pub struct Suggestion<'a> {
91    pub message: fmt::Arguments<'a>,
92    pub applicability: Applicability,
93    pub edits: &'a dyn VisitTextEdits,
94}
95
96pub struct TextEdit<'a> {
97    pub span: SourceSpan,
98    pub replacement: fmt::Arguments<'a>,
99}
100
101/// A synchronous producer of the edits in one atomic suggestion.
102pub trait VisitTextEdits {
103    fn visit_text_edits(&self, visitor: &mut dyn VisitTextEdit);
104}
105
106/// A synchronous visitor over the edits in one suggestion.
107pub trait VisitTextEdit {
108    fn text_edit(&mut self, edit: TextEdit<'_>);
109}
110
111impl<const N: usize> VisitTextEdits for [TextEdit<'_>; N] {
112    fn visit_text_edits(&self, visitor: &mut dyn VisitTextEdit) {
113        for edit in self {
114            visitor.text_edit(TextEdit {
115                span: edit.span,
116                replacement: edit.replacement,
117            });
118        }
119    }
120}
121
122pub(crate) struct DiagnosticMessage<'a>(pub(crate) &'a dyn Diagnostic);
123
124impl fmt::Display for DiagnosticMessage<'_> {
125    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
126        self.0.message(formatter)
127    }
128}
129
130#[cfg(test)]
131mod tests {
132    use alloc::{
133        rc::Rc,
134        string::{String, ToString},
135        vec::Vec,
136    };
137    use core::{
138        cell::Cell,
139        fmt::{self, Write},
140    };
141
142    use super::*;
143    use crate::{SourceId, SourceNamespace, TextRange};
144
145    fn span() -> SourceSpan {
146        SourceSpan::session(
147            SourceId::new(SourceNamespace::new_unchecked(1), 0),
148            TextRange::new(0, 0).unwrap(),
149        )
150    }
151
152    #[derive(Debug)]
153    struct Local<'a> {
154        prefix: &'a str,
155        value: Rc<Cell<u32>>,
156    }
157
158    struct CellDisplay<'a>(&'a Cell<u32>);
159
160    impl fmt::Display for CellDisplay<'_> {
161        fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
162            self.0.get().fmt(formatter)
163        }
164    }
165
166    impl Diagnostic for Local<'_> {
167        fn message(&self, out: &mut dyn Write) -> fmt::Result {
168            write!(out, "{} {}", self.prefix, self.value.get())
169        }
170
171        fn visit(&self, visitor: &mut dyn VisitDiagnostic) {
172            visitor.label(Label {
173                span: span(),
174                style: LabelStyle::Primary,
175                message: Some(format_args!("label {}", CellDisplay(&self.value))),
176            });
177            self.value.set(8);
178            visitor.note(Note {
179                kind: NoteKind::Note,
180                message: format_args!("note {}", CellDisplay(&self.value)),
181            });
182            self.value.set(9);
183            let edits = [TextEdit {
184                span: span(),
185                replacement: format_args!("replacement {}", CellDisplay(&self.value)),
186            }];
187            visitor.suggestion(Suggestion {
188                message: format_args!("suggestion {}", CellDisplay(&self.value)),
189                applicability: Applicability::MachineApplicable,
190                edits: &edits,
191            });
192            self.value.set(10);
193        }
194    }
195
196    #[derive(Default)]
197    struct CollectingVisitor {
198        labels: Vec<String>,
199        notes: Vec<String>,
200        suggestions: Vec<String>,
201        replacements: Vec<String>,
202    }
203
204    impl VisitDiagnostic for CollectingVisitor {
205        fn label(&mut self, label: Label<'_>) {
206            self.labels.push(label.message.unwrap().to_string());
207        }
208
209        fn note(&mut self, note: Note<'_>) {
210            self.notes.push(note.message.to_string());
211        }
212
213        fn suggestion(&mut self, suggestion: Suggestion<'_>) {
214            self.suggestions.push(suggestion.message.to_string());
215            struct CollectEdits<'a>(&'a mut Vec<String>);
216
217            impl VisitTextEdit for CollectEdits<'_> {
218                fn text_edit(&mut self, edit: TextEdit<'_>) {
219                    self.0.push(edit.replacement.to_string());
220                }
221            }
222
223            suggestion.edits.visit_text_edits(&mut CollectEdits(&mut self.replacements));
224        }
225    }
226
227    #[test]
228    fn protocols_are_object_safe_and_borrowed_arguments_are_consumed_synchronously() {
229        fn accepts_objects(_: &dyn Diagnostic, _: &mut dyn VisitDiagnostic) {}
230
231        let value = Rc::new(Cell::new(7));
232        let prefix = String::from("local");
233        let diagnostic = Local {
234            prefix: &prefix,
235            value: Rc::clone(&value),
236        };
237        let mut visitor = CollectingVisitor::default();
238        accepts_objects(&diagnostic, &mut visitor);
239
240        let mut message = String::new();
241        diagnostic.message(&mut message).unwrap();
242        diagnostic.visit(&mut visitor);
243        value.set(99);
244
245        assert_eq!(message, "local 7");
246        assert_eq!(visitor.labels, ["label 7"]);
247        assert_eq!(visitor.notes, ["note 8"]);
248        assert_eq!(visitor.suggestions, ["suggestion 9"]);
249        assert_eq!(visitor.replacements, ["replacement 9"]);
250
251        struct RejectWrites;
252
253        impl Write for RejectWrites {
254            fn write_str(&mut self, _text: &str) -> fmt::Result {
255                Err(fmt::Error)
256            }
257        }
258
259        assert_eq!(diagnostic.message(&mut RejectWrites), Err(fmt::Error));
260    }
261
262    #[derive(Debug)]
263    struct Related;
264
265    impl Diagnostic for Related {
266        fn message(&self, out: &mut dyn Write) -> fmt::Result {
267            out.write_str("related")
268        }
269    }
270
271    #[derive(Debug)]
272    struct Root(Related);
273
274    impl Diagnostic for Root {
275        fn message(&self, out: &mut dyn Write) -> fmt::Result {
276            out.write_str("root")
277        }
278
279        fn diagnostic_source(&self) -> Option<&dyn Diagnostic> {
280            Some(&self.0)
281        }
282
283        fn visit(&self, visitor: &mut dyn VisitDiagnostic) {
284            visitor.related(&self.0);
285        }
286    }
287
288    struct ChannelVisitor {
289        related: usize,
290    }
291
292    impl VisitDiagnostic for ChannelVisitor {
293        fn related(&mut self, _diagnostic: &dyn Diagnostic) {
294            self.related += 1;
295        }
296    }
297
298    #[test]
299    fn diagnostic_source_and_related_are_distinct_channels() {
300        let root = Root(Related);
301        assert_eq!(
302            root.diagnostic_source().map(|source| DiagnosticMessage(source).to_string()),
303            Some("related".to_string())
304        );
305        let mut visitor = ChannelVisitor { related: 0 };
306        root.visit(&mut visitor);
307        assert_eq!(visitor.related, 1);
308    }
309}