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