1 use crate::snippet::Style;
3 CodeSuggestion, DiagnosticBuilder, DiagnosticMessage, EmissionGuarantee, Level, MultiSpan,
4 SubdiagnosticMessage, Substitution, SubstitutionPart, SuggestionStyle,
6 use rustc_data_structures::fx::FxHashMap;
7 use rustc_error_messages::FluentValue;
8 use rustc_lint_defs::{Applicability, LintExpectationId};
9 use rustc_span::edition::LATEST_STABLE_EDITION;
10 use rustc_span::symbol::Symbol;
11 use rustc_span::{Span, DUMMY_SP};
14 use std::hash::{Hash, Hasher};
16 /// Error type for `Diagnostic`'s `suggestions` field, indicating that
17 /// `.disable_suggestions()` was called on the `Diagnostic`.
18 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
19 pub struct SuggestionsDisabled;
21 /// Simplified version of `FluentArg` that can implement `Encodable` and `Decodable`. Collection of
22 /// `DiagnosticArg` are converted to `FluentArgs` (consuming the collection) at the start of
23 /// diagnostic emission.
24 pub type DiagnosticArg<'iter, 'source> =
25 (&'iter DiagnosticArgName<'source>, &'iter DiagnosticArgValue<'source>);
27 /// Name of a diagnostic argument.
28 pub type DiagnosticArgName<'source> = Cow<'source, str>;
30 /// Simplified version of `FluentValue` that can implement `Encodable` and `Decodable`. Converted
31 /// to a `FluentValue` by the emitter to be used in diagnostic translation.
32 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
33 pub enum DiagnosticArgValue<'source> {
34 Str(Cow<'source, str>),
38 /// Converts a value of a type into a `DiagnosticArg` (typically a field of an `IntoDiagnostic`
39 /// struct). Implemented as a custom trait rather than `From` so that it is implemented on the type
40 /// being converted rather than on `DiagnosticArgValue`, which enables types from other `rustc_*`
41 /// crates to implement this.
42 pub trait IntoDiagnosticArg {
43 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static>;
46 impl<'source> Into<FluentValue<'source>> for DiagnosticArgValue<'source> {
47 fn into(self) -> FluentValue<'source> {
49 DiagnosticArgValue::Str(s) => From::from(s),
50 DiagnosticArgValue::Number(n) => From::from(n),
55 /// Trait implemented by error types. This should not be implemented manually. Instead, use
56 /// `#[derive(Subdiagnostic)]` -- see [rustc_macros::Subdiagnostic].
57 #[cfg_attr(bootstrap, rustc_diagnostic_item = "AddSubdiagnostic")]
58 #[cfg_attr(not(bootstrap), rustc_diagnostic_item = "AddToDiagnostic")]
59 pub trait AddToDiagnostic
63 /// Add a subdiagnostic to an existing diagnostic.
64 fn add_to_diagnostic(self, diag: &mut Diagnostic) {
65 self.add_to_diagnostic_with(diag, |_, m| m);
68 /// Add a subdiagnostic to an existing diagnostic where `f` is invoked on every message used
69 /// (to optionally perform eager translation).
70 fn add_to_diagnostic_with<F>(self, diag: &mut Diagnostic, f: F)
72 F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage;
75 /// Trait implemented by lint types. This should not be implemented manually. Instead, use
76 /// `#[derive(LintDiagnostic)]` -- see [rustc_macros::LintDiagnostic].
77 #[rustc_diagnostic_item = "DecorateLint"]
78 pub trait DecorateLint<'a, G: EmissionGuarantee> {
79 /// Decorate and emit a lint.
82 diag: &'b mut DiagnosticBuilder<'a, G>,
83 ) -> &'b mut DiagnosticBuilder<'a, G>;
85 fn msg(&self) -> DiagnosticMessage;
89 #[derive(Clone, Debug, Encodable, Decodable)]
90 pub struct Diagnostic {
91 // NOTE(eddyb) this is private to disallow arbitrary after-the-fact changes,
92 // outside of what methods in this crate themselves allow.
93 pub(crate) level: Level,
95 pub message: Vec<(DiagnosticMessage, Style)>,
96 pub code: Option<DiagnosticId>,
98 pub children: Vec<SubDiagnostic>,
99 pub suggestions: Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
100 args: FxHashMap<DiagnosticArgName<'static>, DiagnosticArgValue<'static>>,
102 /// This is not used for highlighting or rendering any error message. Rather, it can be used
103 /// as a sort key to sort a buffer of diagnostics. By default, it is the primary span of
104 /// `span` if there is one. Otherwise, it is `DUMMY_SP`.
107 /// If diagnostic is from Lint, custom hash function ignores notes
108 /// otherwise hash is based on the all the fields
112 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
113 pub enum DiagnosticId {
115 Lint { name: String, has_future_breakage: bool, is_force_warn: bool },
118 /// A "sub"-diagnostic attached to a parent diagnostic.
119 /// For example, a note attached to an error.
120 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
121 pub struct SubDiagnostic {
123 pub message: Vec<(DiagnosticMessage, Style)>,
125 pub render_span: Option<MultiSpan>,
128 #[derive(Debug, PartialEq, Eq)]
129 pub struct DiagnosticStyledString(pub Vec<StringPart>);
131 impl DiagnosticStyledString {
132 pub fn new() -> DiagnosticStyledString {
133 DiagnosticStyledString(vec![])
135 pub fn push_normal<S: Into<String>>(&mut self, t: S) {
136 self.0.push(StringPart::Normal(t.into()));
138 pub fn push_highlighted<S: Into<String>>(&mut self, t: S) {
139 self.0.push(StringPart::Highlighted(t.into()));
141 pub fn push<S: Into<String>>(&mut self, t: S, highlight: bool) {
143 self.push_highlighted(t);
148 pub fn normal<S: Into<String>>(t: S) -> DiagnosticStyledString {
149 DiagnosticStyledString(vec![StringPart::Normal(t.into())])
152 pub fn highlighted<S: Into<String>>(t: S) -> DiagnosticStyledString {
153 DiagnosticStyledString(vec![StringPart::Highlighted(t.into())])
156 pub fn content(&self) -> String {
157 self.0.iter().map(|x| x.content()).collect::<String>()
161 #[derive(Debug, PartialEq, Eq)]
162 pub enum StringPart {
168 pub fn content(&self) -> &str {
170 &StringPart::Normal(ref s) | &StringPart::Highlighted(ref s) => s,
176 pub fn new<M: Into<DiagnosticMessage>>(level: Level, message: M) -> Self {
177 Diagnostic::new_with_code(level, None, message)
180 pub fn new_with_code<M: Into<DiagnosticMessage>>(
182 code: Option<DiagnosticId>,
187 message: vec![(message.into(), Style::NoStyle)],
189 span: MultiSpan::new(),
191 suggestions: Ok(vec![]),
192 args: Default::default(),
199 pub fn level(&self) -> Level {
203 pub fn is_error(&self) -> bool {
208 | Level::Error { .. }
209 | Level::FailureNote => true,
216 | Level::Expect(_) => false,
220 pub fn update_unstable_expectation_id(
222 unstable_to_stable: &FxHashMap<LintExpectationId, LintExpectationId>,
224 if let Level::Expect(expectation_id) | Level::Warning(Some(expectation_id)) =
227 if expectation_id.is_stable() {
231 // The unstable to stable map only maps the unstable `AttrId` to a stable `HirId` with an attribute index.
232 // The lint index inside the attribute is manually transferred here.
233 let lint_index = expectation_id.get_lint_index();
234 expectation_id.set_lint_index(None);
235 let mut stable_id = unstable_to_stable
236 .get(&expectation_id)
237 .expect("each unstable `LintExpectationId` must have a matching stable id")
240 stable_id.set_lint_index(lint_index);
241 *expectation_id = stable_id;
245 pub fn has_future_breakage(&self) -> bool {
247 Some(DiagnosticId::Lint { has_future_breakage, .. }) => has_future_breakage,
252 pub fn is_force_warn(&self) -> bool {
254 Some(DiagnosticId::Lint { is_force_warn, .. }) => is_force_warn,
259 /// Delay emission of this diagnostic as a bug.
261 /// This can be useful in contexts where an error indicates a bug but
262 /// typically this only happens when other compilation errors have already
263 /// happened. In those cases this can be used to defer emission of this
264 /// diagnostic as a bug in the compiler only if no other errors have been
267 /// In the meantime, though, callsites are required to deal with the "bug"
268 /// locally in whichever way makes the most sense.
270 pub fn downgrade_to_delayed_bug(&mut self) -> &mut Self {
273 "downgrade_to_delayed_bug: cannot downgrade {:?} to DelayedBug: not an error",
276 self.level = Level::DelayedBug;
281 /// Adds a span/label to be included in the resulting snippet.
283 /// This is pushed onto the [`MultiSpan`] that was created when the diagnostic
284 /// was first built. That means it will be shown together with the original
285 /// span/label, *not* a span added by one of the `span_{note,warn,help,suggestions}` methods.
287 /// This span is *not* considered a ["primary span"][`MultiSpan`]; only
288 /// the `Span` supplied when creating the diagnostic is primary.
289 #[rustc_lint_diagnostics]
290 pub fn span_label(&mut self, span: Span, label: impl Into<SubdiagnosticMessage>) -> &mut Self {
291 self.span.push_span_label(span, self.subdiagnostic_message_to_diagnostic_message(label));
295 /// Labels all the given spans with the provided label.
296 /// See [`Self::span_label()`] for more information.
299 spans: impl IntoIterator<Item = Span>,
300 label: impl AsRef<str>,
302 let label = label.as_ref();
304 self.span_label(span, label);
309 pub fn replace_span_with(&mut self, after: Span) -> &mut Self {
310 let before = self.span.clone();
311 self.set_span(after);
312 for span_label in before.span_labels() {
313 if let Some(label) = span_label.label {
314 self.span.push_span_label(after, label);
320 pub fn note_expected_found(
322 expected_label: &dyn fmt::Display,
323 expected: DiagnosticStyledString,
324 found_label: &dyn fmt::Display,
325 found: DiagnosticStyledString,
327 self.note_expected_found_extra(expected_label, expected, found_label, found, &"", &"")
330 pub fn note_unsuccessful_coercion(
332 expected: DiagnosticStyledString,
333 found: DiagnosticStyledString,
335 let mut msg: Vec<_> = vec![("required when trying to coerce from type `", Style::NoStyle)];
336 msg.extend(expected.0.iter().map(|x| match *x {
337 StringPart::Normal(ref s) => (s.as_str(), Style::NoStyle),
338 StringPart::Highlighted(ref s) => (s.as_str(), Style::Highlight),
340 msg.push(("` to type '", Style::NoStyle));
341 msg.extend(found.0.iter().map(|x| match *x {
342 StringPart::Normal(ref s) => (s.as_str(), Style::NoStyle),
343 StringPart::Highlighted(ref s) => (s.as_str(), Style::Highlight),
345 msg.push(("`", Style::NoStyle));
347 // For now, just attach these as notes
348 self.highlighted_note(msg);
352 pub fn note_expected_found_extra(
354 expected_label: &dyn fmt::Display,
355 expected: DiagnosticStyledString,
356 found_label: &dyn fmt::Display,
357 found: DiagnosticStyledString,
358 expected_extra: &dyn fmt::Display,
359 found_extra: &dyn fmt::Display,
361 let expected_label = expected_label.to_string();
362 let expected_label = if expected_label.is_empty() {
363 "expected".to_string()
365 format!("expected {}", expected_label)
367 let found_label = found_label.to_string();
368 let found_label = if found_label.is_empty() {
371 format!("found {}", found_label)
373 let (found_padding, expected_padding) = if expected_label.len() > found_label.len() {
374 (expected_label.len() - found_label.len(), 0)
376 (0, found_label.len() - expected_label.len())
378 let mut msg: Vec<_> =
379 vec![(format!("{}{} `", " ".repeat(expected_padding), expected_label), Style::NoStyle)];
380 msg.extend(expected.0.iter().map(|x| match *x {
381 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
382 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
384 msg.push((format!("`{}\n", expected_extra), Style::NoStyle));
385 msg.push((format!("{}{} `", " ".repeat(found_padding), found_label), Style::NoStyle));
386 msg.extend(found.0.iter().map(|x| match *x {
387 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
388 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
390 msg.push((format!("`{}", found_extra), Style::NoStyle));
392 // For now, just attach these as notes.
393 self.highlighted_note(msg);
397 pub fn note_trait_signature(&mut self, name: Symbol, signature: String) -> &mut Self {
398 self.highlighted_note(vec![
399 (format!("`{}` from trait: `", name), Style::NoStyle),
400 (signature, Style::Highlight),
401 ("`".to_string(), Style::NoStyle),
406 /// Add a note attached to this diagnostic.
407 #[rustc_lint_diagnostics]
408 pub fn note(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
409 self.sub(Level::Note, msg, MultiSpan::new(), None);
413 pub fn highlighted_note<M: Into<SubdiagnosticMessage>>(
415 msg: Vec<(M, Style)>,
417 self.sub_with_highlights(Level::Note, msg, MultiSpan::new(), None);
421 /// Prints the span with a note above it.
422 /// This is like [`Diagnostic::note()`], but it gets its own span.
423 pub fn note_once(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
424 self.sub(Level::OnceNote, msg, MultiSpan::new(), None);
428 /// Prints the span with a note above it.
429 /// This is like [`Diagnostic::note()`], but it gets its own span.
430 #[rustc_lint_diagnostics]
431 pub fn span_note<S: Into<MultiSpan>>(
434 msg: impl Into<SubdiagnosticMessage>,
436 self.sub(Level::Note, msg, sp.into(), None);
440 /// Prints the span with a note above it.
441 /// This is like [`Diagnostic::note()`], but it gets its own span.
442 pub fn span_note_once<S: Into<MultiSpan>>(
445 msg: impl Into<SubdiagnosticMessage>,
447 self.sub(Level::OnceNote, msg, sp.into(), None);
451 /// Add a warning attached to this diagnostic.
452 #[rustc_lint_diagnostics]
453 pub fn warn(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
454 self.sub(Level::Warning(None), msg, MultiSpan::new(), None);
458 /// Prints the span with a warning above it.
459 /// This is like [`Diagnostic::warn()`], but it gets its own span.
460 #[rustc_lint_diagnostics]
461 pub fn span_warn<S: Into<MultiSpan>>(
464 msg: impl Into<SubdiagnosticMessage>,
466 self.sub(Level::Warning(None), msg, sp.into(), None);
470 /// Add a help message attached to this diagnostic.
471 #[rustc_lint_diagnostics]
472 pub fn help(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
473 self.sub(Level::Help, msg, MultiSpan::new(), None);
477 /// Add a help message attached to this diagnostic with a customizable highlighted message.
478 pub fn highlighted_help(&mut self, msg: Vec<(String, Style)>) -> &mut Self {
479 self.sub_with_highlights(Level::Help, msg, MultiSpan::new(), None);
483 /// Prints the span with some help above it.
484 /// This is like [`Diagnostic::help()`], but it gets its own span.
485 #[rustc_lint_diagnostics]
486 pub fn span_help<S: Into<MultiSpan>>(
489 msg: impl Into<SubdiagnosticMessage>,
491 self.sub(Level::Help, msg, sp.into(), None);
495 /// Help the user upgrade to the latest edition.
496 /// This is factored out to make sure it does the right thing with `Cargo.toml`.
497 pub fn help_use_latest_edition(&mut self) -> &mut Self {
498 if std::env::var_os("CARGO").is_some() {
499 self.help(&format!("set `edition = \"{}\"` in `Cargo.toml`", LATEST_STABLE_EDITION));
501 self.help(&format!("pass `--edition {}` to `rustc`", LATEST_STABLE_EDITION));
503 self.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
507 /// Disallow attaching suggestions this diagnostic.
508 /// Any suggestions attached e.g. with the `span_suggestion_*` methods
509 /// (before and after the call to `disable_suggestions`) will be ignored.
510 pub fn disable_suggestions(&mut self) -> &mut Self {
511 self.suggestions = Err(SuggestionsDisabled);
515 /// Clear any existing suggestions.
516 pub fn clear_suggestions(&mut self) -> &mut Self {
517 if let Ok(suggestions) = &mut self.suggestions {
523 /// Helper for pushing to `self.suggestions`, if available (not disable).
524 fn push_suggestion(&mut self, suggestion: CodeSuggestion) {
525 if let Ok(suggestions) = &mut self.suggestions {
526 suggestions.push(suggestion);
530 /// Show a suggestion that has multiple parts to it.
531 /// In other words, multiple changes need to be applied as part of this suggestion.
532 pub fn multipart_suggestion(
534 msg: impl Into<SubdiagnosticMessage>,
535 suggestion: Vec<(Span, String)>,
536 applicability: Applicability,
538 self.multipart_suggestion_with_style(
542 SuggestionStyle::ShowCode,
546 /// Show a suggestion that has multiple parts to it, always as it's own subdiagnostic.
547 /// In other words, multiple changes need to be applied as part of this suggestion.
548 pub fn multipart_suggestion_verbose(
550 msg: impl Into<SubdiagnosticMessage>,
551 suggestion: Vec<(Span, String)>,
552 applicability: Applicability,
554 self.multipart_suggestion_with_style(
558 SuggestionStyle::ShowAlways,
561 /// [`Diagnostic::multipart_suggestion()`] but you can set the [`SuggestionStyle`].
562 pub fn multipart_suggestion_with_style(
564 msg: impl Into<SubdiagnosticMessage>,
565 suggestion: Vec<(Span, String)>,
566 applicability: Applicability,
567 style: SuggestionStyle,
569 assert!(!suggestion.is_empty());
571 !(suggestion.iter().any(|(sp, text)| sp.is_empty() && text.is_empty())),
572 "Span must not be empty and have no suggestion"
575 self.push_suggestion(CodeSuggestion {
576 substitutions: vec![Substitution {
579 .map(|(span, snippet)| SubstitutionPart { snippet, span })
582 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
589 /// Prints out a message with for a multipart suggestion without showing the suggested code.
591 /// This is intended to be used for suggestions that are obvious in what the changes need to
592 /// be from the message, showing the span label inline would be visually unpleasant
593 /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
594 /// improve understandability.
595 pub fn tool_only_multipart_suggestion(
597 msg: impl Into<SubdiagnosticMessage>,
598 suggestion: Vec<(Span, String)>,
599 applicability: Applicability,
601 self.multipart_suggestion_with_style(
605 SuggestionStyle::CompletelyHidden,
609 /// Prints out a message with a suggested edit of the code.
611 /// In case of short messages and a simple suggestion, rustc displays it as a label:
614 /// try adding parentheses: `(tup.0).1`
619 /// * should not end in any punctuation (a `:` is added automatically)
620 /// * should not be a question (avoid language like "did you mean")
621 /// * should not contain any phrases like "the following", "as shown", etc.
622 /// * may look like "to do xyz, use" or "to do xyz, use abc"
623 /// * may contain a name of a function, variable, or type, but not whole expressions
625 /// See `CodeSuggestion` for more information.
626 pub fn span_suggestion(
629 msg: impl Into<SubdiagnosticMessage>,
630 suggestion: impl ToString,
631 applicability: Applicability,
633 self.span_suggestion_with_style(
638 SuggestionStyle::ShowCode,
643 /// [`Diagnostic::span_suggestion()`] but you can set the [`SuggestionStyle`].
644 pub fn span_suggestion_with_style(
647 msg: impl Into<SubdiagnosticMessage>,
648 suggestion: impl ToString,
649 applicability: Applicability,
650 style: SuggestionStyle,
653 !(sp.is_empty() && suggestion.to_string().is_empty()),
654 "Span must not be empty and have no suggestion"
656 self.push_suggestion(CodeSuggestion {
657 substitutions: vec![Substitution {
658 parts: vec![SubstitutionPart { snippet: suggestion.to_string(), span: sp }],
660 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
667 /// Always show the suggested change.
668 pub fn span_suggestion_verbose(
671 msg: impl Into<SubdiagnosticMessage>,
672 suggestion: impl ToString,
673 applicability: Applicability,
675 self.span_suggestion_with_style(
680 SuggestionStyle::ShowAlways,
685 /// Prints out a message with multiple suggested edits of the code.
686 /// See also [`Diagnostic::span_suggestion()`].
687 pub fn span_suggestions(
690 msg: impl Into<SubdiagnosticMessage>,
691 suggestions: impl Iterator<Item = String>,
692 applicability: Applicability,
694 let mut suggestions: Vec<_> = suggestions.collect();
698 !(sp.is_empty() && suggestions.iter().any(|suggestion| suggestion.is_empty())),
699 "Span must not be empty and have no suggestion"
702 let substitutions = suggestions
704 .map(|snippet| Substitution { parts: vec![SubstitutionPart { snippet, span: sp }] })
706 self.push_suggestion(CodeSuggestion {
708 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
709 style: SuggestionStyle::ShowCode,
715 /// Prints out a message with multiple suggested edits of the code.
716 /// See also [`Diagnostic::span_suggestion()`].
717 pub fn multipart_suggestions(
719 msg: impl Into<SubdiagnosticMessage>,
720 suggestions: impl Iterator<Item = Vec<(Span, String)>>,
721 applicability: Applicability,
723 let suggestions: Vec<_> = suggestions.collect();
727 .flat_map(|suggs| suggs)
728 .any(|(sp, suggestion)| sp.is_empty() && suggestion.is_empty())),
729 "Span must not be empty and have no suggestion"
732 self.push_suggestion(CodeSuggestion {
733 substitutions: suggestions
735 .map(|sugg| Substitution {
738 .map(|(span, snippet)| SubstitutionPart { snippet, span })
742 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
743 style: SuggestionStyle::ShowCode,
748 /// Prints out a message with a suggested edit of the code. If the suggestion is presented
749 /// inline, it will only show the message and not the suggestion.
751 /// See `CodeSuggestion` for more information.
752 pub fn span_suggestion_short(
755 msg: impl Into<SubdiagnosticMessage>,
756 suggestion: impl ToString,
757 applicability: Applicability,
759 self.span_suggestion_with_style(
764 SuggestionStyle::HideCodeInline,
769 /// Prints out a message for a suggestion without showing the suggested code.
771 /// This is intended to be used for suggestions that are obvious in what the changes need to
772 /// be from the message, showing the span label inline would be visually unpleasant
773 /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
774 /// improve understandability.
775 pub fn span_suggestion_hidden(
778 msg: impl Into<SubdiagnosticMessage>,
779 suggestion: impl ToString,
780 applicability: Applicability,
782 self.span_suggestion_with_style(
787 SuggestionStyle::HideCodeAlways,
792 /// Adds a suggestion to the JSON output that will not be shown in the CLI.
794 /// This is intended to be used for suggestions that are *very* obvious in what the changes
795 /// need to be from the message, but we still want other tools to be able to apply them.
796 pub fn tool_only_span_suggestion(
799 msg: impl Into<SubdiagnosticMessage>,
800 suggestion: impl ToString,
801 applicability: Applicability,
803 self.span_suggestion_with_style(
808 SuggestionStyle::CompletelyHidden,
813 /// Add a subdiagnostic from a type that implements `Subdiagnostic` (see
814 /// [rustc_macros::Subdiagnostic]).
815 pub fn subdiagnostic(&mut self, subdiagnostic: impl AddToDiagnostic) -> &mut Self {
816 subdiagnostic.add_to_diagnostic(self);
820 /// Add a subdiagnostic from a type that implements `Subdiagnostic` (see
821 /// [rustc_macros::Subdiagnostic]). Performs eager translation of any translatable messages
822 /// used in the subdiagnostic, so suitable for use with repeated messages (i.e. re-use of
823 /// interpolated variables).
824 pub fn eager_subdiagnostic(
826 handler: &crate::Handler,
827 subdiagnostic: impl AddToDiagnostic,
829 subdiagnostic.add_to_diagnostic_with(self, |diag, msg| {
830 let args = diag.args();
831 let msg = diag.subdiagnostic_message_to_diagnostic_message(msg);
832 handler.eagerly_translate(msg, args)
837 pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self {
838 self.span = sp.into();
839 if let Some(span) = self.span.primary_span() {
840 self.sort_span = span;
845 pub fn set_is_lint(&mut self) -> &mut Self {
850 pub fn code(&mut self, s: DiagnosticId) -> &mut Self {
855 pub fn clear_code(&mut self) -> &mut Self {
860 pub fn get_code(&self) -> Option<DiagnosticId> {
864 pub fn set_primary_message(&mut self, msg: impl Into<DiagnosticMessage>) -> &mut Self {
865 self.message[0] = (msg.into(), Style::NoStyle);
869 // Exact iteration order of diagnostic arguments shouldn't make a difference to output because
870 // they're only used in interpolation.
871 #[allow(rustc::potential_query_instability)]
872 pub fn args<'a>(&'a self) -> impl Iterator<Item = DiagnosticArg<'a, 'static>> {
878 name: impl Into<Cow<'static, str>>,
879 arg: impl IntoDiagnosticArg,
881 self.args.insert(name.into(), arg.into_diagnostic_arg());
885 pub fn styled_message(&self) -> &[(DiagnosticMessage, Style)] {
889 /// Helper function that takes a `SubdiagnosticMessage` and returns a `DiagnosticMessage` by
890 /// combining it with the primary message of the diagnostic (if translatable, otherwise it just
891 /// passes the user's string along).
892 pub(crate) fn subdiagnostic_message_to_diagnostic_message(
894 attr: impl Into<SubdiagnosticMessage>,
895 ) -> DiagnosticMessage {
897 self.message.iter().map(|(msg, _)| msg).next().expect("diagnostic with no messages");
898 msg.with_subdiagnostic_message(attr.into())
901 /// Convenience function for internal use, clients should use one of the
902 /// public methods above.
904 /// Used by `proc_macro_server` for implementing `server::Diagnostic`.
908 message: impl Into<SubdiagnosticMessage>,
910 render_span: Option<MultiSpan>,
912 let sub = SubDiagnostic {
915 self.subdiagnostic_message_to_diagnostic_message(message),
921 self.children.push(sub);
924 /// Convenience function for internal use, clients should use one of the
925 /// public methods above.
926 fn sub_with_highlights<M: Into<SubdiagnosticMessage>>(
929 message: Vec<(M, Style)>,
931 render_span: Option<MultiSpan>,
933 let message = message
935 .map(|m| (self.subdiagnostic_message_to_diagnostic_message(m.0), m.1))
937 let sub = SubDiagnostic { level, message, span, render_span };
938 self.children.push(sub);
941 /// Fields used for Hash, and PartialEq trait
946 &[(DiagnosticMessage, Style)],
947 &Option<DiagnosticId>,
949 &Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
950 Option<&[SubDiagnostic]>,
958 (if self.is_lint { None } else { Some(&self.children) }),
963 impl Hash for Diagnostic {
964 fn hash<H>(&self, state: &mut H)
968 self.keys().hash(state);
972 impl PartialEq for Diagnostic {
973 fn eq(&self, other: &Self) -> bool {
974 self.keys() == other.keys()