]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_errors/src/diagnostic.rs
Remove unnecessary .as_ref().
[rust.git] / compiler / rustc_errors / src / diagnostic.rs
1 use crate::snippet::Style;
2 use crate::CodeSuggestion;
3 use crate::Level;
4 use crate::Substitution;
5 use crate::SubstitutionPart;
6 use crate::SuggestionStyle;
7 use crate::ToolMetadata;
8 use rustc_lint_defs::Applicability;
9 use rustc_serialize::json::Json;
10 use rustc_span::edition::LATEST_STABLE_EDITION;
11 use rustc_span::{MultiSpan, Span, DUMMY_SP};
12 use std::fmt;
13 use std::hash::{Hash, Hasher};
14
15 /// Error type for `Diagnostic`'s `suggestions` field, indicating that
16 /// `.disable_suggestions()` was called on the `Diagnostic`.
17 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
18 pub struct SuggestionsDisabled;
19
20 #[must_use]
21 #[derive(Clone, Debug, Encodable, Decodable)]
22 pub struct Diagnostic {
23     // NOTE(eddyb) this is private to disallow arbitrary after-the-fact changes,
24     // outside of what methods in this crate themselves allow.
25     crate level: Level,
26
27     pub message: Vec<(String, Style)>,
28     pub code: Option<DiagnosticId>,
29     pub span: MultiSpan,
30     pub children: Vec<SubDiagnostic>,
31     pub suggestions: Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
32
33     /// This is not used for highlighting or rendering any error message.  Rather, it can be used
34     /// as a sort key to sort a buffer of diagnostics.  By default, it is the primary span of
35     /// `span` if there is one.  Otherwise, it is `DUMMY_SP`.
36     pub sort_span: Span,
37
38     /// If diagnostic is from Lint, custom hash function ignores notes
39     /// otherwise hash is based on the all the fields
40     pub is_lint: bool,
41 }
42
43 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
44 pub enum DiagnosticId {
45     Error(String),
46     Lint { name: String, has_future_breakage: bool, is_force_warn: bool },
47 }
48
49 /// A "sub"-diagnostic attached to a parent diagnostic.
50 /// For example, a note attached to an error.
51 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
52 pub struct SubDiagnostic {
53     pub level: Level,
54     pub message: Vec<(String, Style)>,
55     pub span: MultiSpan,
56     pub render_span: Option<MultiSpan>,
57 }
58
59 #[derive(Debug, PartialEq, Eq)]
60 pub struct DiagnosticStyledString(pub Vec<StringPart>);
61
62 impl DiagnosticStyledString {
63     pub fn new() -> DiagnosticStyledString {
64         DiagnosticStyledString(vec![])
65     }
66     pub fn push_normal<S: Into<String>>(&mut self, t: S) {
67         self.0.push(StringPart::Normal(t.into()));
68     }
69     pub fn push_highlighted<S: Into<String>>(&mut self, t: S) {
70         self.0.push(StringPart::Highlighted(t.into()));
71     }
72     pub fn push<S: Into<String>>(&mut self, t: S, highlight: bool) {
73         if highlight {
74             self.push_highlighted(t);
75         } else {
76             self.push_normal(t);
77         }
78     }
79     pub fn normal<S: Into<String>>(t: S) -> DiagnosticStyledString {
80         DiagnosticStyledString(vec![StringPart::Normal(t.into())])
81     }
82
83     pub fn highlighted<S: Into<String>>(t: S) -> DiagnosticStyledString {
84         DiagnosticStyledString(vec![StringPart::Highlighted(t.into())])
85     }
86
87     pub fn content(&self) -> String {
88         self.0.iter().map(|x| x.content()).collect::<String>()
89     }
90 }
91
92 #[derive(Debug, PartialEq, Eq)]
93 pub enum StringPart {
94     Normal(String),
95     Highlighted(String),
96 }
97
98 impl StringPart {
99     pub fn content(&self) -> &str {
100         match self {
101             &StringPart::Normal(ref s) | &StringPart::Highlighted(ref s) => s,
102         }
103     }
104 }
105
106 impl Diagnostic {
107     pub fn new(level: Level, message: &str) -> Self {
108         Diagnostic::new_with_code(level, None, message)
109     }
110
111     pub fn new_with_code(level: Level, code: Option<DiagnosticId>, message: &str) -> Self {
112         Diagnostic {
113             level,
114             message: vec![(message.to_owned(), Style::NoStyle)],
115             code,
116             span: MultiSpan::new(),
117             children: vec![],
118             suggestions: Ok(vec![]),
119             sort_span: DUMMY_SP,
120             is_lint: false,
121         }
122     }
123
124     #[inline(always)]
125     pub fn level(&self) -> Level {
126         self.level
127     }
128
129     pub fn is_error(&self) -> bool {
130         match self.level {
131             Level::Bug
132             | Level::DelayedBug
133             | Level::Fatal
134             | Level::Error { .. }
135             | Level::FailureNote => true,
136
137             Level::Warning | Level::Note | Level::Help | Level::Allow | Level::Expect(_) => false,
138         }
139     }
140
141     pub fn has_future_breakage(&self) -> bool {
142         match self.code {
143             Some(DiagnosticId::Lint { has_future_breakage, .. }) => has_future_breakage,
144             _ => false,
145         }
146     }
147
148     pub fn is_force_warn(&self) -> bool {
149         match self.code {
150             Some(DiagnosticId::Lint { is_force_warn, .. }) => is_force_warn,
151             _ => false,
152         }
153     }
154
155     /// Delay emission of this diagnostic as a bug.
156     ///
157     /// This can be useful in contexts where an error indicates a bug but
158     /// typically this only happens when other compilation errors have already
159     /// happened. In those cases this can be used to defer emission of this
160     /// diagnostic as a bug in the compiler only if no other errors have been
161     /// emitted.
162     ///
163     /// In the meantime, though, callsites are required to deal with the "bug"
164     /// locally in whichever way makes the most sense.
165     #[track_caller]
166     pub fn downgrade_to_delayed_bug(&mut self) -> &mut Self {
167         assert!(
168             self.is_error(),
169             "downgrade_to_delayed_bug: cannot downgrade {:?} to DelayedBug: not an error",
170             self.level
171         );
172         self.level = Level::DelayedBug;
173
174         self
175     }
176
177     /// Adds a span/label to be included in the resulting snippet.
178     ///
179     /// This is pushed onto the [`MultiSpan`] that was created when the diagnostic
180     /// was first built. That means it will be shown together with the original
181     /// span/label, *not* a span added by one of the `span_{note,warn,help,suggestions}` methods.
182     ///
183     /// This span is *not* considered a ["primary span"][`MultiSpan`]; only
184     /// the `Span` supplied when creating the diagnostic is primary.
185     pub fn span_label<T: Into<String>>(&mut self, span: Span, label: T) -> &mut Self {
186         self.span.push_span_label(span, label.into());
187         self
188     }
189
190     /// Labels all the given spans with the provided label.
191     /// See [`Self::span_label()`] for more information.
192     pub fn span_labels(
193         &mut self,
194         spans: impl IntoIterator<Item = Span>,
195         label: impl AsRef<str>,
196     ) -> &mut Self {
197         let label = label.as_ref();
198         for span in spans {
199             self.span_label(span, label);
200         }
201         self
202     }
203
204     pub fn replace_span_with(&mut self, after: Span) -> &mut Self {
205         let before = self.span.clone();
206         self.set_span(after);
207         for span_label in before.span_labels() {
208             if let Some(label) = span_label.label {
209                 self.span_label(after, label);
210             }
211         }
212         self
213     }
214
215     pub fn note_expected_found(
216         &mut self,
217         expected_label: &dyn fmt::Display,
218         expected: DiagnosticStyledString,
219         found_label: &dyn fmt::Display,
220         found: DiagnosticStyledString,
221     ) -> &mut Self {
222         self.note_expected_found_extra(expected_label, expected, found_label, found, &"", &"")
223     }
224
225     pub fn note_unsuccessful_coercion(
226         &mut self,
227         expected: DiagnosticStyledString,
228         found: DiagnosticStyledString,
229     ) -> &mut Self {
230         let mut msg: Vec<_> =
231             vec![("required when trying to coerce from type `".to_string(), Style::NoStyle)];
232         msg.extend(expected.0.iter().map(|x| match *x {
233             StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
234             StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
235         }));
236         msg.push(("` to type '".to_string(), Style::NoStyle));
237         msg.extend(found.0.iter().map(|x| match *x {
238             StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
239             StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
240         }));
241         msg.push(("`".to_string(), Style::NoStyle));
242
243         // For now, just attach these as notes
244         self.highlighted_note(msg);
245         self
246     }
247
248     pub fn note_expected_found_extra(
249         &mut self,
250         expected_label: &dyn fmt::Display,
251         expected: DiagnosticStyledString,
252         found_label: &dyn fmt::Display,
253         found: DiagnosticStyledString,
254         expected_extra: &dyn fmt::Display,
255         found_extra: &dyn fmt::Display,
256     ) -> &mut Self {
257         let expected_label = expected_label.to_string();
258         let expected_label = if expected_label.is_empty() {
259             "expected".to_string()
260         } else {
261             format!("expected {}", expected_label)
262         };
263         let found_label = found_label.to_string();
264         let found_label = if found_label.is_empty() {
265             "found".to_string()
266         } else {
267             format!("found {}", found_label)
268         };
269         let (found_padding, expected_padding) = if expected_label.len() > found_label.len() {
270             (expected_label.len() - found_label.len(), 0)
271         } else {
272             (0, found_label.len() - expected_label.len())
273         };
274         let mut msg: Vec<_> =
275             vec![(format!("{}{} `", " ".repeat(expected_padding), expected_label), Style::NoStyle)];
276         msg.extend(expected.0.iter().map(|x| match *x {
277             StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
278             StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
279         }));
280         msg.push((format!("`{}\n", expected_extra), Style::NoStyle));
281         msg.push((format!("{}{} `", " ".repeat(found_padding), found_label), Style::NoStyle));
282         msg.extend(found.0.iter().map(|x| match *x {
283             StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
284             StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
285         }));
286         msg.push((format!("`{}", found_extra), Style::NoStyle));
287
288         // For now, just attach these as notes.
289         self.highlighted_note(msg);
290         self
291     }
292
293     pub fn note_trait_signature(&mut self, name: String, signature: String) -> &mut Self {
294         self.highlighted_note(vec![
295             (format!("`{}` from trait: `", name), Style::NoStyle),
296             (signature, Style::Highlight),
297             ("`".to_string(), Style::NoStyle),
298         ]);
299         self
300     }
301
302     /// Add a note attached to this diagnostic.
303     pub fn note(&mut self, msg: &str) -> &mut Self {
304         self.sub(Level::Note, msg, MultiSpan::new(), None);
305         self
306     }
307
308     pub fn highlighted_note(&mut self, msg: Vec<(String, Style)>) -> &mut Self {
309         self.sub_with_highlights(Level::Note, msg, MultiSpan::new(), None);
310         self
311     }
312
313     /// Prints the span with a note above it.
314     /// This is like [`Diagnostic::note()`], but it gets its own span.
315     pub fn span_note<S: Into<MultiSpan>>(&mut self, sp: S, msg: &str) -> &mut Self {
316         self.sub(Level::Note, msg, sp.into(), None);
317         self
318     }
319
320     /// Add a warning attached to this diagnostic.
321     pub fn warn(&mut self, msg: &str) -> &mut Self {
322         self.sub(Level::Warning, msg, MultiSpan::new(), None);
323         self
324     }
325
326     /// Prints the span with a warning above it.
327     /// This is like [`Diagnostic::warn()`], but it gets its own span.
328     pub fn span_warn<S: Into<MultiSpan>>(&mut self, sp: S, msg: &str) -> &mut Self {
329         self.sub(Level::Warning, msg, sp.into(), None);
330         self
331     }
332
333     /// Add a help message attached to this diagnostic.
334     pub fn help(&mut self, msg: &str) -> &mut Self {
335         self.sub(Level::Help, msg, MultiSpan::new(), None);
336         self
337     }
338
339     /// Prints the span with some help above it.
340     /// This is like [`Diagnostic::help()`], but it gets its own span.
341     pub fn span_help<S: Into<MultiSpan>>(&mut self, sp: S, msg: &str) -> &mut Self {
342         self.sub(Level::Help, msg, sp.into(), None);
343         self
344     }
345
346     /// Help the user upgrade to the latest edition.
347     /// This is factored out to make sure it does the right thing with `Cargo.toml`.
348     pub fn help_use_latest_edition(&mut self) -> &mut Self {
349         if std::env::var_os("CARGO").is_some() {
350             self.help(&format!("set `edition = \"{}\"` in `Cargo.toml`", LATEST_STABLE_EDITION));
351         } else {
352             self.help(&format!("pass `--edition {}` to `rustc`", LATEST_STABLE_EDITION));
353         }
354         self.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
355         self
356     }
357
358     /// Disallow attaching suggestions this diagnostic.
359     /// Any suggestions attached e.g. with the `span_suggestion_*` methods
360     /// (before and after the call to `disable_suggestions`) will be ignored.
361     pub fn disable_suggestions(&mut self) -> &mut Self {
362         self.suggestions = Err(SuggestionsDisabled);
363         self
364     }
365
366     /// Helper for pushing to `self.suggestions`, if available (not disable).
367     fn push_suggestion(&mut self, suggestion: CodeSuggestion) {
368         if let Ok(suggestions) = &mut self.suggestions {
369             suggestions.push(suggestion);
370         }
371     }
372
373     /// Show a suggestion that has multiple parts to it.
374     /// In other words, multiple changes need to be applied as part of this suggestion.
375     pub fn multipart_suggestion(
376         &mut self,
377         msg: &str,
378         suggestion: Vec<(Span, String)>,
379         applicability: Applicability,
380     ) -> &mut Self {
381         self.multipart_suggestion_with_style(
382             msg,
383             suggestion,
384             applicability,
385             SuggestionStyle::ShowCode,
386         )
387     }
388
389     /// Show a suggestion that has multiple parts to it, always as it's own subdiagnostic.
390     /// In other words, multiple changes need to be applied as part of this suggestion.
391     pub fn multipart_suggestion_verbose(
392         &mut self,
393         msg: &str,
394         suggestion: Vec<(Span, String)>,
395         applicability: Applicability,
396     ) -> &mut Self {
397         self.multipart_suggestion_with_style(
398             msg,
399             suggestion,
400             applicability,
401             SuggestionStyle::ShowAlways,
402         )
403     }
404     /// [`Diagnostic::multipart_suggestion()`] but you can set the [`SuggestionStyle`].
405     pub fn multipart_suggestion_with_style(
406         &mut self,
407         msg: &str,
408         suggestion: Vec<(Span, String)>,
409         applicability: Applicability,
410         style: SuggestionStyle,
411     ) -> &mut Self {
412         assert!(!suggestion.is_empty());
413         self.push_suggestion(CodeSuggestion {
414             substitutions: vec![Substitution {
415                 parts: suggestion
416                     .into_iter()
417                     .map(|(span, snippet)| SubstitutionPart { snippet, span })
418                     .collect(),
419             }],
420             msg: msg.to_owned(),
421             style,
422             applicability,
423             tool_metadata: Default::default(),
424         });
425         self
426     }
427
428     /// Prints out a message with for a multipart suggestion without showing the suggested code.
429     ///
430     /// This is intended to be used for suggestions that are obvious in what the changes need to
431     /// be from the message, showing the span label inline would be visually unpleasant
432     /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
433     /// improve understandability.
434     pub fn tool_only_multipart_suggestion(
435         &mut self,
436         msg: &str,
437         suggestion: Vec<(Span, String)>,
438         applicability: Applicability,
439     ) -> &mut Self {
440         assert!(!suggestion.is_empty());
441         self.push_suggestion(CodeSuggestion {
442             substitutions: vec![Substitution {
443                 parts: suggestion
444                     .into_iter()
445                     .map(|(span, snippet)| SubstitutionPart { snippet, span })
446                     .collect(),
447             }],
448             msg: msg.to_owned(),
449             style: SuggestionStyle::CompletelyHidden,
450             applicability,
451             tool_metadata: Default::default(),
452         });
453         self
454     }
455
456     /// Prints out a message with a suggested edit of the code.
457     ///
458     /// In case of short messages and a simple suggestion, rustc displays it as a label:
459     ///
460     /// ```text
461     /// try adding parentheses: `(tup.0).1`
462     /// ```
463     ///
464     /// The message
465     ///
466     /// * should not end in any punctuation (a `:` is added automatically)
467     /// * should not be a question (avoid language like "did you mean")
468     /// * should not contain any phrases like "the following", "as shown", etc.
469     /// * may look like "to do xyz, use" or "to do xyz, use abc"
470     /// * may contain a name of a function, variable, or type, but not whole expressions
471     ///
472     /// See `CodeSuggestion` for more information.
473     pub fn span_suggestion(
474         &mut self,
475         sp: Span,
476         msg: &str,
477         suggestion: String,
478         applicability: Applicability,
479     ) -> &mut Self {
480         self.span_suggestion_with_style(
481             sp,
482             msg,
483             suggestion,
484             applicability,
485             SuggestionStyle::ShowCode,
486         );
487         self
488     }
489
490     /// [`Diagnostic::span_suggestion()`] but you can set the [`SuggestionStyle`].
491     pub fn span_suggestion_with_style(
492         &mut self,
493         sp: Span,
494         msg: &str,
495         suggestion: String,
496         applicability: Applicability,
497         style: SuggestionStyle,
498     ) -> &mut Self {
499         self.push_suggestion(CodeSuggestion {
500             substitutions: vec![Substitution {
501                 parts: vec![SubstitutionPart { snippet: suggestion, span: sp }],
502             }],
503             msg: msg.to_owned(),
504             style,
505             applicability,
506             tool_metadata: Default::default(),
507         });
508         self
509     }
510
511     /// Always show the suggested change.
512     pub fn span_suggestion_verbose(
513         &mut self,
514         sp: Span,
515         msg: &str,
516         suggestion: String,
517         applicability: Applicability,
518     ) -> &mut Self {
519         self.span_suggestion_with_style(
520             sp,
521             msg,
522             suggestion,
523             applicability,
524             SuggestionStyle::ShowAlways,
525         );
526         self
527     }
528
529     /// Prints out a message with multiple suggested edits of the code.
530     /// See also [`Diagnostic::span_suggestion()`].
531     pub fn span_suggestions(
532         &mut self,
533         sp: Span,
534         msg: &str,
535         suggestions: impl Iterator<Item = String>,
536         applicability: Applicability,
537     ) -> &mut Self {
538         let mut suggestions: Vec<_> = suggestions.collect();
539         suggestions.sort();
540         let substitutions = suggestions
541             .into_iter()
542             .map(|snippet| Substitution { parts: vec![SubstitutionPart { snippet, span: sp }] })
543             .collect();
544         self.push_suggestion(CodeSuggestion {
545             substitutions,
546             msg: msg.to_owned(),
547             style: SuggestionStyle::ShowCode,
548             applicability,
549             tool_metadata: Default::default(),
550         });
551         self
552     }
553
554     /// Prints out a message with multiple suggested edits of the code.
555     /// See also [`Diagnostic::span_suggestion()`].
556     pub fn multipart_suggestions(
557         &mut self,
558         msg: &str,
559         suggestions: impl Iterator<Item = Vec<(Span, String)>>,
560         applicability: Applicability,
561     ) -> &mut Self {
562         self.push_suggestion(CodeSuggestion {
563             substitutions: suggestions
564                 .map(|sugg| Substitution {
565                     parts: sugg
566                         .into_iter()
567                         .map(|(span, snippet)| SubstitutionPart { snippet, span })
568                         .collect(),
569                 })
570                 .collect(),
571             msg: msg.to_owned(),
572             style: SuggestionStyle::ShowCode,
573             applicability,
574             tool_metadata: Default::default(),
575         });
576         self
577     }
578     /// Prints out a message with a suggested edit of the code. If the suggestion is presented
579     /// inline, it will only show the message and not the suggestion.
580     ///
581     /// See `CodeSuggestion` for more information.
582     pub fn span_suggestion_short(
583         &mut self,
584         sp: Span,
585         msg: &str,
586         suggestion: String,
587         applicability: Applicability,
588     ) -> &mut Self {
589         self.span_suggestion_with_style(
590             sp,
591             msg,
592             suggestion,
593             applicability,
594             SuggestionStyle::HideCodeInline,
595         );
596         self
597     }
598
599     /// Prints out a message for a suggestion without showing the suggested code.
600     ///
601     /// This is intended to be used for suggestions that are obvious in what the changes need to
602     /// be from the message, showing the span label inline would be visually unpleasant
603     /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
604     /// improve understandability.
605     pub fn span_suggestion_hidden(
606         &mut self,
607         sp: Span,
608         msg: &str,
609         suggestion: String,
610         applicability: Applicability,
611     ) -> &mut Self {
612         self.span_suggestion_with_style(
613             sp,
614             msg,
615             suggestion,
616             applicability,
617             SuggestionStyle::HideCodeAlways,
618         );
619         self
620     }
621
622     /// Adds a suggestion to the JSON output that will not be shown in the CLI.
623     ///
624     /// This is intended to be used for suggestions that are *very* obvious in what the changes
625     /// need to be from the message, but we still want other tools to be able to apply them.
626     pub fn tool_only_span_suggestion(
627         &mut self,
628         sp: Span,
629         msg: &str,
630         suggestion: String,
631         applicability: Applicability,
632     ) -> &mut Self {
633         self.span_suggestion_with_style(
634             sp,
635             msg,
636             suggestion,
637             applicability,
638             SuggestionStyle::CompletelyHidden,
639         );
640         self
641     }
642
643     /// Adds a suggestion intended only for a tool. The intent is that the metadata encodes
644     /// the suggestion in a tool-specific way, as it may not even directly involve Rust code.
645     pub fn tool_only_suggestion_with_metadata(
646         &mut self,
647         msg: &str,
648         applicability: Applicability,
649         tool_metadata: Json,
650     ) {
651         self.push_suggestion(CodeSuggestion {
652             substitutions: vec![],
653             msg: msg.to_owned(),
654             style: SuggestionStyle::CompletelyHidden,
655             applicability,
656             tool_metadata: ToolMetadata::new(tool_metadata),
657         })
658     }
659
660     pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self {
661         self.span = sp.into();
662         if let Some(span) = self.span.primary_span() {
663             self.sort_span = span;
664         }
665         self
666     }
667
668     pub fn set_is_lint(&mut self) -> &mut Self {
669         self.is_lint = true;
670         self
671     }
672
673     pub fn code(&mut self, s: DiagnosticId) -> &mut Self {
674         self.code = Some(s);
675         self
676     }
677
678     pub fn clear_code(&mut self) -> &mut Self {
679         self.code = None;
680         self
681     }
682
683     pub fn get_code(&self) -> Option<DiagnosticId> {
684         self.code.clone()
685     }
686
687     pub fn set_primary_message<M: Into<String>>(&mut self, msg: M) -> &mut Self {
688         self.message[0] = (msg.into(), Style::NoStyle);
689         self
690     }
691
692     pub fn message(&self) -> String {
693         self.message.iter().map(|i| i.0.as_str()).collect::<String>()
694     }
695
696     pub fn styled_message(&self) -> &Vec<(String, Style)> {
697         &self.message
698     }
699
700     /// Convenience function for internal use, clients should use one of the
701     /// public methods above.
702     ///
703     /// Used by `proc_macro_server` for implementing `server::Diagnostic`.
704     pub fn sub(
705         &mut self,
706         level: Level,
707         message: &str,
708         span: MultiSpan,
709         render_span: Option<MultiSpan>,
710     ) {
711         let sub = SubDiagnostic {
712             level,
713             message: vec![(message.to_owned(), Style::NoStyle)],
714             span,
715             render_span,
716         };
717         self.children.push(sub);
718     }
719
720     /// Convenience function for internal use, clients should use one of the
721     /// public methods above.
722     fn sub_with_highlights(
723         &mut self,
724         level: Level,
725         message: Vec<(String, Style)>,
726         span: MultiSpan,
727         render_span: Option<MultiSpan>,
728     ) {
729         let sub = SubDiagnostic { level, message, span, render_span };
730         self.children.push(sub);
731     }
732
733     /// Fields used for Hash, and PartialEq trait
734     fn keys(
735         &self,
736     ) -> (
737         &Level,
738         &Vec<(String, Style)>,
739         &Option<DiagnosticId>,
740         &MultiSpan,
741         &Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
742         Option<&Vec<SubDiagnostic>>,
743     ) {
744         (
745             &self.level,
746             &self.message,
747             &self.code,
748             &self.span,
749             &self.suggestions,
750             (if self.is_lint { None } else { Some(&self.children) }),
751         )
752     }
753 }
754
755 impl Hash for Diagnostic {
756     fn hash<H>(&self, state: &mut H)
757     where
758         H: Hasher,
759     {
760         self.keys().hash(state);
761     }
762 }
763
764 impl PartialEq for Diagnostic {
765     fn eq(&self, other: &Self) -> bool {
766         self.keys() == other.keys()
767     }
768 }
769
770 impl SubDiagnostic {
771     pub fn message(&self) -> String {
772         self.message.iter().map(|i| i.0.as_str()).collect::<String>()
773     }
774
775     pub fn styled_message(&self) -> &Vec<(String, Style)> {
776         &self.message
777     }
778 }