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