]> git.lizzy.rs Git - rust.git/blob - src/librustc_errors/diagnostic.rs
Auto merge of #69393 - Dylan-DPC:rollup-rxbd1zg, r=Dylan-DPC
[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
198         let found_label = format!("found {}", found_label);
199         let (found_padding, expected_padding) = if expected_label.len() > found_label.len() {
200             (expected_label.len() - found_label.len(), 0)
201         } else {
202             (0, found_label.len() - expected_label.len())
203         };
204         let mut msg: Vec<_> =
205             vec![(format!("{}{} `", " ".repeat(expected_padding), expected_label), Style::NoStyle)];
206         msg.extend(expected.0.iter().map(|x| match *x {
207             StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
208             StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
209         }));
210         msg.push((format!("`{}\n", expected_extra), Style::NoStyle));
211         msg.push((format!("{}{} `", " ".repeat(found_padding), found_label), Style::NoStyle));
212         msg.extend(found.0.iter().map(|x| match *x {
213             StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
214             StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
215         }));
216         msg.push((format!("`{}", found_extra), Style::NoStyle));
217
218         // For now, just attach these as notes.
219         self.highlighted_note(msg);
220         self
221     }
222
223     pub fn note_trait_signature(&mut self, name: String, signature: String) -> &mut Self {
224         self.highlighted_note(vec![
225             (format!("`{}` from trait: `", name), Style::NoStyle),
226             (signature, Style::Highlight),
227             ("`".to_string(), Style::NoStyle),
228         ]);
229         self
230     }
231
232     pub fn note(&mut self, msg: &str) -> &mut Self {
233         self.sub(Level::Note, msg, MultiSpan::new(), None);
234         self
235     }
236
237     pub fn highlighted_note(&mut self, msg: Vec<(String, Style)>) -> &mut Self {
238         self.sub_with_highlights(Level::Note, msg, MultiSpan::new(), None);
239         self
240     }
241
242     /// Prints the span with a note above it.
243     pub fn span_note<S: Into<MultiSpan>>(&mut self, sp: S, msg: &str) -> &mut Self {
244         self.sub(Level::Note, msg, sp.into(), None);
245         self
246     }
247
248     pub fn warn(&mut self, msg: &str) -> &mut Self {
249         self.sub(Level::Warning, msg, MultiSpan::new(), None);
250         self
251     }
252
253     /// Prints the span with a warn above it.
254     pub fn span_warn<S: Into<MultiSpan>>(&mut self, sp: S, msg: &str) -> &mut Self {
255         self.sub(Level::Warning, msg, sp.into(), None);
256         self
257     }
258
259     pub fn help(&mut self, msg: &str) -> &mut Self {
260         self.sub(Level::Help, msg, MultiSpan::new(), None);
261         self
262     }
263
264     /// Prints the span with some help above it.
265     pub fn span_help<S: Into<MultiSpan>>(&mut self, sp: S, msg: &str) -> &mut Self {
266         self.sub(Level::Help, msg, sp.into(), None);
267         self
268     }
269
270     pub fn multipart_suggestion(
271         &mut self,
272         msg: &str,
273         suggestion: Vec<(Span, String)>,
274         applicability: Applicability,
275     ) -> &mut Self {
276         self.suggestions.push(CodeSuggestion {
277             substitutions: vec![Substitution {
278                 parts: suggestion
279                     .into_iter()
280                     .map(|(span, snippet)| SubstitutionPart { snippet, span })
281                     .collect(),
282             }],
283             msg: msg.to_owned(),
284             style: SuggestionStyle::ShowCode,
285             applicability,
286         });
287         self
288     }
289
290     /// Prints out a message with for a multipart suggestion without showing the suggested code.
291     ///
292     /// This is intended to be used for suggestions that are obvious in what the changes need to
293     /// be from the message, showing the span label inline would be visually unpleasant
294     /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
295     /// improve understandability.
296     pub fn tool_only_multipart_suggestion(
297         &mut self,
298         msg: &str,
299         suggestion: Vec<(Span, String)>,
300         applicability: Applicability,
301     ) -> &mut Self {
302         self.suggestions.push(CodeSuggestion {
303             substitutions: vec![Substitution {
304                 parts: suggestion
305                     .into_iter()
306                     .map(|(span, snippet)| SubstitutionPart { snippet, span })
307                     .collect(),
308             }],
309             msg: msg.to_owned(),
310             style: SuggestionStyle::CompletelyHidden,
311             applicability,
312         });
313         self
314     }
315
316     /// Prints out a message with a suggested edit of the code.
317     ///
318     /// In case of short messages and a simple suggestion, rustc displays it as a label:
319     ///
320     /// ```text
321     /// try adding parentheses: `(tup.0).1`
322     /// ```
323     ///
324     /// The message
325     ///
326     /// * should not end in any punctuation (a `:` is added automatically)
327     /// * should not be a question (avoid language like "did you mean")
328     /// * should not contain any phrases like "the following", "as shown", etc.
329     /// * may look like "to do xyz, use" or "to do xyz, use abc"
330     /// * may contain a name of a function, variable, or type, but not whole expressions
331     ///
332     /// See `CodeSuggestion` for more information.
333     pub fn span_suggestion(
334         &mut self,
335         sp: Span,
336         msg: &str,
337         suggestion: String,
338         applicability: Applicability,
339     ) -> &mut Self {
340         self.span_suggestion_with_style(
341             sp,
342             msg,
343             suggestion,
344             applicability,
345             SuggestionStyle::ShowCode,
346         );
347         self
348     }
349
350     pub fn span_suggestion_with_style(
351         &mut self,
352         sp: Span,
353         msg: &str,
354         suggestion: String,
355         applicability: Applicability,
356         style: SuggestionStyle,
357     ) -> &mut Self {
358         self.suggestions.push(CodeSuggestion {
359             substitutions: vec![Substitution {
360                 parts: vec![SubstitutionPart { snippet: suggestion, span: sp }],
361             }],
362             msg: msg.to_owned(),
363             style,
364             applicability,
365         });
366         self
367     }
368
369     pub fn span_suggestion_verbose(
370         &mut self,
371         sp: Span,
372         msg: &str,
373         suggestion: String,
374         applicability: Applicability,
375     ) -> &mut Self {
376         self.span_suggestion_with_style(
377             sp,
378             msg,
379             suggestion,
380             applicability,
381             SuggestionStyle::ShowAlways,
382         );
383         self
384     }
385
386     /// Prints out a message with multiple suggested edits of the code.
387     pub fn span_suggestions(
388         &mut self,
389         sp: Span,
390         msg: &str,
391         suggestions: impl Iterator<Item = String>,
392         applicability: Applicability,
393     ) -> &mut Self {
394         self.suggestions.push(CodeSuggestion {
395             substitutions: suggestions
396                 .map(|snippet| Substitution { parts: vec![SubstitutionPart { snippet, span: sp }] })
397                 .collect(),
398             msg: msg.to_owned(),
399             style: SuggestionStyle::ShowCode,
400             applicability,
401         });
402         self
403     }
404
405     /// Prints out a message with a suggested edit of the code. If the suggestion is presented
406     /// inline, it will only show the message and not the suggestion.
407     ///
408     /// See `CodeSuggestion` for more information.
409     pub fn span_suggestion_short(
410         &mut self,
411         sp: Span,
412         msg: &str,
413         suggestion: String,
414         applicability: Applicability,
415     ) -> &mut Self {
416         self.span_suggestion_with_style(
417             sp,
418             msg,
419             suggestion,
420             applicability,
421             SuggestionStyle::HideCodeInline,
422         );
423         self
424     }
425
426     /// Prints out a message with for a suggestion without showing the suggested code.
427     ///
428     /// This is intended to be used for suggestions that are obvious in what the changes need to
429     /// be from the message, showing the span label inline would be visually unpleasant
430     /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
431     /// improve understandability.
432     pub fn span_suggestion_hidden(
433         &mut self,
434         sp: Span,
435         msg: &str,
436         suggestion: String,
437         applicability: Applicability,
438     ) -> &mut Self {
439         self.span_suggestion_with_style(
440             sp,
441             msg,
442             suggestion,
443             applicability,
444             SuggestionStyle::HideCodeAlways,
445         );
446         self
447     }
448
449     /// Adds a suggestion to the json output, but otherwise remains silent/undisplayed in the cli.
450     ///
451     /// This is intended to be used for suggestions that are *very* obvious in what the changes
452     /// need to be from the message, but we still want other tools to be able to apply them.
453     pub fn tool_only_span_suggestion(
454         &mut self,
455         sp: Span,
456         msg: &str,
457         suggestion: String,
458         applicability: Applicability,
459     ) -> &mut Self {
460         self.span_suggestion_with_style(
461             sp,
462             msg,
463             suggestion,
464             applicability,
465             SuggestionStyle::CompletelyHidden,
466         );
467         self
468     }
469
470     pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self {
471         self.span = sp.into();
472         if let Some(span) = self.span.primary_span() {
473             self.sort_span = span;
474         }
475         self
476     }
477
478     pub fn code(&mut self, s: DiagnosticId) -> &mut Self {
479         self.code = Some(s);
480         self
481     }
482
483     pub fn clear_code(&mut self) -> &mut Self {
484         self.code = None;
485         self
486     }
487
488     pub fn get_code(&self) -> Option<DiagnosticId> {
489         self.code.clone()
490     }
491
492     pub fn set_primary_message<M: Into<String>>(&mut self, msg: M) -> &mut Self {
493         self.message[0] = (msg.into(), Style::NoStyle);
494         self
495     }
496
497     pub fn message(&self) -> String {
498         self.message.iter().map(|i| i.0.as_str()).collect::<String>()
499     }
500
501     pub fn styled_message(&self) -> &Vec<(String, Style)> {
502         &self.message
503     }
504
505     /// Used by a lint. Copies over all details *but* the "main
506     /// message".
507     pub fn copy_details_not_message(&mut self, from: &Diagnostic) {
508         self.span = from.span.clone();
509         self.code = from.code.clone();
510         self.children.extend(from.children.iter().cloned())
511     }
512
513     /// Convenience function for internal use, clients should use one of the
514     /// public methods above.
515     pub fn sub(
516         &mut self,
517         level: Level,
518         message: &str,
519         span: MultiSpan,
520         render_span: Option<MultiSpan>,
521     ) {
522         let sub = SubDiagnostic {
523             level,
524             message: vec![(message.to_owned(), Style::NoStyle)],
525             span,
526             render_span,
527         };
528         self.children.push(sub);
529     }
530
531     /// Convenience function for internal use, clients should use one of the
532     /// public methods above.
533     fn sub_with_highlights(
534         &mut self,
535         level: Level,
536         message: Vec<(String, Style)>,
537         span: MultiSpan,
538         render_span: Option<MultiSpan>,
539     ) {
540         let sub = SubDiagnostic { level, message, span, render_span };
541         self.children.push(sub);
542     }
543 }
544
545 impl SubDiagnostic {
546     pub fn message(&self) -> String {
547         self.message.iter().map(|i| i.0.as_str()).collect::<String>()
548     }
549
550     pub fn styled_message(&self) -> &Vec<(String, Style)> {
551         &self.message
552     }
553 }