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