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