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::fluent_value_from_str_list_sep_by_and;
8 use rustc_error_messages::FluentValue;
9 use rustc_lint_defs::{Applicability, LintExpectationId};
10 use rustc_span::edition::LATEST_STABLE_EDITION;
11 use rustc_span::symbol::Symbol;
12 use rustc_span::{Span, DUMMY_SP};
15 use std::hash::{Hash, Hasher};
16 use std::panic::Location;
18 /// Error type for `Diagnostic`'s `suggestions` field, indicating that
19 /// `.disable_suggestions()` was called on the `Diagnostic`.
20 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
21 pub struct SuggestionsDisabled;
23 /// Simplified version of `FluentArg` that can implement `Encodable` and `Decodable`. Collection of
24 /// `DiagnosticArg` are converted to `FluentArgs` (consuming the collection) at the start of
25 /// diagnostic emission.
26 pub type DiagnosticArg<'iter, 'source> =
27 (&'iter DiagnosticArgName<'source>, &'iter DiagnosticArgValue<'source>);
29 /// Name of a diagnostic argument.
30 pub type DiagnosticArgName<'source> = Cow<'source, str>;
32 /// Simplified version of `FluentValue` that can implement `Encodable` and `Decodable`. Converted
33 /// to a `FluentValue` by the emitter to be used in diagnostic translation.
34 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
35 pub enum DiagnosticArgValue<'source> {
36 Str(Cow<'source, str>),
38 StrListSepByAnd(Vec<Cow<'source, str>>),
41 /// Converts a value of a type into a `DiagnosticArg` (typically a field of an `IntoDiagnostic`
42 /// struct). Implemented as a custom trait rather than `From` so that it is implemented on the type
43 /// being converted rather than on `DiagnosticArgValue`, which enables types from other `rustc_*`
44 /// crates to implement this.
45 pub trait IntoDiagnosticArg {
46 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static>;
49 impl<'source> IntoDiagnosticArg for DiagnosticArgValue<'source> {
50 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
52 DiagnosticArgValue::Str(s) => DiagnosticArgValue::Str(Cow::Owned(s.into_owned())),
53 DiagnosticArgValue::Number(n) => DiagnosticArgValue::Number(n),
54 DiagnosticArgValue::StrListSepByAnd(l) => DiagnosticArgValue::StrListSepByAnd(
55 l.into_iter().map(|s| Cow::Owned(s.into_owned())).collect(),
61 impl<'source> Into<FluentValue<'source>> for DiagnosticArgValue<'source> {
62 fn into(self) -> FluentValue<'source> {
64 DiagnosticArgValue::Str(s) => From::from(s),
65 DiagnosticArgValue::Number(n) => From::from(n),
66 DiagnosticArgValue::StrListSepByAnd(l) => fluent_value_from_str_list_sep_by_and(l),
71 /// Trait implemented by error types. This should not be implemented manually. Instead, use
72 /// `#[derive(Subdiagnostic)]` -- see [rustc_macros::Subdiagnostic].
73 #[rustc_diagnostic_item = "AddToDiagnostic"]
74 pub trait AddToDiagnostic
78 /// Add a subdiagnostic to an existing diagnostic.
79 fn add_to_diagnostic(self, diag: &mut Diagnostic) {
80 self.add_to_diagnostic_with(diag, |_, m| m);
83 /// Add a subdiagnostic to an existing diagnostic where `f` is invoked on every message used
84 /// (to optionally perform eager translation).
85 fn add_to_diagnostic_with<F>(self, diag: &mut Diagnostic, f: F)
87 F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage;
90 /// Trait implemented by lint types. This should not be implemented manually. Instead, use
91 /// `#[derive(LintDiagnostic)]` -- see [rustc_macros::LintDiagnostic].
92 #[rustc_diagnostic_item = "DecorateLint"]
93 pub trait DecorateLint<'a, G: EmissionGuarantee> {
94 /// Decorate and emit a lint.
97 diag: &'b mut DiagnosticBuilder<'a, G>,
98 ) -> &'b mut DiagnosticBuilder<'a, G>;
100 fn msg(&self) -> DiagnosticMessage;
104 #[derive(Clone, Debug, Encodable, Decodable)]
105 pub struct Diagnostic {
106 // NOTE(eddyb) this is private to disallow arbitrary after-the-fact changes,
107 // outside of what methods in this crate themselves allow.
108 pub(crate) level: Level,
110 pub message: Vec<(DiagnosticMessage, Style)>,
111 pub code: Option<DiagnosticId>,
113 pub children: Vec<SubDiagnostic>,
114 pub suggestions: Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
115 args: FxHashMap<DiagnosticArgName<'static>, DiagnosticArgValue<'static>>,
117 /// This is not used for highlighting or rendering any error message. Rather, it can be used
118 /// as a sort key to sort a buffer of diagnostics. By default, it is the primary span of
119 /// `span` if there is one. Otherwise, it is `DUMMY_SP`.
122 /// If diagnostic is from Lint, custom hash function ignores notes
123 /// otherwise hash is based on the all the fields
126 /// With `-Ztrack_diagnostics` enabled,
127 /// we print where in rustc this error was emitted.
128 pub emitted_at: DiagnosticLocation,
131 #[derive(Clone, Debug, Encodable, Decodable)]
132 pub struct DiagnosticLocation {
133 file: Cow<'static, str>,
138 impl DiagnosticLocation {
140 fn caller() -> Self {
141 let loc = Location::caller();
142 DiagnosticLocation { file: loc.file().into(), line: loc.line(), col: loc.column() }
146 impl fmt::Display for DiagnosticLocation {
147 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148 write!(f, "{}:{}:{}", self.file, self.line, self.col)
152 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
153 pub enum DiagnosticId {
155 Lint { name: String, has_future_breakage: bool, is_force_warn: bool },
158 /// A "sub"-diagnostic attached to a parent diagnostic.
159 /// For example, a note attached to an error.
160 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
161 pub struct SubDiagnostic {
163 pub message: Vec<(DiagnosticMessage, Style)>,
165 pub render_span: Option<MultiSpan>,
168 #[derive(Debug, PartialEq, Eq)]
169 pub struct DiagnosticStyledString(pub Vec<StringPart>);
171 impl DiagnosticStyledString {
172 pub fn new() -> DiagnosticStyledString {
173 DiagnosticStyledString(vec![])
175 pub fn push_normal<S: Into<String>>(&mut self, t: S) {
176 self.0.push(StringPart::Normal(t.into()));
178 pub fn push_highlighted<S: Into<String>>(&mut self, t: S) {
179 self.0.push(StringPart::Highlighted(t.into()));
181 pub fn push<S: Into<String>>(&mut self, t: S, highlight: bool) {
183 self.push_highlighted(t);
188 pub fn normal<S: Into<String>>(t: S) -> DiagnosticStyledString {
189 DiagnosticStyledString(vec![StringPart::Normal(t.into())])
192 pub fn highlighted<S: Into<String>>(t: S) -> DiagnosticStyledString {
193 DiagnosticStyledString(vec![StringPart::Highlighted(t.into())])
196 pub fn content(&self) -> String {
197 self.0.iter().map(|x| x.content()).collect::<String>()
201 #[derive(Debug, PartialEq, Eq)]
202 pub enum StringPart {
208 pub fn content(&self) -> &str {
210 &StringPart::Normal(ref s) | &StringPart::Highlighted(ref s) => s,
217 pub fn new<M: Into<DiagnosticMessage>>(level: Level, message: M) -> Self {
218 Diagnostic::new_with_code(level, None, message)
222 pub fn new_with_messages(level: Level, messages: Vec<(DiagnosticMessage, Style)>) -> Self {
227 span: MultiSpan::new(),
229 suggestions: Ok(vec![]),
230 args: Default::default(),
233 emitted_at: DiagnosticLocation::caller(),
238 pub fn new_with_code<M: Into<DiagnosticMessage>>(
240 code: Option<DiagnosticId>,
245 message: vec![(message.into(), Style::NoStyle)],
247 span: MultiSpan::new(),
249 suggestions: Ok(vec![]),
250 args: Default::default(),
253 emitted_at: DiagnosticLocation::caller(),
258 pub fn level(&self) -> Level {
262 pub fn is_error(&self) -> bool {
267 | Level::Error { .. }
268 | Level::FailureNote => true,
275 | Level::Expect(_) => false,
279 pub fn update_unstable_expectation_id(
281 unstable_to_stable: &FxHashMap<LintExpectationId, LintExpectationId>,
283 if let Level::Expect(expectation_id) | Level::Warning(Some(expectation_id)) =
286 if expectation_id.is_stable() {
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
296 .expect("each unstable `LintExpectationId` must have a matching stable id")
299 stable_id.set_lint_index(lint_index);
300 *expectation_id = stable_id;
304 pub fn has_future_breakage(&self) -> bool {
306 Some(DiagnosticId::Lint { has_future_breakage, .. }) => has_future_breakage,
311 pub fn is_force_warn(&self) -> bool {
313 Some(DiagnosticId::Lint { is_force_warn, .. }) => is_force_warn,
318 /// Delay emission of this diagnostic as a bug.
320 /// This can be useful in contexts where an error indicates a bug but
321 /// typically this only happens when other compilation errors have already
322 /// happened. In those cases this can be used to defer emission of this
323 /// diagnostic as a bug in the compiler only if no other errors have been
326 /// In the meantime, though, callsites are required to deal with the "bug"
327 /// locally in whichever way makes the most sense.
329 pub fn downgrade_to_delayed_bug(&mut self) -> &mut Self {
332 "downgrade_to_delayed_bug: cannot downgrade {:?} to DelayedBug: not an error",
335 self.level = Level::DelayedBug;
340 /// Adds a span/label to be included in the resulting snippet.
342 /// This is pushed onto the [`MultiSpan`] that was created when the diagnostic
343 /// was first built. That means it will be shown together with the original
344 /// span/label, *not* a span added by one of the `span_{note,warn,help,suggestions}` methods.
346 /// This span is *not* considered a ["primary span"][`MultiSpan`]; only
347 /// the `Span` supplied when creating the diagnostic is primary.
348 #[rustc_lint_diagnostics]
349 pub fn span_label(&mut self, span: Span, label: impl Into<SubdiagnosticMessage>) -> &mut Self {
350 self.span.push_span_label(span, self.subdiagnostic_message_to_diagnostic_message(label));
354 /// Labels all the given spans with the provided label.
355 /// See [`Self::span_label()`] for more information.
358 spans: impl IntoIterator<Item = Span>,
359 label: impl AsRef<str>,
361 let label = label.as_ref();
363 self.span_label(span, label);
368 pub fn replace_span_with(&mut self, after: Span) -> &mut Self {
369 let before = self.span.clone();
370 self.set_span(after);
371 for span_label in before.span_labels() {
372 if let Some(label) = span_label.label {
373 self.span.push_span_label(after, label);
379 pub fn note_expected_found(
381 expected_label: &dyn fmt::Display,
382 expected: DiagnosticStyledString,
383 found_label: &dyn fmt::Display,
384 found: DiagnosticStyledString,
386 self.note_expected_found_extra(expected_label, expected, found_label, found, &"", &"")
389 pub fn note_unsuccessful_coercion(
391 expected: DiagnosticStyledString,
392 found: DiagnosticStyledString,
394 let mut msg: Vec<_> = vec![("required when trying to coerce from type `", Style::NoStyle)];
395 msg.extend(expected.0.iter().map(|x| match *x {
396 StringPart::Normal(ref s) => (s.as_str(), Style::NoStyle),
397 StringPart::Highlighted(ref s) => (s.as_str(), Style::Highlight),
399 msg.push(("` to type '", Style::NoStyle));
400 msg.extend(found.0.iter().map(|x| match *x {
401 StringPart::Normal(ref s) => (s.as_str(), Style::NoStyle),
402 StringPart::Highlighted(ref s) => (s.as_str(), Style::Highlight),
404 msg.push(("`", Style::NoStyle));
406 // For now, just attach these as notes
407 self.highlighted_note(msg);
411 pub fn note_expected_found_extra(
413 expected_label: &dyn fmt::Display,
414 expected: DiagnosticStyledString,
415 found_label: &dyn fmt::Display,
416 found: DiagnosticStyledString,
417 expected_extra: &dyn fmt::Display,
418 found_extra: &dyn fmt::Display,
420 let expected_label = expected_label.to_string();
421 let expected_label = if expected_label.is_empty() {
422 "expected".to_string()
424 format!("expected {}", expected_label)
426 let found_label = found_label.to_string();
427 let found_label = if found_label.is_empty() {
430 format!("found {}", found_label)
432 let (found_padding, expected_padding) = if expected_label.len() > found_label.len() {
433 (expected_label.len() - found_label.len(), 0)
435 (0, found_label.len() - expected_label.len())
437 let mut msg: Vec<_> =
438 vec![(format!("{}{} `", " ".repeat(expected_padding), expected_label), Style::NoStyle)];
439 msg.extend(expected.0.iter().map(|x| match *x {
440 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
441 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
443 msg.push((format!("`{}\n", expected_extra), Style::NoStyle));
444 msg.push((format!("{}{} `", " ".repeat(found_padding), found_label), Style::NoStyle));
445 msg.extend(found.0.iter().map(|x| match *x {
446 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
447 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
449 msg.push((format!("`{}", found_extra), Style::NoStyle));
451 // For now, just attach these as notes.
452 self.highlighted_note(msg);
456 pub fn note_trait_signature(&mut self, name: Symbol, signature: String) -> &mut Self {
457 self.highlighted_note(vec![
458 (format!("`{}` from trait: `", name), Style::NoStyle),
459 (signature, Style::Highlight),
460 ("`".to_string(), Style::NoStyle),
465 /// Add a note attached to this diagnostic.
466 #[rustc_lint_diagnostics]
467 pub fn note(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
468 self.sub(Level::Note, msg, MultiSpan::new(), None);
472 pub fn highlighted_note<M: Into<SubdiagnosticMessage>>(
474 msg: Vec<(M, Style)>,
476 self.sub_with_highlights(Level::Note, msg, MultiSpan::new(), None);
480 /// Prints the span with a note above it.
481 /// This is like [`Diagnostic::note()`], but it gets its own span.
482 pub fn note_once(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
483 self.sub(Level::OnceNote, msg, MultiSpan::new(), None);
487 /// Prints the span with a note above it.
488 /// This is like [`Diagnostic::note()`], but it gets its own span.
489 #[rustc_lint_diagnostics]
490 pub fn span_note<S: Into<MultiSpan>>(
493 msg: impl Into<SubdiagnosticMessage>,
495 self.sub(Level::Note, msg, sp.into(), None);
499 /// Prints the span with a note above it.
500 /// This is like [`Diagnostic::note()`], but it gets its own span.
501 pub fn span_note_once<S: Into<MultiSpan>>(
504 msg: impl Into<SubdiagnosticMessage>,
506 self.sub(Level::OnceNote, msg, sp.into(), None);
510 /// Add a warning attached to this diagnostic.
511 #[rustc_lint_diagnostics]
512 pub fn warn(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
513 self.sub(Level::Warning(None), msg, MultiSpan::new(), None);
517 /// Prints the span with a warning above it.
518 /// This is like [`Diagnostic::warn()`], but it gets its own span.
519 #[rustc_lint_diagnostics]
520 pub fn span_warn<S: Into<MultiSpan>>(
523 msg: impl Into<SubdiagnosticMessage>,
525 self.sub(Level::Warning(None), msg, sp.into(), None);
529 /// Add a help message attached to this diagnostic.
530 #[rustc_lint_diagnostics]
531 pub fn help(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
532 self.sub(Level::Help, msg, MultiSpan::new(), None);
536 /// Add a help message attached to this diagnostic with a customizable highlighted message.
537 pub fn highlighted_help(&mut self, msg: Vec<(String, Style)>) -> &mut Self {
538 self.sub_with_highlights(Level::Help, msg, MultiSpan::new(), None);
542 /// Prints the span with some help above it.
543 /// This is like [`Diagnostic::help()`], but it gets its own span.
544 #[rustc_lint_diagnostics]
545 pub fn span_help<S: Into<MultiSpan>>(
548 msg: impl Into<SubdiagnosticMessage>,
550 self.sub(Level::Help, msg, sp.into(), None);
554 /// Help the user upgrade to the latest edition.
555 /// This is factored out to make sure it does the right thing with `Cargo.toml`.
556 pub fn help_use_latest_edition(&mut self) -> &mut Self {
557 if std::env::var_os("CARGO").is_some() {
558 self.help(&format!("set `edition = \"{}\"` in `Cargo.toml`", LATEST_STABLE_EDITION));
560 self.help(&format!("pass `--edition {}` to `rustc`", LATEST_STABLE_EDITION));
562 self.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
566 /// Disallow attaching suggestions this diagnostic.
567 /// Any suggestions attached e.g. with the `span_suggestion_*` methods
568 /// (before and after the call to `disable_suggestions`) will be ignored.
569 pub fn disable_suggestions(&mut self) -> &mut Self {
570 self.suggestions = Err(SuggestionsDisabled);
574 /// Clear any existing suggestions.
575 pub fn clear_suggestions(&mut self) -> &mut Self {
576 if let Ok(suggestions) = &mut self.suggestions {
582 /// Helper for pushing to `self.suggestions`, if available (not disable).
583 fn push_suggestion(&mut self, suggestion: CodeSuggestion) {
584 if let Ok(suggestions) = &mut self.suggestions {
585 suggestions.push(suggestion);
589 /// Show a suggestion that has multiple parts to it.
590 /// In other words, multiple changes need to be applied as part of this suggestion.
591 pub fn multipart_suggestion(
593 msg: impl Into<SubdiagnosticMessage>,
594 suggestion: Vec<(Span, String)>,
595 applicability: Applicability,
597 self.multipart_suggestion_with_style(
601 SuggestionStyle::ShowCode,
605 /// Show a suggestion that has multiple parts to it, always as it's own subdiagnostic.
606 /// In other words, multiple changes need to be applied as part of this suggestion.
607 pub fn multipart_suggestion_verbose(
609 msg: impl Into<SubdiagnosticMessage>,
610 suggestion: Vec<(Span, String)>,
611 applicability: Applicability,
613 self.multipart_suggestion_with_style(
617 SuggestionStyle::ShowAlways,
620 /// [`Diagnostic::multipart_suggestion()`] but you can set the [`SuggestionStyle`].
621 pub fn multipart_suggestion_with_style(
623 msg: impl Into<SubdiagnosticMessage>,
624 suggestion: Vec<(Span, String)>,
625 applicability: Applicability,
626 style: SuggestionStyle,
628 assert!(!suggestion.is_empty());
630 !(suggestion.iter().any(|(sp, text)| sp.is_empty() && text.is_empty())),
631 "Span must not be empty and have no suggestion"
634 self.push_suggestion(CodeSuggestion {
635 substitutions: vec![Substitution {
638 .map(|(span, snippet)| SubstitutionPart { snippet, span })
641 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
648 /// Prints out a message with for a multipart suggestion without showing the suggested code.
650 /// This is intended to be used for suggestions that are obvious in what the changes need to
651 /// be from the message, showing the span label inline would be visually unpleasant
652 /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
653 /// improve understandability.
654 pub fn tool_only_multipart_suggestion(
656 msg: impl Into<SubdiagnosticMessage>,
657 suggestion: Vec<(Span, String)>,
658 applicability: Applicability,
660 self.multipart_suggestion_with_style(
664 SuggestionStyle::CompletelyHidden,
668 /// Prints out a message with a suggested edit of the code.
670 /// In case of short messages and a simple suggestion, rustc displays it as a label:
673 /// try adding parentheses: `(tup.0).1`
678 /// * should not end in any punctuation (a `:` is added automatically)
679 /// * should not be a question (avoid language like "did you mean")
680 /// * should not contain any phrases like "the following", "as shown", etc.
681 /// * may look like "to do xyz, use" or "to do xyz, use abc"
682 /// * may contain a name of a function, variable, or type, but not whole expressions
684 /// See `CodeSuggestion` for more information.
685 pub fn span_suggestion(
688 msg: impl Into<SubdiagnosticMessage>,
689 suggestion: impl ToString,
690 applicability: Applicability,
692 self.span_suggestion_with_style(
697 SuggestionStyle::ShowCode,
702 /// [`Diagnostic::span_suggestion()`] but you can set the [`SuggestionStyle`].
703 pub fn span_suggestion_with_style(
706 msg: impl Into<SubdiagnosticMessage>,
707 suggestion: impl ToString,
708 applicability: Applicability,
709 style: SuggestionStyle,
712 !(sp.is_empty() && suggestion.to_string().is_empty()),
713 "Span must not be empty and have no suggestion"
715 self.push_suggestion(CodeSuggestion {
716 substitutions: vec![Substitution {
717 parts: vec![SubstitutionPart { snippet: suggestion.to_string(), span: sp }],
719 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
726 /// Always show the suggested change.
727 pub fn span_suggestion_verbose(
730 msg: impl Into<SubdiagnosticMessage>,
731 suggestion: impl ToString,
732 applicability: Applicability,
734 self.span_suggestion_with_style(
739 SuggestionStyle::ShowAlways,
744 /// Prints out a message with multiple suggested edits of the code.
745 /// See also [`Diagnostic::span_suggestion()`].
746 pub fn span_suggestions(
749 msg: impl Into<SubdiagnosticMessage>,
750 suggestions: impl IntoIterator<Item = String>,
751 applicability: Applicability,
753 self.span_suggestions_with_style(
758 SuggestionStyle::ShowCode,
762 /// [`Diagnostic::span_suggestions()`] but you can set the [`SuggestionStyle`].
763 pub fn span_suggestions_with_style(
766 msg: impl Into<SubdiagnosticMessage>,
767 suggestions: impl IntoIterator<Item = String>,
768 applicability: Applicability,
769 style: SuggestionStyle,
771 let mut suggestions: Vec<_> = suggestions.into_iter().collect();
775 !(sp.is_empty() && suggestions.iter().any(|suggestion| suggestion.is_empty())),
776 "Span must not be empty and have no suggestion"
779 let substitutions = suggestions
781 .map(|snippet| Substitution { parts: vec![SubstitutionPart { snippet, span: sp }] })
783 self.push_suggestion(CodeSuggestion {
785 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
792 /// Prints out a message with multiple suggested edits of the code, where each edit consists of
794 /// See also [`Diagnostic::multipart_suggestion()`].
795 pub fn multipart_suggestions(
797 msg: impl Into<SubdiagnosticMessage>,
798 suggestions: impl IntoIterator<Item = Vec<(Span, String)>>,
799 applicability: Applicability,
801 let suggestions: Vec<_> = suggestions.into_iter().collect();
805 .flat_map(|suggs| suggs)
806 .any(|(sp, suggestion)| sp.is_empty() && suggestion.is_empty())),
807 "Span must not be empty and have no suggestion"
810 self.push_suggestion(CodeSuggestion {
811 substitutions: suggestions
813 .map(|sugg| Substitution {
816 .map(|(span, snippet)| SubstitutionPart { snippet, span })
820 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
821 style: SuggestionStyle::ShowCode,
827 /// Prints out a message with a suggested edit of the code. If the suggestion is presented
828 /// inline, it will only show the message and not the suggestion.
830 /// See `CodeSuggestion` for more information.
831 pub fn span_suggestion_short(
834 msg: impl Into<SubdiagnosticMessage>,
835 suggestion: impl ToString,
836 applicability: Applicability,
838 self.span_suggestion_with_style(
843 SuggestionStyle::HideCodeInline,
848 /// Prints out a message for a suggestion without showing the suggested code.
850 /// This is intended to be used for suggestions that are obvious in what the changes need to
851 /// be from the message, showing the span label inline would be visually unpleasant
852 /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
853 /// improve understandability.
854 pub fn span_suggestion_hidden(
857 msg: impl Into<SubdiagnosticMessage>,
858 suggestion: impl ToString,
859 applicability: Applicability,
861 self.span_suggestion_with_style(
866 SuggestionStyle::HideCodeAlways,
871 /// Adds a suggestion to the JSON output that will not be shown in the CLI.
873 /// This is intended to be used for suggestions that are *very* obvious in what the changes
874 /// need to be from the message, but we still want other tools to be able to apply them.
875 pub fn tool_only_span_suggestion(
878 msg: impl Into<SubdiagnosticMessage>,
879 suggestion: impl ToString,
880 applicability: Applicability,
882 self.span_suggestion_with_style(
887 SuggestionStyle::CompletelyHidden,
892 /// Add a subdiagnostic from a type that implements `Subdiagnostic` (see
893 /// [rustc_macros::Subdiagnostic]).
894 pub fn subdiagnostic(&mut self, subdiagnostic: impl AddToDiagnostic) -> &mut Self {
895 subdiagnostic.add_to_diagnostic(self);
899 /// Add a subdiagnostic from a type that implements `Subdiagnostic` (see
900 /// [rustc_macros::Subdiagnostic]). Performs eager translation of any translatable messages
901 /// used in the subdiagnostic, so suitable for use with repeated messages (i.e. re-use of
902 /// interpolated variables).
903 pub fn eager_subdiagnostic(
905 handler: &crate::Handler,
906 subdiagnostic: impl AddToDiagnostic,
908 subdiagnostic.add_to_diagnostic_with(self, |diag, msg| {
909 let args = diag.args();
910 let msg = diag.subdiagnostic_message_to_diagnostic_message(msg);
911 handler.eagerly_translate(msg, args)
916 pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self {
917 self.span = sp.into();
918 if let Some(span) = self.span.primary_span() {
919 self.sort_span = span;
924 pub fn set_is_lint(&mut self) -> &mut Self {
929 pub fn code(&mut self, s: DiagnosticId) -> &mut Self {
934 pub fn clear_code(&mut self) -> &mut Self {
939 pub fn get_code(&self) -> Option<DiagnosticId> {
943 pub fn set_primary_message(&mut self, msg: impl Into<DiagnosticMessage>) -> &mut Self {
944 self.message[0] = (msg.into(), Style::NoStyle);
948 // Exact iteration order of diagnostic arguments shouldn't make a difference to output because
949 // they're only used in interpolation.
950 #[allow(rustc::potential_query_instability)]
951 pub fn args<'a>(&'a self) -> impl Iterator<Item = DiagnosticArg<'a, 'static>> {
957 name: impl Into<Cow<'static, str>>,
958 arg: impl IntoDiagnosticArg,
960 self.args.insert(name.into(), arg.into_diagnostic_arg());
966 args: FxHashMap<DiagnosticArgName<'static>, DiagnosticArgValue<'static>>,
971 pub fn styled_message(&self) -> &[(DiagnosticMessage, Style)] {
975 /// Helper function that takes a `SubdiagnosticMessage` and returns a `DiagnosticMessage` by
976 /// combining it with the primary message of the diagnostic (if translatable, otherwise it just
977 /// passes the user's string along).
978 pub(crate) fn subdiagnostic_message_to_diagnostic_message(
980 attr: impl Into<SubdiagnosticMessage>,
981 ) -> DiagnosticMessage {
983 self.message.iter().map(|(msg, _)| msg).next().expect("diagnostic with no messages");
984 msg.with_subdiagnostic_message(attr.into())
987 /// Convenience function for internal use, clients should use one of the
988 /// public methods above.
990 /// Used by `proc_macro_server` for implementing `server::Diagnostic`.
994 message: impl Into<SubdiagnosticMessage>,
996 render_span: Option<MultiSpan>,
998 let sub = SubDiagnostic {
1001 self.subdiagnostic_message_to_diagnostic_message(message),
1007 self.children.push(sub);
1010 /// Convenience function for internal use, clients should use one of the
1011 /// public methods above.
1012 fn sub_with_highlights<M: Into<SubdiagnosticMessage>>(
1015 message: Vec<(M, Style)>,
1017 render_span: Option<MultiSpan>,
1019 let message = message
1021 .map(|m| (self.subdiagnostic_message_to_diagnostic_message(m.0), m.1))
1023 let sub = SubDiagnostic { level, message, span, render_span };
1024 self.children.push(sub);
1027 /// Fields used for Hash, and PartialEq trait
1032 &[(DiagnosticMessage, Style)],
1033 &Option<DiagnosticId>,
1035 &Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
1036 Option<&[SubDiagnostic]>,
1044 (if self.is_lint { None } else { Some(&self.children) }),
1049 impl Hash for Diagnostic {
1050 fn hash<H>(&self, state: &mut H)
1054 self.keys().hash(state);
1058 impl PartialEq for Diagnostic {
1059 fn eq(&self, other: &Self) -> bool {
1060 self.keys() == other.keys()