]> git.lizzy.rs Git - rust.git/blob - src/librustc_errors/diagnostic.rs
Rollup merge of #67313 - oli-obk:document_all_the_t̶h̶i̶n̶g̶s̶dataflow, r=ecstatic...
[rust.git] / src / librustc_errors / diagnostic.rs
1 use crate::snippet::Style;
2 use crate::Applicability;
3 use crate::CodeSuggestion;
4 use crate::Level;
5 use crate::Substitution;
6 use crate::SubstitutionPart;
7 use crate::SuggestionStyle;
8 use rustc_span::{MultiSpan, Span, DUMMY_SP};
9 use std::fmt;
10
11 #[must_use]
12 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
13 pub struct Diagnostic {
14     pub level: Level,
15     pub message: Vec<(String, Style)>,
16     pub code: Option<DiagnosticId>,
17     pub span: MultiSpan,
18     pub children: Vec<SubDiagnostic>,
19     pub suggestions: Vec<CodeSuggestion>,
20
21     /// This is not used for highlighting or rendering any error message.  Rather, it can be used
22     /// as a sort key to sort a buffer of diagnostics.  By default, it is the primary span of
23     /// `span` if there is one.  Otherwise, it is `DUMMY_SP`.
24     pub sort_span: Span,
25 }
26
27 #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
28 pub enum DiagnosticId {
29     Error(String),
30     Lint(String),
31 }
32
33 /// For example a note attached to an error.
34 #[derive(Clone, Debug, PartialEq, Hash, RustcEncodable, RustcDecodable)]
35 pub struct SubDiagnostic {
36     pub level: Level,
37     pub message: Vec<(String, Style)>,
38     pub span: MultiSpan,
39     pub render_span: Option<MultiSpan>,
40 }
41
42 #[derive(Debug, PartialEq, Eq)]
43 pub struct DiagnosticStyledString(pub Vec<StringPart>);
44
45 impl DiagnosticStyledString {
46     pub fn new() -> DiagnosticStyledString {
47         DiagnosticStyledString(vec![])
48     }
49     pub fn push_normal<S: Into<String>>(&mut self, t: S) {
50         self.0.push(StringPart::Normal(t.into()));
51     }
52     pub fn push_highlighted<S: Into<String>>(&mut self, t: S) {
53         self.0.push(StringPart::Highlighted(t.into()));
54     }
55     pub fn push<S: Into<String>>(&mut self, t: S, highlight: bool) {
56         if highlight {
57             self.push_highlighted(t);
58         } else {
59             self.push_normal(t);
60         }
61     }
62     pub fn normal<S: Into<String>>(t: S) -> DiagnosticStyledString {
63         DiagnosticStyledString(vec![StringPart::Normal(t.into())])
64     }
65
66     pub fn highlighted<S: Into<String>>(t: S) -> DiagnosticStyledString {
67         DiagnosticStyledString(vec![StringPart::Highlighted(t.into())])
68     }
69
70     pub fn content(&self) -> String {
71         self.0.iter().map(|x| x.content()).collect::<String>()
72     }
73 }
74
75 #[derive(Debug, PartialEq, Eq)]
76 pub enum StringPart {
77     Normal(String),
78     Highlighted(String),
79 }
80
81 impl StringPart {
82     pub fn content(&self) -> &str {
83         match self {
84             &StringPart::Normal(ref s) | &StringPart::Highlighted(ref s) => s,
85         }
86     }
87 }
88
89 impl Diagnostic {
90     pub fn new(level: Level, message: &str) -> Self {
91         Diagnostic::new_with_code(level, None, message)
92     }
93
94     pub fn new_with_code(level: Level, code: Option<DiagnosticId>, message: &str) -> Self {
95         Diagnostic {
96             level,
97             message: vec![(message.to_owned(), Style::NoStyle)],
98             code,
99             span: MultiSpan::new(),
100             children: vec![],
101             suggestions: vec![],
102             sort_span: DUMMY_SP,
103         }
104     }
105
106     pub fn is_error(&self) -> bool {
107         match self.level {
108             Level::Bug | Level::Fatal | Level::Error | Level::FailureNote => true,
109
110             Level::Warning | Level::Note | Level::Help | Level::Cancelled => false,
111         }
112     }
113
114     /// Cancel the diagnostic (a structured diagnostic must either be emitted or
115     /// canceled or it will panic when dropped).
116     pub fn cancel(&mut self) {
117         self.level = Level::Cancelled;
118     }
119
120     pub fn cancelled(&self) -> bool {
121         self.level == Level::Cancelled
122     }
123
124     /// Set the sorting span.
125     pub fn set_sort_span(&mut self, sp: Span) {
126         self.sort_span = sp;
127     }
128
129     /// Adds a span/label to be included in the resulting snippet.
130     /// This label will be shown together with the original span/label used when creating the
131     /// diagnostic, *not* a span added by one of the `span_*` methods.
132     ///
133     /// This is pushed onto the `MultiSpan` that was created when the
134     /// diagnostic was first built. If you don't call this function at
135     /// all, and you just supplied a `Span` to create the diagnostic,
136     /// then the snippet will just include that `Span`, which is
137     /// called the primary span.
138     pub fn span_label<T: Into<String>>(&mut self, span: Span, label: T) -> &mut Self {
139         self.span.push_span_label(span, label.into());
140         self
141     }
142
143     pub fn replace_span_with(&mut self, after: Span) -> &mut Self {
144         let before = self.span.clone();
145         self.set_span(after);
146         for span_label in before.span_labels() {
147             if let Some(label) = span_label.label {
148                 self.span_label(after, label);
149             }
150         }
151         self
152     }
153
154     pub fn note_expected_found(
155         &mut self,
156         expected_label: &dyn fmt::Display,
157         expected: DiagnosticStyledString,
158         found_label: &dyn fmt::Display,
159         found: DiagnosticStyledString,
160     ) -> &mut Self {
161         self.note_expected_found_extra(expected_label, expected, found_label, found, &"", &"")
162     }
163
164     pub fn note_unsuccessfull_coercion(
165         &mut self,
166         expected: DiagnosticStyledString,
167         found: DiagnosticStyledString,
168     ) -> &mut Self {
169         let mut msg: Vec<_> =
170             vec![(format!("required when trying to coerce from type `"), Style::NoStyle)];
171         msg.extend(expected.0.iter().map(|x| match *x {
172             StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
173             StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
174         }));
175         msg.push((format!("` to type '"), Style::NoStyle));
176         msg.extend(found.0.iter().map(|x| match *x {
177             StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
178             StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
179         }));
180         msg.push((format!("`"), Style::NoStyle));
181
182         // For now, just attach these as notes
183         self.highlighted_note(msg);
184         self
185     }
186
187     pub fn note_expected_found_extra(
188         &mut self,
189         expected_label: &dyn fmt::Display,
190         expected: DiagnosticStyledString,
191         found_label: &dyn fmt::Display,
192         found: DiagnosticStyledString,
193         expected_extra: &dyn fmt::Display,
194         found_extra: &dyn fmt::Display,
195     ) -> &mut Self {
196         let expected_label = format!("expected {}", expected_label);
197         let found_label = format!("found {}", found_label);
198         let (found_padding, expected_padding) = if expected_label.len() > found_label.len() {
199             (expected_label.len() - found_label.len(), 0)
200         } else {
201             (0, found_label.len() - expected_label.len())
202         };
203         let mut msg: Vec<_> =
204             vec![(format!("{}{} `", " ".repeat(expected_padding), expected_label), Style::NoStyle)];
205         msg.extend(expected.0.iter().map(|x| match *x {
206             StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
207             StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
208         }));
209         msg.push((format!("`{}\n", expected_extra), Style::NoStyle));
210         msg.push((format!("{}{} `", " ".repeat(found_padding), found_label), Style::NoStyle));
211         msg.extend(found.0.iter().map(|x| match *x {
212             StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
213             StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
214         }));
215         msg.push((format!("`{}", found_extra), Style::NoStyle));
216
217         // For now, just attach these as notes.
218         self.highlighted_note(msg);
219         self
220     }
221
222     pub fn note_trait_signature(&mut self, name: String, signature: String) -> &mut Self {
223         self.highlighted_note(vec![
224             (format!("`{}` from trait: `", name), Style::NoStyle),
225             (signature, Style::Highlight),
226             ("`".to_string(), Style::NoStyle),
227         ]);
228         self
229     }
230
231     pub fn note(&mut self, msg: &str) -> &mut Self {
232         self.sub(Level::Note, msg, MultiSpan::new(), None);
233         self
234     }
235
236     pub fn highlighted_note(&mut self, msg: Vec<(String, Style)>) -> &mut Self {
237         self.sub_with_highlights(Level::Note, msg, MultiSpan::new(), None);
238         self
239     }
240
241     /// Prints the span with a note above it.
242     pub fn span_note<S: Into<MultiSpan>>(&mut self, sp: S, msg: &str) -> &mut Self {
243         self.sub(Level::Note, msg, sp.into(), None);
244         self
245     }
246
247     pub fn warn(&mut self, msg: &str) -> &mut Self {
248         self.sub(Level::Warning, msg, MultiSpan::new(), None);
249         self
250     }
251
252     /// Prints the span with a warn above it.
253     pub fn span_warn<S: Into<MultiSpan>>(&mut self, sp: S, msg: &str) -> &mut Self {
254         self.sub(Level::Warning, msg, sp.into(), None);
255         self
256     }
257
258     pub fn help(&mut self, msg: &str) -> &mut Self {
259         self.sub(Level::Help, msg, MultiSpan::new(), None);
260         self
261     }
262
263     /// Prints the span with some help above it.
264     pub fn span_help<S: Into<MultiSpan>>(&mut self, sp: S, msg: &str) -> &mut Self {
265         self.sub(Level::Help, msg, sp.into(), None);
266         self
267     }
268
269     pub fn multipart_suggestion(
270         &mut self,
271         msg: &str,
272         suggestion: Vec<(Span, String)>,
273         applicability: Applicability,
274     ) -> &mut Self {
275         self.suggestions.push(CodeSuggestion {
276             substitutions: vec![Substitution {
277                 parts: suggestion
278                     .into_iter()
279                     .map(|(span, snippet)| SubstitutionPart { snippet, span })
280                     .collect(),
281             }],
282             msg: msg.to_owned(),
283             style: SuggestionStyle::ShowCode,
284             applicability,
285         });
286         self
287     }
288
289     /// Prints out a message with for a multipart suggestion without showing the suggested code.
290     ///
291     /// This is intended to be used for suggestions that are obvious in what the changes need to
292     /// be from the message, showing the span label inline would be visually unpleasant
293     /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
294     /// improve understandability.
295     pub fn tool_only_multipart_suggestion(
296         &mut self,
297         msg: &str,
298         suggestion: Vec<(Span, String)>,
299         applicability: Applicability,
300     ) -> &mut Self {
301         self.suggestions.push(CodeSuggestion {
302             substitutions: vec![Substitution {
303                 parts: suggestion
304                     .into_iter()
305                     .map(|(span, snippet)| SubstitutionPart { snippet, span })
306                     .collect(),
307             }],
308             msg: msg.to_owned(),
309             style: SuggestionStyle::CompletelyHidden,
310             applicability,
311         });
312         self
313     }
314
315     /// Prints out a message with a suggested edit of the code.
316     ///
317     /// In case of short messages and a simple suggestion, rustc displays it as a label:
318     ///
319     /// ```text
320     /// try adding parentheses: `(tup.0).1`
321     /// ```
322     ///
323     /// The message
324     ///
325     /// * should not end in any punctuation (a `:` is added automatically)
326     /// * should not be a question (avoid language like "did you mean")
327     /// * should not contain any phrases like "the following", "as shown", etc.
328     /// * may look like "to do xyz, use" or "to do xyz, use abc"
329     /// * may contain a name of a function, variable, or type, but not whole expressions
330     ///
331     /// See `CodeSuggestion` for more information.
332     pub fn span_suggestion(
333         &mut self,
334         sp: Span,
335         msg: &str,
336         suggestion: String,
337         applicability: Applicability,
338     ) -> &mut Self {
339         self.span_suggestion_with_style(
340             sp,
341             msg,
342             suggestion,
343             applicability,
344             SuggestionStyle::ShowCode,
345         );
346         self
347     }
348
349     pub fn span_suggestion_with_style(
350         &mut self,
351         sp: Span,
352         msg: &str,
353         suggestion: String,
354         applicability: Applicability,
355         style: SuggestionStyle,
356     ) -> &mut Self {
357         self.suggestions.push(CodeSuggestion {
358             substitutions: vec![Substitution {
359                 parts: vec![SubstitutionPart { snippet: suggestion, span: sp }],
360             }],
361             msg: msg.to_owned(),
362             style,
363             applicability,
364         });
365         self
366     }
367
368     pub fn span_suggestion_verbose(
369         &mut self,
370         sp: Span,
371         msg: &str,
372         suggestion: String,
373         applicability: Applicability,
374     ) -> &mut Self {
375         self.span_suggestion_with_style(
376             sp,
377             msg,
378             suggestion,
379             applicability,
380             SuggestionStyle::ShowAlways,
381         );
382         self
383     }
384
385     /// Prints out a message with multiple suggested edits of the code.
386     pub fn span_suggestions(
387         &mut self,
388         sp: Span,
389         msg: &str,
390         suggestions: impl Iterator<Item = String>,
391         applicability: Applicability,
392     ) -> &mut Self {
393         self.suggestions.push(CodeSuggestion {
394             substitutions: suggestions
395                 .map(|snippet| Substitution { parts: vec![SubstitutionPart { snippet, span: sp }] })
396                 .collect(),
397             msg: msg.to_owned(),
398             style: SuggestionStyle::ShowCode,
399             applicability,
400         });
401         self
402     }
403
404     /// Prints out a message with a suggested edit of the code. If the suggestion is presented
405     /// inline, it will only show the message and not the suggestion.
406     ///
407     /// See `CodeSuggestion` for more information.
408     pub fn span_suggestion_short(
409         &mut self,
410         sp: Span,
411         msg: &str,
412         suggestion: String,
413         applicability: Applicability,
414     ) -> &mut Self {
415         self.span_suggestion_with_style(
416             sp,
417             msg,
418             suggestion,
419             applicability,
420             SuggestionStyle::HideCodeInline,
421         );
422         self
423     }
424
425     /// Prints out a message with for a suggestion without showing the suggested code.
426     ///
427     /// This is intended to be used for suggestions that are obvious in what the changes need to
428     /// be from the message, showing the span label inline would be visually unpleasant
429     /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
430     /// improve understandability.
431     pub fn span_suggestion_hidden(
432         &mut self,
433         sp: Span,
434         msg: &str,
435         suggestion: String,
436         applicability: Applicability,
437     ) -> &mut Self {
438         self.span_suggestion_with_style(
439             sp,
440             msg,
441             suggestion,
442             applicability,
443             SuggestionStyle::HideCodeAlways,
444         );
445         self
446     }
447
448     /// Adds a suggestion to the json output, but otherwise remains silent/undisplayed in the cli.
449     ///
450     /// This is intended to be used for suggestions that are *very* obvious in what the changes
451     /// need to be from the message, but we still want other tools to be able to apply them.
452     pub fn tool_only_span_suggestion(
453         &mut self,
454         sp: Span,
455         msg: &str,
456         suggestion: String,
457         applicability: Applicability,
458     ) -> &mut Self {
459         self.span_suggestion_with_style(
460             sp,
461             msg,
462             suggestion,
463             applicability,
464             SuggestionStyle::CompletelyHidden,
465         );
466         self
467     }
468
469     pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self {
470         self.span = sp.into();
471         if let Some(span) = self.span.primary_span() {
472             self.sort_span = span;
473         }
474         self
475     }
476
477     pub fn code(&mut self, s: DiagnosticId) -> &mut Self {
478         self.code = Some(s);
479         self
480     }
481
482     pub fn clear_code(&mut self) -> &mut Self {
483         self.code = None;
484         self
485     }
486
487     pub fn get_code(&self) -> Option<DiagnosticId> {
488         self.code.clone()
489     }
490
491     pub fn set_primary_message<M: Into<String>>(&mut self, msg: M) -> &mut Self {
492         self.message[0] = (msg.into(), Style::NoStyle);
493         self
494     }
495
496     pub fn message(&self) -> String {
497         self.message.iter().map(|i| i.0.as_str()).collect::<String>()
498     }
499
500     pub fn styled_message(&self) -> &Vec<(String, Style)> {
501         &self.message
502     }
503
504     /// Used by a lint. Copies over all details *but* the "main
505     /// message".
506     pub fn copy_details_not_message(&mut self, from: &Diagnostic) {
507         self.span = from.span.clone();
508         self.code = from.code.clone();
509         self.children.extend(from.children.iter().cloned())
510     }
511
512     /// Convenience function for internal use, clients should use one of the
513     /// public methods above.
514     pub fn sub(
515         &mut self,
516         level: Level,
517         message: &str,
518         span: MultiSpan,
519         render_span: Option<MultiSpan>,
520     ) {
521         let sub = SubDiagnostic {
522             level,
523             message: vec![(message.to_owned(), Style::NoStyle)],
524             span,
525             render_span,
526         };
527         self.children.push(sub);
528     }
529
530     /// Convenience function for internal use, clients should use one of the
531     /// public methods above.
532     fn sub_with_highlights(
533         &mut self,
534         level: Level,
535         message: Vec<(String, Style)>,
536         span: MultiSpan,
537         render_span: Option<MultiSpan>,
538     ) {
539         let sub = SubDiagnostic { level, message, span, render_span };
540         self.children.push(sub);
541     }
542 }
543
544 impl SubDiagnostic {
545     pub fn message(&self) -> String {
546         self.message.iter().map(|i| i.0.as_str()).collect::<String>()
547     }
548
549     pub fn styled_message(&self) -> &Vec<(String, Style)> {
550         &self.message
551     }
552 }