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