]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_errors/src/diagnostic.rs
Rollup merge of #101343 - diminishedprime:patch-3, r=tmandry
[rust.git] / compiler / rustc_errors / src / diagnostic.rs
1 use crate::snippet::Style;
2 use crate::{
3     CodeSuggestion, DiagnosticMessage, EmissionGuarantee, Level, LintDiagnosticBuilder, MultiSpan,
4     SubdiagnosticMessage, Substitution, SubstitutionPart, SuggestionStyle,
5 };
6 use rustc_data_structures::fx::FxHashMap;
7 use rustc_error_messages::FluentValue;
8 use rustc_hir as hir;
9 use rustc_lint_defs::{Applicability, LintExpectationId};
10 use rustc_span::edition::LATEST_STABLE_EDITION;
11 use rustc_span::symbol::{Ident, MacroRulesNormalizedIdent, Symbol};
12 use rustc_span::{edition::Edition, Span, DUMMY_SP};
13 use rustc_target::spec::PanicStrategy;
14 use std::borrow::Cow;
15 use std::fmt;
16 use std::hash::{Hash, Hasher};
17 use std::path::{Path, PathBuf};
18
19 /// Error type for `Diagnostic`'s `suggestions` field, indicating that
20 /// `.disable_suggestions()` was called on the `Diagnostic`.
21 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
22 pub struct SuggestionsDisabled;
23
24 /// Simplified version of `FluentArg` that can implement `Encodable` and `Decodable`. Collection of
25 /// `DiagnosticArg` are converted to `FluentArgs` (consuming the collection) at the start of
26 /// diagnostic emission.
27 pub type DiagnosticArg<'source> = (Cow<'source, str>, DiagnosticArgValue<'source>);
28
29 /// Simplified version of `FluentValue` that can implement `Encodable` and `Decodable`. Converted
30 /// to a `FluentValue` by the emitter to be used in diagnostic translation.
31 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
32 pub enum DiagnosticArgValue<'source> {
33     Str(Cow<'source, str>),
34     Number(usize),
35 }
36
37 /// Converts a value of a type into a `DiagnosticArg` (typically a field of a `SessionDiagnostic`
38 /// struct). Implemented as a custom trait rather than `From` so that it is implemented on the type
39 /// being converted rather than on `DiagnosticArgValue`, which enables types from other `rustc_*`
40 /// crates to implement this.
41 pub trait IntoDiagnosticArg {
42     fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static>;
43 }
44
45 pub struct DiagnosticArgFromDisplay<'a>(pub &'a dyn fmt::Display);
46
47 impl IntoDiagnosticArg for DiagnosticArgFromDisplay<'_> {
48     fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
49         self.0.to_string().into_diagnostic_arg()
50     }
51 }
52
53 impl<'a> From<&'a dyn fmt::Display> for DiagnosticArgFromDisplay<'a> {
54     fn from(t: &'a dyn fmt::Display) -> Self {
55         DiagnosticArgFromDisplay(t)
56     }
57 }
58
59 impl<'a, T: fmt::Display> From<&'a T> for DiagnosticArgFromDisplay<'a> {
60     fn from(t: &'a T) -> Self {
61         DiagnosticArgFromDisplay(t)
62     }
63 }
64
65 macro_rules! into_diagnostic_arg_using_display {
66     ($( $ty:ty ),+ $(,)?) => {
67         $(
68             impl IntoDiagnosticArg for $ty {
69                 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
70                     self.to_string().into_diagnostic_arg()
71                 }
72             }
73         )+
74     }
75 }
76
77 into_diagnostic_arg_using_display!(
78     i8,
79     u8,
80     i16,
81     u16,
82     i32,
83     u32,
84     i64,
85     u64,
86     i128,
87     u128,
88     std::io::Error,
89     std::num::NonZeroU32,
90     hir::Target,
91     Edition,
92     Ident,
93     MacroRulesNormalizedIdent,
94 );
95
96 impl IntoDiagnosticArg for bool {
97     fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
98         if self {
99             DiagnosticArgValue::Str(Cow::Borrowed("true"))
100         } else {
101             DiagnosticArgValue::Str(Cow::Borrowed("false"))
102         }
103     }
104 }
105
106 impl IntoDiagnosticArg for char {
107     fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
108         DiagnosticArgValue::Str(Cow::Owned(format!("{:?}", self)))
109     }
110 }
111
112 impl IntoDiagnosticArg for Symbol {
113     fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
114         self.to_ident_string().into_diagnostic_arg()
115     }
116 }
117
118 impl<'a> IntoDiagnosticArg for &'a str {
119     fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
120         self.to_string().into_diagnostic_arg()
121     }
122 }
123
124 impl IntoDiagnosticArg for String {
125     fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
126         DiagnosticArgValue::Str(Cow::Owned(self))
127     }
128 }
129
130 impl<'a> IntoDiagnosticArg for &'a Path {
131     fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
132         DiagnosticArgValue::Str(Cow::Owned(self.display().to_string()))
133     }
134 }
135
136 impl IntoDiagnosticArg for PathBuf {
137     fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
138         DiagnosticArgValue::Str(Cow::Owned(self.display().to_string()))
139     }
140 }
141
142 impl IntoDiagnosticArg for usize {
143     fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
144         DiagnosticArgValue::Number(self)
145     }
146 }
147
148 impl IntoDiagnosticArg for PanicStrategy {
149     fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
150         DiagnosticArgValue::Str(Cow::Owned(self.desc().to_string()))
151     }
152 }
153
154 impl<'source> Into<FluentValue<'source>> for DiagnosticArgValue<'source> {
155     fn into(self) -> FluentValue<'source> {
156         match self {
157             DiagnosticArgValue::Str(s) => From::from(s),
158             DiagnosticArgValue::Number(n) => From::from(n),
159         }
160     }
161 }
162
163 impl IntoDiagnosticArg for hir::ConstContext {
164     fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
165         DiagnosticArgValue::Str(Cow::Borrowed(match self {
166             hir::ConstContext::ConstFn => "constant function",
167             hir::ConstContext::Static(_) => "static",
168             hir::ConstContext::Const => "constant",
169         }))
170     }
171 }
172
173 /// Trait implemented by error types. This should not be implemented manually. Instead, use
174 /// `#[derive(SessionSubdiagnostic)]` -- see [rustc_macros::SessionSubdiagnostic].
175 #[rustc_diagnostic_item = "AddSubdiagnostic"]
176 pub trait AddSubdiagnostic {
177     /// Add a subdiagnostic to an existing diagnostic.
178     fn add_to_diagnostic(self, diag: &mut Diagnostic);
179 }
180
181 /// Trait implemented by lint types. This should not be implemented manually. Instead, use
182 /// `#[derive(LintDiagnostic)]` -- see [rustc_macros::LintDiagnostic].
183 #[rustc_diagnostic_item = "DecorateLint"]
184 pub trait DecorateLint<'a, G: EmissionGuarantee> {
185     /// Decorate and emit a lint.
186     fn decorate_lint(self, diag: LintDiagnosticBuilder<'a, G>);
187 }
188
189 #[must_use]
190 #[derive(Clone, Debug, Encodable, Decodable)]
191 pub struct Diagnostic {
192     // NOTE(eddyb) this is private to disallow arbitrary after-the-fact changes,
193     // outside of what methods in this crate themselves allow.
194     pub(crate) level: Level,
195
196     pub message: Vec<(DiagnosticMessage, Style)>,
197     pub code: Option<DiagnosticId>,
198     pub span: MultiSpan,
199     pub children: Vec<SubDiagnostic>,
200     pub suggestions: Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
201     args: Vec<DiagnosticArg<'static>>,
202
203     /// This is not used for highlighting or rendering any error message.  Rather, it can be used
204     /// as a sort key to sort a buffer of diagnostics.  By default, it is the primary span of
205     /// `span` if there is one.  Otherwise, it is `DUMMY_SP`.
206     pub sort_span: Span,
207
208     /// If diagnostic is from Lint, custom hash function ignores notes
209     /// otherwise hash is based on the all the fields
210     pub is_lint: bool,
211 }
212
213 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
214 pub enum DiagnosticId {
215     Error(String),
216     Lint { name: String, has_future_breakage: bool, is_force_warn: bool },
217 }
218
219 /// A "sub"-diagnostic attached to a parent diagnostic.
220 /// For example, a note attached to an error.
221 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
222 pub struct SubDiagnostic {
223     pub level: Level,
224     pub message: Vec<(DiagnosticMessage, Style)>,
225     pub span: MultiSpan,
226     pub render_span: Option<MultiSpan>,
227 }
228
229 #[derive(Debug, PartialEq, Eq)]
230 pub struct DiagnosticStyledString(pub Vec<StringPart>);
231
232 impl DiagnosticStyledString {
233     pub fn new() -> DiagnosticStyledString {
234         DiagnosticStyledString(vec![])
235     }
236     pub fn push_normal<S: Into<String>>(&mut self, t: S) {
237         self.0.push(StringPart::Normal(t.into()));
238     }
239     pub fn push_highlighted<S: Into<String>>(&mut self, t: S) {
240         self.0.push(StringPart::Highlighted(t.into()));
241     }
242     pub fn push<S: Into<String>>(&mut self, t: S, highlight: bool) {
243         if highlight {
244             self.push_highlighted(t);
245         } else {
246             self.push_normal(t);
247         }
248     }
249     pub fn normal<S: Into<String>>(t: S) -> DiagnosticStyledString {
250         DiagnosticStyledString(vec![StringPart::Normal(t.into())])
251     }
252
253     pub fn highlighted<S: Into<String>>(t: S) -> DiagnosticStyledString {
254         DiagnosticStyledString(vec![StringPart::Highlighted(t.into())])
255     }
256
257     pub fn content(&self) -> String {
258         self.0.iter().map(|x| x.content()).collect::<String>()
259     }
260 }
261
262 #[derive(Debug, PartialEq, Eq)]
263 pub enum StringPart {
264     Normal(String),
265     Highlighted(String),
266 }
267
268 impl StringPart {
269     pub fn content(&self) -> &str {
270         match self {
271             &StringPart::Normal(ref s) | &StringPart::Highlighted(ref s) => s,
272         }
273     }
274 }
275
276 impl Diagnostic {
277     pub fn new<M: Into<DiagnosticMessage>>(level: Level, message: M) -> Self {
278         Diagnostic::new_with_code(level, None, message)
279     }
280
281     pub fn new_with_code<M: Into<DiagnosticMessage>>(
282         level: Level,
283         code: Option<DiagnosticId>,
284         message: M,
285     ) -> Self {
286         Diagnostic {
287             level,
288             message: vec![(message.into(), Style::NoStyle)],
289             code,
290             span: MultiSpan::new(),
291             children: vec![],
292             suggestions: Ok(vec![]),
293             args: vec![],
294             sort_span: DUMMY_SP,
295             is_lint: false,
296         }
297     }
298
299     #[inline(always)]
300     pub fn level(&self) -> Level {
301         self.level
302     }
303
304     pub fn is_error(&self) -> bool {
305         match self.level {
306             Level::Bug
307             | Level::DelayedBug
308             | Level::Fatal
309             | Level::Error { .. }
310             | Level::FailureNote => true,
311
312             Level::Warning(_)
313             | Level::Note
314             | Level::OnceNote
315             | Level::Help
316             | Level::Allow
317             | Level::Expect(_) => false,
318         }
319     }
320
321     pub fn update_unstable_expectation_id(
322         &mut self,
323         unstable_to_stable: &FxHashMap<LintExpectationId, LintExpectationId>,
324     ) {
325         if let Level::Expect(expectation_id) | Level::Warning(Some(expectation_id)) =
326             &mut self.level
327         {
328             if expectation_id.is_stable() {
329                 return;
330             }
331
332             // The unstable to stable map only maps the unstable `AttrId` to a stable `HirId` with an attribute index.
333             // The lint index inside the attribute is manually transferred here.
334             let lint_index = expectation_id.get_lint_index();
335             expectation_id.set_lint_index(None);
336             let mut stable_id = *unstable_to_stable
337                 .get(&expectation_id)
338                 .expect("each unstable `LintExpectationId` must have a matching stable id");
339
340             stable_id.set_lint_index(lint_index);
341             *expectation_id = stable_id;
342         }
343     }
344
345     pub fn has_future_breakage(&self) -> bool {
346         match self.code {
347             Some(DiagnosticId::Lint { has_future_breakage, .. }) => has_future_breakage,
348             _ => false,
349         }
350     }
351
352     pub fn is_force_warn(&self) -> bool {
353         match self.code {
354             Some(DiagnosticId::Lint { is_force_warn, .. }) => is_force_warn,
355             _ => false,
356         }
357     }
358
359     /// Delay emission of this diagnostic as a bug.
360     ///
361     /// This can be useful in contexts where an error indicates a bug but
362     /// typically this only happens when other compilation errors have already
363     /// happened. In those cases this can be used to defer emission of this
364     /// diagnostic as a bug in the compiler only if no other errors have been
365     /// emitted.
366     ///
367     /// In the meantime, though, callsites are required to deal with the "bug"
368     /// locally in whichever way makes the most sense.
369     #[track_caller]
370     pub fn downgrade_to_delayed_bug(&mut self) -> &mut Self {
371         assert!(
372             self.is_error(),
373             "downgrade_to_delayed_bug: cannot downgrade {:?} to DelayedBug: not an error",
374             self.level
375         );
376         self.level = Level::DelayedBug;
377
378         self
379     }
380
381     /// Adds a span/label to be included in the resulting snippet.
382     ///
383     /// This is pushed onto the [`MultiSpan`] that was created when the diagnostic
384     /// was first built. That means it will be shown together with the original
385     /// span/label, *not* a span added by one of the `span_{note,warn,help,suggestions}` methods.
386     ///
387     /// This span is *not* considered a ["primary span"][`MultiSpan`]; only
388     /// the `Span` supplied when creating the diagnostic is primary.
389     #[rustc_lint_diagnostics]
390     pub fn span_label(&mut self, span: Span, label: impl Into<SubdiagnosticMessage>) -> &mut Self {
391         self.span.push_span_label(span, self.subdiagnostic_message_to_diagnostic_message(label));
392         self
393     }
394
395     /// Labels all the given spans with the provided label.
396     /// See [`Self::span_label()`] for more information.
397     pub fn span_labels(
398         &mut self,
399         spans: impl IntoIterator<Item = Span>,
400         label: impl AsRef<str>,
401     ) -> &mut Self {
402         let label = label.as_ref();
403         for span in spans {
404             self.span_label(span, label);
405         }
406         self
407     }
408
409     pub fn replace_span_with(&mut self, after: Span) -> &mut Self {
410         let before = self.span.clone();
411         self.set_span(after);
412         for span_label in before.span_labels() {
413             if let Some(label) = span_label.label {
414                 self.span.push_span_label(after, label);
415             }
416         }
417         self
418     }
419
420     pub fn note_expected_found(
421         &mut self,
422         expected_label: &dyn fmt::Display,
423         expected: DiagnosticStyledString,
424         found_label: &dyn fmt::Display,
425         found: DiagnosticStyledString,
426     ) -> &mut Self {
427         self.note_expected_found_extra(expected_label, expected, found_label, found, &"", &"")
428     }
429
430     pub fn note_unsuccessful_coercion(
431         &mut self,
432         expected: DiagnosticStyledString,
433         found: DiagnosticStyledString,
434     ) -> &mut Self {
435         let mut msg: Vec<_> = vec![("required when trying to coerce from type `", Style::NoStyle)];
436         msg.extend(expected.0.iter().map(|x| match *x {
437             StringPart::Normal(ref s) => (s.as_str(), Style::NoStyle),
438             StringPart::Highlighted(ref s) => (s.as_str(), Style::Highlight),
439         }));
440         msg.push(("` to type '", Style::NoStyle));
441         msg.extend(found.0.iter().map(|x| match *x {
442             StringPart::Normal(ref s) => (s.as_str(), Style::NoStyle),
443             StringPart::Highlighted(ref s) => (s.as_str(), Style::Highlight),
444         }));
445         msg.push(("`", Style::NoStyle));
446
447         // For now, just attach these as notes
448         self.highlighted_note(msg);
449         self
450     }
451
452     pub fn note_expected_found_extra(
453         &mut self,
454         expected_label: &dyn fmt::Display,
455         expected: DiagnosticStyledString,
456         found_label: &dyn fmt::Display,
457         found: DiagnosticStyledString,
458         expected_extra: &dyn fmt::Display,
459         found_extra: &dyn fmt::Display,
460     ) -> &mut Self {
461         let expected_label = expected_label.to_string();
462         let expected_label = if expected_label.is_empty() {
463             "expected".to_string()
464         } else {
465             format!("expected {}", expected_label)
466         };
467         let found_label = found_label.to_string();
468         let found_label = if found_label.is_empty() {
469             "found".to_string()
470         } else {
471             format!("found {}", found_label)
472         };
473         let (found_padding, expected_padding) = if expected_label.len() > found_label.len() {
474             (expected_label.len() - found_label.len(), 0)
475         } else {
476             (0, found_label.len() - expected_label.len())
477         };
478         let mut msg: Vec<_> =
479             vec![(format!("{}{} `", " ".repeat(expected_padding), expected_label), Style::NoStyle)];
480         msg.extend(expected.0.iter().map(|x| match *x {
481             StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
482             StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
483         }));
484         msg.push((format!("`{}\n", expected_extra), Style::NoStyle));
485         msg.push((format!("{}{} `", " ".repeat(found_padding), found_label), Style::NoStyle));
486         msg.extend(found.0.iter().map(|x| match *x {
487             StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
488             StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
489         }));
490         msg.push((format!("`{}", found_extra), Style::NoStyle));
491
492         // For now, just attach these as notes.
493         self.highlighted_note(msg);
494         self
495     }
496
497     pub fn note_trait_signature(&mut self, name: Symbol, signature: String) -> &mut Self {
498         self.highlighted_note(vec![
499             (format!("`{}` from trait: `", name), Style::NoStyle),
500             (signature, Style::Highlight),
501             ("`".to_string(), Style::NoStyle),
502         ]);
503         self
504     }
505
506     /// Add a note attached to this diagnostic.
507     #[rustc_lint_diagnostics]
508     pub fn note(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
509         self.sub(Level::Note, msg, MultiSpan::new(), None);
510         self
511     }
512
513     pub fn highlighted_note<M: Into<SubdiagnosticMessage>>(
514         &mut self,
515         msg: Vec<(M, Style)>,
516     ) -> &mut Self {
517         self.sub_with_highlights(Level::Note, msg, MultiSpan::new(), None);
518         self
519     }
520
521     /// Prints the span with a note above it.
522     /// This is like [`Diagnostic::note()`], but it gets its own span.
523     pub fn note_once(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
524         self.sub(Level::OnceNote, msg, MultiSpan::new(), None);
525         self
526     }
527
528     /// Prints the span with a note above it.
529     /// This is like [`Diagnostic::note()`], but it gets its own span.
530     #[rustc_lint_diagnostics]
531     pub fn span_note<S: Into<MultiSpan>>(
532         &mut self,
533         sp: S,
534         msg: impl Into<SubdiagnosticMessage>,
535     ) -> &mut Self {
536         self.sub(Level::Note, msg, sp.into(), None);
537         self
538     }
539
540     /// Prints the span with a note above it.
541     /// This is like [`Diagnostic::note()`], but it gets its own span.
542     pub fn span_note_once<S: Into<MultiSpan>>(
543         &mut self,
544         sp: S,
545         msg: impl Into<SubdiagnosticMessage>,
546     ) -> &mut Self {
547         self.sub(Level::OnceNote, msg, sp.into(), None);
548         self
549     }
550
551     /// Add a warning attached to this diagnostic.
552     #[rustc_lint_diagnostics]
553     pub fn warn(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
554         self.sub(Level::Warning(None), msg, MultiSpan::new(), None);
555         self
556     }
557
558     /// Prints the span with a warning above it.
559     /// This is like [`Diagnostic::warn()`], but it gets its own span.
560     #[rustc_lint_diagnostics]
561     pub fn span_warn<S: Into<MultiSpan>>(
562         &mut self,
563         sp: S,
564         msg: impl Into<SubdiagnosticMessage>,
565     ) -> &mut Self {
566         self.sub(Level::Warning(None), msg, sp.into(), None);
567         self
568     }
569
570     /// Add a help message attached to this diagnostic.
571     #[rustc_lint_diagnostics]
572     pub fn help(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
573         self.sub(Level::Help, msg, MultiSpan::new(), None);
574         self
575     }
576
577     /// Add a help message attached to this diagnostic with a customizable highlighted message.
578     pub fn highlighted_help(&mut self, msg: Vec<(String, Style)>) -> &mut Self {
579         self.sub_with_highlights(Level::Help, msg, MultiSpan::new(), None);
580         self
581     }
582
583     /// Prints the span with some help above it.
584     /// This is like [`Diagnostic::help()`], but it gets its own span.
585     #[rustc_lint_diagnostics]
586     pub fn span_help<S: Into<MultiSpan>>(
587         &mut self,
588         sp: S,
589         msg: impl Into<SubdiagnosticMessage>,
590     ) -> &mut Self {
591         self.sub(Level::Help, msg, sp.into(), None);
592         self
593     }
594
595     /// Help the user upgrade to the latest edition.
596     /// This is factored out to make sure it does the right thing with `Cargo.toml`.
597     pub fn help_use_latest_edition(&mut self) -> &mut Self {
598         if std::env::var_os("CARGO").is_some() {
599             self.help(&format!("set `edition = \"{}\"` in `Cargo.toml`", LATEST_STABLE_EDITION));
600         } else {
601             self.help(&format!("pass `--edition {}` to `rustc`", LATEST_STABLE_EDITION));
602         }
603         self.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
604         self
605     }
606
607     /// Disallow attaching suggestions this diagnostic.
608     /// Any suggestions attached e.g. with the `span_suggestion_*` methods
609     /// (before and after the call to `disable_suggestions`) will be ignored.
610     pub fn disable_suggestions(&mut self) -> &mut Self {
611         self.suggestions = Err(SuggestionsDisabled);
612         self
613     }
614
615     /// Clear any existing suggestions.
616     pub fn clear_suggestions(&mut self) -> &mut Self {
617         if let Ok(suggestions) = &mut self.suggestions {
618             suggestions.clear();
619         }
620         self
621     }
622
623     /// Helper for pushing to `self.suggestions`, if available (not disable).
624     fn push_suggestion(&mut self, suggestion: CodeSuggestion) {
625         if let Ok(suggestions) = &mut self.suggestions {
626             suggestions.push(suggestion);
627         }
628     }
629
630     /// Show a suggestion that has multiple parts to it.
631     /// In other words, multiple changes need to be applied as part of this suggestion.
632     pub fn multipart_suggestion(
633         &mut self,
634         msg: impl Into<SubdiagnosticMessage>,
635         suggestion: Vec<(Span, String)>,
636         applicability: Applicability,
637     ) -> &mut Self {
638         self.multipart_suggestion_with_style(
639             msg,
640             suggestion,
641             applicability,
642             SuggestionStyle::ShowCode,
643         )
644     }
645
646     /// Show a suggestion that has multiple parts to it, always as it's own subdiagnostic.
647     /// In other words, multiple changes need to be applied as part of this suggestion.
648     pub fn multipart_suggestion_verbose(
649         &mut self,
650         msg: impl Into<SubdiagnosticMessage>,
651         suggestion: Vec<(Span, String)>,
652         applicability: Applicability,
653     ) -> &mut Self {
654         self.multipart_suggestion_with_style(
655             msg,
656             suggestion,
657             applicability,
658             SuggestionStyle::ShowAlways,
659         )
660     }
661     /// [`Diagnostic::multipart_suggestion()`] but you can set the [`SuggestionStyle`].
662     pub fn multipart_suggestion_with_style(
663         &mut self,
664         msg: impl Into<SubdiagnosticMessage>,
665         suggestion: Vec<(Span, String)>,
666         applicability: Applicability,
667         style: SuggestionStyle,
668     ) -> &mut Self {
669         assert!(!suggestion.is_empty());
670         self.push_suggestion(CodeSuggestion {
671             substitutions: vec![Substitution {
672                 parts: suggestion
673                     .into_iter()
674                     .map(|(span, snippet)| SubstitutionPart { snippet, span })
675                     .collect(),
676             }],
677             msg: self.subdiagnostic_message_to_diagnostic_message(msg),
678             style,
679             applicability,
680         });
681         self
682     }
683
684     /// Prints out a message with for a multipart suggestion without showing the suggested code.
685     ///
686     /// This is intended to be used for suggestions that are obvious in what the changes need to
687     /// be from the message, showing the span label inline would be visually unpleasant
688     /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
689     /// improve understandability.
690     pub fn tool_only_multipart_suggestion(
691         &mut self,
692         msg: impl Into<SubdiagnosticMessage>,
693         suggestion: Vec<(Span, String)>,
694         applicability: Applicability,
695     ) -> &mut Self {
696         self.multipart_suggestion_with_style(
697             msg,
698             suggestion,
699             applicability,
700             SuggestionStyle::CompletelyHidden,
701         )
702     }
703
704     /// Prints out a message with a suggested edit of the code.
705     ///
706     /// In case of short messages and a simple suggestion, rustc displays it as a label:
707     ///
708     /// ```text
709     /// try adding parentheses: `(tup.0).1`
710     /// ```
711     ///
712     /// The message
713     ///
714     /// * should not end in any punctuation (a `:` is added automatically)
715     /// * should not be a question (avoid language like "did you mean")
716     /// * should not contain any phrases like "the following", "as shown", etc.
717     /// * may look like "to do xyz, use" or "to do xyz, use abc"
718     /// * may contain a name of a function, variable, or type, but not whole expressions
719     ///
720     /// See `CodeSuggestion` for more information.
721     pub fn span_suggestion(
722         &mut self,
723         sp: Span,
724         msg: impl Into<SubdiagnosticMessage>,
725         suggestion: impl ToString,
726         applicability: Applicability,
727     ) -> &mut Self {
728         self.span_suggestion_with_style(
729             sp,
730             msg,
731             suggestion,
732             applicability,
733             SuggestionStyle::ShowCode,
734         );
735         self
736     }
737
738     /// [`Diagnostic::span_suggestion()`] but you can set the [`SuggestionStyle`].
739     pub fn span_suggestion_with_style(
740         &mut self,
741         sp: Span,
742         msg: impl Into<SubdiagnosticMessage>,
743         suggestion: impl ToString,
744         applicability: Applicability,
745         style: SuggestionStyle,
746     ) -> &mut Self {
747         self.push_suggestion(CodeSuggestion {
748             substitutions: vec![Substitution {
749                 parts: vec![SubstitutionPart { snippet: suggestion.to_string(), span: sp }],
750             }],
751             msg: self.subdiagnostic_message_to_diagnostic_message(msg),
752             style,
753             applicability,
754         });
755         self
756     }
757
758     /// Always show the suggested change.
759     pub fn span_suggestion_verbose(
760         &mut self,
761         sp: Span,
762         msg: impl Into<SubdiagnosticMessage>,
763         suggestion: impl ToString,
764         applicability: Applicability,
765     ) -> &mut Self {
766         self.span_suggestion_with_style(
767             sp,
768             msg,
769             suggestion,
770             applicability,
771             SuggestionStyle::ShowAlways,
772         );
773         self
774     }
775
776     /// Prints out a message with multiple suggested edits of the code.
777     /// See also [`Diagnostic::span_suggestion()`].
778     pub fn span_suggestions(
779         &mut self,
780         sp: Span,
781         msg: impl Into<SubdiagnosticMessage>,
782         suggestions: impl Iterator<Item = String>,
783         applicability: Applicability,
784     ) -> &mut Self {
785         let mut suggestions: Vec<_> = suggestions.collect();
786         suggestions.sort();
787         let substitutions = suggestions
788             .into_iter()
789             .map(|snippet| Substitution { parts: vec![SubstitutionPart { snippet, span: sp }] })
790             .collect();
791         self.push_suggestion(CodeSuggestion {
792             substitutions,
793             msg: self.subdiagnostic_message_to_diagnostic_message(msg),
794             style: SuggestionStyle::ShowCode,
795             applicability,
796         });
797         self
798     }
799
800     /// Prints out a message with multiple suggested edits of the code.
801     /// See also [`Diagnostic::span_suggestion()`].
802     pub fn multipart_suggestions(
803         &mut self,
804         msg: impl Into<SubdiagnosticMessage>,
805         suggestions: impl Iterator<Item = Vec<(Span, String)>>,
806         applicability: Applicability,
807     ) -> &mut Self {
808         self.push_suggestion(CodeSuggestion {
809             substitutions: suggestions
810                 .map(|sugg| Substitution {
811                     parts: sugg
812                         .into_iter()
813                         .map(|(span, snippet)| SubstitutionPart { snippet, span })
814                         .collect(),
815                 })
816                 .collect(),
817             msg: self.subdiagnostic_message_to_diagnostic_message(msg),
818             style: SuggestionStyle::ShowCode,
819             applicability,
820         });
821         self
822     }
823     /// Prints out a message with a suggested edit of the code. If the suggestion is presented
824     /// inline, it will only show the message and not the suggestion.
825     ///
826     /// See `CodeSuggestion` for more information.
827     pub fn span_suggestion_short(
828         &mut self,
829         sp: Span,
830         msg: impl Into<SubdiagnosticMessage>,
831         suggestion: impl ToString,
832         applicability: Applicability,
833     ) -> &mut Self {
834         self.span_suggestion_with_style(
835             sp,
836             msg,
837             suggestion,
838             applicability,
839             SuggestionStyle::HideCodeInline,
840         );
841         self
842     }
843
844     /// Prints out a message for a suggestion without showing the suggested code.
845     ///
846     /// This is intended to be used for suggestions that are obvious in what the changes need to
847     /// be from the message, showing the span label inline would be visually unpleasant
848     /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
849     /// improve understandability.
850     pub fn span_suggestion_hidden(
851         &mut self,
852         sp: Span,
853         msg: impl Into<SubdiagnosticMessage>,
854         suggestion: impl ToString,
855         applicability: Applicability,
856     ) -> &mut Self {
857         self.span_suggestion_with_style(
858             sp,
859             msg,
860             suggestion,
861             applicability,
862             SuggestionStyle::HideCodeAlways,
863         );
864         self
865     }
866
867     /// Adds a suggestion to the JSON output that will not be shown in the CLI.
868     ///
869     /// This is intended to be used for suggestions that are *very* obvious in what the changes
870     /// need to be from the message, but we still want other tools to be able to apply them.
871     pub fn tool_only_span_suggestion(
872         &mut self,
873         sp: Span,
874         msg: impl Into<SubdiagnosticMessage>,
875         suggestion: impl ToString,
876         applicability: Applicability,
877     ) -> &mut Self {
878         self.span_suggestion_with_style(
879             sp,
880             msg,
881             suggestion,
882             applicability,
883             SuggestionStyle::CompletelyHidden,
884         );
885         self
886     }
887
888     /// Add a subdiagnostic from a type that implements `SessionSubdiagnostic` - see
889     /// [rustc_macros::SessionSubdiagnostic].
890     pub fn subdiagnostic(&mut self, subdiagnostic: impl AddSubdiagnostic) -> &mut Self {
891         subdiagnostic.add_to_diagnostic(self);
892         self
893     }
894
895     pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self {
896         self.span = sp.into();
897         if let Some(span) = self.span.primary_span() {
898             self.sort_span = span;
899         }
900         self
901     }
902
903     pub fn set_is_lint(&mut self) -> &mut Self {
904         self.is_lint = true;
905         self
906     }
907
908     pub fn code(&mut self, s: DiagnosticId) -> &mut Self {
909         self.code = Some(s);
910         self
911     }
912
913     pub fn clear_code(&mut self) -> &mut Self {
914         self.code = None;
915         self
916     }
917
918     pub fn get_code(&self) -> Option<DiagnosticId> {
919         self.code.clone()
920     }
921
922     pub fn set_primary_message(&mut self, msg: impl Into<DiagnosticMessage>) -> &mut Self {
923         self.message[0] = (msg.into(), Style::NoStyle);
924         self
925     }
926
927     pub fn args(&self) -> &[DiagnosticArg<'static>] {
928         &self.args
929     }
930
931     pub fn set_arg(
932         &mut self,
933         name: impl Into<Cow<'static, str>>,
934         arg: impl IntoDiagnosticArg,
935     ) -> &mut Self {
936         self.args.push((name.into(), arg.into_diagnostic_arg()));
937         self
938     }
939
940     pub fn styled_message(&self) -> &[(DiagnosticMessage, Style)] {
941         &self.message
942     }
943
944     /// Helper function that takes a `SubdiagnosticMessage` and returns a `DiagnosticMessage` by
945     /// combining it with the primary message of the diagnostic (if translatable, otherwise it just
946     /// passes the user's string along).
947     fn subdiagnostic_message_to_diagnostic_message(
948         &self,
949         attr: impl Into<SubdiagnosticMessage>,
950     ) -> DiagnosticMessage {
951         let msg =
952             self.message.iter().map(|(msg, _)| msg).next().expect("diagnostic with no messages");
953         msg.with_subdiagnostic_message(attr.into())
954     }
955
956     /// Convenience function for internal use, clients should use one of the
957     /// public methods above.
958     ///
959     /// Used by `proc_macro_server` for implementing `server::Diagnostic`.
960     pub fn sub(
961         &mut self,
962         level: Level,
963         message: impl Into<SubdiagnosticMessage>,
964         span: MultiSpan,
965         render_span: Option<MultiSpan>,
966     ) {
967         let sub = SubDiagnostic {
968             level,
969             message: vec![(
970                 self.subdiagnostic_message_to_diagnostic_message(message),
971                 Style::NoStyle,
972             )],
973             span,
974             render_span,
975         };
976         self.children.push(sub);
977     }
978
979     /// Convenience function for internal use, clients should use one of the
980     /// public methods above.
981     fn sub_with_highlights<M: Into<SubdiagnosticMessage>>(
982         &mut self,
983         level: Level,
984         message: Vec<(M, Style)>,
985         span: MultiSpan,
986         render_span: Option<MultiSpan>,
987     ) {
988         let message = message
989             .into_iter()
990             .map(|m| (self.subdiagnostic_message_to_diagnostic_message(m.0), m.1))
991             .collect();
992         let sub = SubDiagnostic { level, message, span, render_span };
993         self.children.push(sub);
994     }
995
996     /// Fields used for Hash, and PartialEq trait
997     fn keys(
998         &self,
999     ) -> (
1000         &Level,
1001         &[(DiagnosticMessage, Style)],
1002         &Option<DiagnosticId>,
1003         &MultiSpan,
1004         &Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
1005         Option<&[SubDiagnostic]>,
1006     ) {
1007         (
1008             &self.level,
1009             &self.message,
1010             &self.code,
1011             &self.span,
1012             &self.suggestions,
1013             (if self.is_lint { None } else { Some(&self.children) }),
1014         )
1015     }
1016 }
1017
1018 impl Hash for Diagnostic {
1019     fn hash<H>(&self, state: &mut H)
1020     where
1021         H: Hasher,
1022     {
1023         self.keys().hash(state);
1024     }
1025 }
1026
1027 impl PartialEq for Diagnostic {
1028     fn eq(&self, other: &Self) -> bool {
1029         self.keys() == other.keys()
1030     }
1031 }