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