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