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