]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_errors/src/diagnostic.rs
Rollup merge of #104839 - HintringerFabian:docs_array_from_fn, r=scottmcm
[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) -> &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                 self.span.push_span_label(after, label);
374             }
375         }
376         self
377     }
378
379     pub fn note_expected_found(
380         &mut self,
381         expected_label: &dyn fmt::Display,
382         expected: DiagnosticStyledString,
383         found_label: &dyn fmt::Display,
384         found: DiagnosticStyledString,
385     ) -> &mut Self {
386         self.note_expected_found_extra(expected_label, expected, found_label, found, &"", &"")
387     }
388
389     pub fn note_unsuccessful_coercion(
390         &mut self,
391         expected: DiagnosticStyledString,
392         found: DiagnosticStyledString,
393     ) -> &mut Self {
394         let mut msg: Vec<_> = vec![("required when trying to coerce from type `", Style::NoStyle)];
395         msg.extend(expected.0.iter().map(|x| match *x {
396             StringPart::Normal(ref s) => (s.as_str(), Style::NoStyle),
397             StringPart::Highlighted(ref s) => (s.as_str(), Style::Highlight),
398         }));
399         msg.push(("` to type '", Style::NoStyle));
400         msg.extend(found.0.iter().map(|x| match *x {
401             StringPart::Normal(ref s) => (s.as_str(), Style::NoStyle),
402             StringPart::Highlighted(ref s) => (s.as_str(), Style::Highlight),
403         }));
404         msg.push(("`", Style::NoStyle));
405
406         // For now, just attach these as notes
407         self.highlighted_note(msg);
408         self
409     }
410
411     pub fn note_expected_found_extra(
412         &mut self,
413         expected_label: &dyn fmt::Display,
414         expected: DiagnosticStyledString,
415         found_label: &dyn fmt::Display,
416         found: DiagnosticStyledString,
417         expected_extra: &dyn fmt::Display,
418         found_extra: &dyn fmt::Display,
419     ) -> &mut Self {
420         let expected_label = expected_label.to_string();
421         let expected_label = if expected_label.is_empty() {
422             "expected".to_string()
423         } else {
424             format!("expected {}", expected_label)
425         };
426         let found_label = found_label.to_string();
427         let found_label = if found_label.is_empty() {
428             "found".to_string()
429         } else {
430             format!("found {}", found_label)
431         };
432         let (found_padding, expected_padding) = if expected_label.len() > found_label.len() {
433             (expected_label.len() - found_label.len(), 0)
434         } else {
435             (0, found_label.len() - expected_label.len())
436         };
437         let mut msg: Vec<_> =
438             vec![(format!("{}{} `", " ".repeat(expected_padding), expected_label), Style::NoStyle)];
439         msg.extend(expected.0.iter().map(|x| match *x {
440             StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
441             StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
442         }));
443         msg.push((format!("`{}\n", expected_extra), Style::NoStyle));
444         msg.push((format!("{}{} `", " ".repeat(found_padding), found_label), Style::NoStyle));
445         msg.extend(found.0.iter().map(|x| match *x {
446             StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
447             StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
448         }));
449         msg.push((format!("`{}", found_extra), Style::NoStyle));
450
451         // For now, just attach these as notes.
452         self.highlighted_note(msg);
453         self
454     }
455
456     pub fn note_trait_signature(&mut self, name: Symbol, signature: String) -> &mut Self {
457         self.highlighted_note(vec![
458             (format!("`{}` from trait: `", name), Style::NoStyle),
459             (signature, Style::Highlight),
460             ("`".to_string(), Style::NoStyle),
461         ]);
462         self
463     }
464
465     /// Add a note attached to this diagnostic.
466     #[rustc_lint_diagnostics]
467     pub fn note(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
468         self.sub(Level::Note, msg, MultiSpan::new(), None);
469         self
470     }
471
472     pub fn highlighted_note<M: Into<SubdiagnosticMessage>>(
473         &mut self,
474         msg: Vec<(M, Style)>,
475     ) -> &mut Self {
476         self.sub_with_highlights(Level::Note, msg, MultiSpan::new(), None);
477         self
478     }
479
480     /// Prints the span with a note above it.
481     /// This is like [`Diagnostic::note()`], but it gets its own span.
482     pub fn note_once(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
483         self.sub(Level::OnceNote, msg, MultiSpan::new(), None);
484         self
485     }
486
487     /// Prints the span with a note above it.
488     /// This is like [`Diagnostic::note()`], but it gets its own span.
489     #[rustc_lint_diagnostics]
490     pub fn span_note<S: Into<MultiSpan>>(
491         &mut self,
492         sp: S,
493         msg: impl Into<SubdiagnosticMessage>,
494     ) -> &mut Self {
495         self.sub(Level::Note, msg, sp.into(), 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 span_note_once<S: Into<MultiSpan>>(
502         &mut self,
503         sp: S,
504         msg: impl Into<SubdiagnosticMessage>,
505     ) -> &mut Self {
506         self.sub(Level::OnceNote, msg, sp.into(), None);
507         self
508     }
509
510     /// Add a warning attached to this diagnostic.
511     #[rustc_lint_diagnostics]
512     pub fn warn(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
513         self.sub(Level::Warning(None), msg, MultiSpan::new(), None);
514         self
515     }
516
517     /// Prints the span with a warning above it.
518     /// This is like [`Diagnostic::warn()`], but it gets its own span.
519     #[rustc_lint_diagnostics]
520     pub fn span_warn<S: Into<MultiSpan>>(
521         &mut self,
522         sp: S,
523         msg: impl Into<SubdiagnosticMessage>,
524     ) -> &mut Self {
525         self.sub(Level::Warning(None), msg, sp.into(), None);
526         self
527     }
528
529     /// Add a help message attached to this diagnostic.
530     #[rustc_lint_diagnostics]
531     pub fn help(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
532         self.sub(Level::Help, msg, MultiSpan::new(), None);
533         self
534     }
535
536     /// Add a help message attached to this diagnostic with a customizable highlighted message.
537     pub fn highlighted_help(&mut self, msg: Vec<(String, Style)>) -> &mut Self {
538         self.sub_with_highlights(Level::Help, msg, MultiSpan::new(), None);
539         self
540     }
541
542     /// Prints the span with some help above it.
543     /// This is like [`Diagnostic::help()`], but it gets its own span.
544     #[rustc_lint_diagnostics]
545     pub fn span_help<S: Into<MultiSpan>>(
546         &mut self,
547         sp: S,
548         msg: impl Into<SubdiagnosticMessage>,
549     ) -> &mut Self {
550         self.sub(Level::Help, msg, sp.into(), None);
551         self
552     }
553
554     /// Help the user upgrade to the latest edition.
555     /// This is factored out to make sure it does the right thing with `Cargo.toml`.
556     pub fn help_use_latest_edition(&mut self) -> &mut Self {
557         if std::env::var_os("CARGO").is_some() {
558             self.help(&format!("set `edition = \"{}\"` in `Cargo.toml`", LATEST_STABLE_EDITION));
559         } else {
560             self.help(&format!("pass `--edition {}` to `rustc`", LATEST_STABLE_EDITION));
561         }
562         self.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
563         self
564     }
565
566     /// Disallow attaching suggestions this diagnostic.
567     /// Any suggestions attached e.g. with the `span_suggestion_*` methods
568     /// (before and after the call to `disable_suggestions`) will be ignored.
569     pub fn disable_suggestions(&mut self) -> &mut Self {
570         self.suggestions = Err(SuggestionsDisabled);
571         self
572     }
573
574     /// Clear any existing suggestions.
575     pub fn clear_suggestions(&mut self) -> &mut Self {
576         if let Ok(suggestions) = &mut self.suggestions {
577             suggestions.clear();
578         }
579         self
580     }
581
582     /// Helper for pushing to `self.suggestions`, if available (not disable).
583     fn push_suggestion(&mut self, suggestion: CodeSuggestion) {
584         if let Ok(suggestions) = &mut self.suggestions {
585             suggestions.push(suggestion);
586         }
587     }
588
589     /// Show a suggestion that has multiple parts to it.
590     /// In other words, multiple changes need to be applied as part of this suggestion.
591     pub fn multipart_suggestion(
592         &mut self,
593         msg: impl Into<SubdiagnosticMessage>,
594         suggestion: Vec<(Span, String)>,
595         applicability: Applicability,
596     ) -> &mut Self {
597         self.multipart_suggestion_with_style(
598             msg,
599             suggestion,
600             applicability,
601             SuggestionStyle::ShowCode,
602         )
603     }
604
605     /// Show a suggestion that has multiple parts to it, always as it's own subdiagnostic.
606     /// In other words, multiple changes need to be applied as part of this suggestion.
607     pub fn multipart_suggestion_verbose(
608         &mut self,
609         msg: impl Into<SubdiagnosticMessage>,
610         suggestion: Vec<(Span, String)>,
611         applicability: Applicability,
612     ) -> &mut Self {
613         self.multipart_suggestion_with_style(
614             msg,
615             suggestion,
616             applicability,
617             SuggestionStyle::ShowAlways,
618         )
619     }
620     /// [`Diagnostic::multipart_suggestion()`] but you can set the [`SuggestionStyle`].
621     pub fn multipart_suggestion_with_style(
622         &mut self,
623         msg: impl Into<SubdiagnosticMessage>,
624         suggestion: Vec<(Span, String)>,
625         applicability: Applicability,
626         style: SuggestionStyle,
627     ) -> &mut Self {
628         assert!(!suggestion.is_empty());
629         debug_assert!(
630             !(suggestion.iter().any(|(sp, text)| sp.is_empty() && text.is_empty())),
631             "Span must not be empty and have no suggestion"
632         );
633
634         self.push_suggestion(CodeSuggestion {
635             substitutions: vec![Substitution {
636                 parts: suggestion
637                     .into_iter()
638                     .map(|(span, snippet)| SubstitutionPart { snippet, span })
639                     .collect(),
640             }],
641             msg: self.subdiagnostic_message_to_diagnostic_message(msg),
642             style,
643             applicability,
644         });
645         self
646     }
647
648     /// Prints out a message with for a multipart suggestion without showing the suggested code.
649     ///
650     /// This is intended to be used for suggestions that are obvious in what the changes need to
651     /// be from the message, showing the span label inline would be visually unpleasant
652     /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
653     /// improve understandability.
654     pub fn tool_only_multipart_suggestion(
655         &mut self,
656         msg: impl Into<SubdiagnosticMessage>,
657         suggestion: Vec<(Span, String)>,
658         applicability: Applicability,
659     ) -> &mut Self {
660         self.multipart_suggestion_with_style(
661             msg,
662             suggestion,
663             applicability,
664             SuggestionStyle::CompletelyHidden,
665         )
666     }
667
668     /// Prints out a message with a suggested edit of the code.
669     ///
670     /// In case of short messages and a simple suggestion, rustc displays it as a label:
671     ///
672     /// ```text
673     /// try adding parentheses: `(tup.0).1`
674     /// ```
675     ///
676     /// The message
677     ///
678     /// * should not end in any punctuation (a `:` is added automatically)
679     /// * should not be a question (avoid language like "did you mean")
680     /// * should not contain any phrases like "the following", "as shown", etc.
681     /// * may look like "to do xyz, use" or "to do xyz, use abc"
682     /// * may contain a name of a function, variable, or type, but not whole expressions
683     ///
684     /// See `CodeSuggestion` for more information.
685     pub fn span_suggestion(
686         &mut self,
687         sp: Span,
688         msg: impl Into<SubdiagnosticMessage>,
689         suggestion: impl ToString,
690         applicability: Applicability,
691     ) -> &mut Self {
692         self.span_suggestion_with_style(
693             sp,
694             msg,
695             suggestion,
696             applicability,
697             SuggestionStyle::ShowCode,
698         );
699         self
700     }
701
702     /// [`Diagnostic::span_suggestion()`] but you can set the [`SuggestionStyle`].
703     pub fn span_suggestion_with_style(
704         &mut self,
705         sp: Span,
706         msg: impl Into<SubdiagnosticMessage>,
707         suggestion: impl ToString,
708         applicability: Applicability,
709         style: SuggestionStyle,
710     ) -> &mut Self {
711         debug_assert!(
712             !(sp.is_empty() && suggestion.to_string().is_empty()),
713             "Span must not be empty and have no suggestion"
714         );
715         self.push_suggestion(CodeSuggestion {
716             substitutions: vec![Substitution {
717                 parts: vec![SubstitutionPart { snippet: suggestion.to_string(), span: sp }],
718             }],
719             msg: self.subdiagnostic_message_to_diagnostic_message(msg),
720             style,
721             applicability,
722         });
723         self
724     }
725
726     /// Always show the suggested change.
727     pub fn span_suggestion_verbose(
728         &mut self,
729         sp: Span,
730         msg: impl Into<SubdiagnosticMessage>,
731         suggestion: impl ToString,
732         applicability: Applicability,
733     ) -> &mut Self {
734         self.span_suggestion_with_style(
735             sp,
736             msg,
737             suggestion,
738             applicability,
739             SuggestionStyle::ShowAlways,
740         );
741         self
742     }
743
744     /// Prints out a message with multiple suggested edits of the code.
745     /// See also [`Diagnostic::span_suggestion()`].
746     pub fn span_suggestions(
747         &mut self,
748         sp: Span,
749         msg: impl Into<SubdiagnosticMessage>,
750         suggestions: impl IntoIterator<Item = String>,
751         applicability: Applicability,
752     ) -> &mut Self {
753         self.span_suggestions_with_style(
754             sp,
755             msg,
756             suggestions,
757             applicability,
758             SuggestionStyle::ShowCode,
759         )
760     }
761
762     /// [`Diagnostic::span_suggestions()`] but you can set the [`SuggestionStyle`].
763     pub fn span_suggestions_with_style(
764         &mut self,
765         sp: Span,
766         msg: impl Into<SubdiagnosticMessage>,
767         suggestions: impl IntoIterator<Item = String>,
768         applicability: Applicability,
769         style: SuggestionStyle,
770     ) -> &mut Self {
771         let mut suggestions: Vec<_> = suggestions.into_iter().collect();
772         suggestions.sort();
773
774         debug_assert!(
775             !(sp.is_empty() && suggestions.iter().any(|suggestion| suggestion.is_empty())),
776             "Span must not be empty and have no suggestion"
777         );
778
779         let substitutions = suggestions
780             .into_iter()
781             .map(|snippet| Substitution { parts: vec![SubstitutionPart { snippet, span: sp }] })
782             .collect();
783         self.push_suggestion(CodeSuggestion {
784             substitutions,
785             msg: self.subdiagnostic_message_to_diagnostic_message(msg),
786             style,
787             applicability,
788         });
789         self
790     }
791
792     /// Prints out a message with multiple suggested edits of the code, where each edit consists of
793     /// multiple parts.
794     /// See also [`Diagnostic::multipart_suggestion()`].
795     pub fn multipart_suggestions(
796         &mut self,
797         msg: impl Into<SubdiagnosticMessage>,
798         suggestions: impl IntoIterator<Item = Vec<(Span, String)>>,
799         applicability: Applicability,
800     ) -> &mut Self {
801         let suggestions: Vec<_> = suggestions.into_iter().collect();
802         debug_assert!(
803             !(suggestions
804                 .iter()
805                 .flat_map(|suggs| suggs)
806                 .any(|(sp, suggestion)| sp.is_empty() && suggestion.is_empty())),
807             "Span must not be empty and have no suggestion"
808         );
809
810         self.push_suggestion(CodeSuggestion {
811             substitutions: suggestions
812                 .into_iter()
813                 .map(|sugg| Substitution {
814                     parts: sugg
815                         .into_iter()
816                         .map(|(span, snippet)| SubstitutionPart { snippet, span })
817                         .collect(),
818                 })
819                 .collect(),
820             msg: self.subdiagnostic_message_to_diagnostic_message(msg),
821             style: SuggestionStyle::ShowCode,
822             applicability,
823         });
824         self
825     }
826
827     /// Prints out a message with a suggested edit of the code. If the suggestion is presented
828     /// inline, it will only show the message and not the suggestion.
829     ///
830     /// See `CodeSuggestion` for more information.
831     pub fn span_suggestion_short(
832         &mut self,
833         sp: Span,
834         msg: impl Into<SubdiagnosticMessage>,
835         suggestion: impl ToString,
836         applicability: Applicability,
837     ) -> &mut Self {
838         self.span_suggestion_with_style(
839             sp,
840             msg,
841             suggestion,
842             applicability,
843             SuggestionStyle::HideCodeInline,
844         );
845         self
846     }
847
848     /// Prints out a message for a suggestion without showing the suggested code.
849     ///
850     /// This is intended to be used for suggestions that are obvious in what the changes need to
851     /// be from the message, showing the span label inline would be visually unpleasant
852     /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
853     /// improve understandability.
854     pub fn span_suggestion_hidden(
855         &mut self,
856         sp: Span,
857         msg: impl Into<SubdiagnosticMessage>,
858         suggestion: impl ToString,
859         applicability: Applicability,
860     ) -> &mut Self {
861         self.span_suggestion_with_style(
862             sp,
863             msg,
864             suggestion,
865             applicability,
866             SuggestionStyle::HideCodeAlways,
867         );
868         self
869     }
870
871     /// Adds a suggestion to the JSON output that will not be shown in the CLI.
872     ///
873     /// This is intended to be used for suggestions that are *very* obvious in what the changes
874     /// need to be from the message, but we still want other tools to be able to apply them.
875     pub fn tool_only_span_suggestion(
876         &mut self,
877         sp: Span,
878         msg: impl Into<SubdiagnosticMessage>,
879         suggestion: impl ToString,
880         applicability: Applicability,
881     ) -> &mut Self {
882         self.span_suggestion_with_style(
883             sp,
884             msg,
885             suggestion,
886             applicability,
887             SuggestionStyle::CompletelyHidden,
888         );
889         self
890     }
891
892     /// Add a subdiagnostic from a type that implements `Subdiagnostic` (see
893     /// [rustc_macros::Subdiagnostic]).
894     pub fn subdiagnostic(&mut self, subdiagnostic: impl AddToDiagnostic) -> &mut Self {
895         subdiagnostic.add_to_diagnostic(self);
896         self
897     }
898
899     /// Add a subdiagnostic from a type that implements `Subdiagnostic` (see
900     /// [rustc_macros::Subdiagnostic]). Performs eager translation of any translatable messages
901     /// used in the subdiagnostic, so suitable for use with repeated messages (i.e. re-use of
902     /// interpolated variables).
903     pub fn eager_subdiagnostic(
904         &mut self,
905         handler: &crate::Handler,
906         subdiagnostic: impl AddToDiagnostic,
907     ) -> &mut Self {
908         subdiagnostic.add_to_diagnostic_with(self, |diag, msg| {
909             let args = diag.args();
910             let msg = diag.subdiagnostic_message_to_diagnostic_message(msg);
911             handler.eagerly_translate(msg, args)
912         });
913         self
914     }
915
916     pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self {
917         self.span = sp.into();
918         if let Some(span) = self.span.primary_span() {
919             self.sort_span = span;
920         }
921         self
922     }
923
924     pub fn set_is_lint(&mut self) -> &mut Self {
925         self.is_lint = true;
926         self
927     }
928
929     pub fn code(&mut self, s: DiagnosticId) -> &mut Self {
930         self.code = Some(s);
931         self
932     }
933
934     pub fn clear_code(&mut self) -> &mut Self {
935         self.code = None;
936         self
937     }
938
939     pub fn get_code(&self) -> Option<DiagnosticId> {
940         self.code.clone()
941     }
942
943     pub fn set_primary_message(&mut self, msg: impl Into<DiagnosticMessage>) -> &mut Self {
944         self.message[0] = (msg.into(), Style::NoStyle);
945         self
946     }
947
948     // Exact iteration order of diagnostic arguments shouldn't make a difference to output because
949     // they're only used in interpolation.
950     #[allow(rustc::potential_query_instability)]
951     pub fn args<'a>(&'a self) -> impl Iterator<Item = DiagnosticArg<'a, 'static>> {
952         self.args.iter()
953     }
954
955     pub fn set_arg(
956         &mut self,
957         name: impl Into<Cow<'static, str>>,
958         arg: impl IntoDiagnosticArg,
959     ) -> &mut Self {
960         self.args.insert(name.into(), arg.into_diagnostic_arg());
961         self
962     }
963
964     pub fn replace_args(
965         &mut self,
966         args: FxHashMap<DiagnosticArgName<'static>, DiagnosticArgValue<'static>>,
967     ) {
968         self.args = args;
969     }
970
971     pub fn styled_message(&self) -> &[(DiagnosticMessage, Style)] {
972         &self.message
973     }
974
975     /// Helper function that takes a `SubdiagnosticMessage` and returns a `DiagnosticMessage` by
976     /// combining it with the primary message of the diagnostic (if translatable, otherwise it just
977     /// passes the user's string along).
978     pub(crate) fn subdiagnostic_message_to_diagnostic_message(
979         &self,
980         attr: impl Into<SubdiagnosticMessage>,
981     ) -> DiagnosticMessage {
982         let msg =
983             self.message.iter().map(|(msg, _)| msg).next().expect("diagnostic with no messages");
984         msg.with_subdiagnostic_message(attr.into())
985     }
986
987     /// Convenience function for internal use, clients should use one of the
988     /// public methods above.
989     ///
990     /// Used by `proc_macro_server` for implementing `server::Diagnostic`.
991     pub fn sub(
992         &mut self,
993         level: Level,
994         message: impl Into<SubdiagnosticMessage>,
995         span: MultiSpan,
996         render_span: Option<MultiSpan>,
997     ) {
998         let sub = SubDiagnostic {
999             level,
1000             message: vec![(
1001                 self.subdiagnostic_message_to_diagnostic_message(message),
1002                 Style::NoStyle,
1003             )],
1004             span,
1005             render_span,
1006         };
1007         self.children.push(sub);
1008     }
1009
1010     /// Convenience function for internal use, clients should use one of the
1011     /// public methods above.
1012     fn sub_with_highlights<M: Into<SubdiagnosticMessage>>(
1013         &mut self,
1014         level: Level,
1015         message: Vec<(M, Style)>,
1016         span: MultiSpan,
1017         render_span: Option<MultiSpan>,
1018     ) {
1019         let message = message
1020             .into_iter()
1021             .map(|m| (self.subdiagnostic_message_to_diagnostic_message(m.0), m.1))
1022             .collect();
1023         let sub = SubDiagnostic { level, message, span, render_span };
1024         self.children.push(sub);
1025     }
1026
1027     /// Fields used for Hash, and PartialEq trait
1028     fn keys(
1029         &self,
1030     ) -> (
1031         &Level,
1032         &[(DiagnosticMessage, Style)],
1033         &Option<DiagnosticId>,
1034         &MultiSpan,
1035         &Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
1036         Option<&[SubDiagnostic]>,
1037     ) {
1038         (
1039             &self.level,
1040             &self.message,
1041             &self.code,
1042             &self.span,
1043             &self.suggestions,
1044             (if self.is_lint { None } else { Some(&self.children) }),
1045         )
1046     }
1047 }
1048
1049 impl Hash for Diagnostic {
1050     fn hash<H>(&self, state: &mut H)
1051     where
1052         H: Hasher,
1053     {
1054         self.keys().hash(state);
1055     }
1056 }
1057
1058 impl PartialEq for Diagnostic {
1059     fn eq(&self, other: &Self) -> bool {
1060         self.keys() == other.keys()
1061     }
1062 }