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 if span_label.is_primary {
374 self.span.push_span_label(after, label);
376 self.span.push_span_label(span_label.span, label);
383 pub fn note_expected_found(
385 expected_label: &dyn fmt::Display,
386 expected: DiagnosticStyledString,
387 found_label: &dyn fmt::Display,
388 found: DiagnosticStyledString,
390 self.note_expected_found_extra(expected_label, expected, found_label, found, &"", &"")
393 pub fn note_unsuccessful_coercion(
395 expected: DiagnosticStyledString,
396 found: DiagnosticStyledString,
398 let mut msg: Vec<_> = vec![("required when trying to coerce from type `", Style::NoStyle)];
399 msg.extend(expected.0.iter().map(|x| match *x {
400 StringPart::Normal(ref s) => (s.as_str(), Style::NoStyle),
401 StringPart::Highlighted(ref s) => (s.as_str(), Style::Highlight),
403 msg.push(("` to type '", Style::NoStyle));
404 msg.extend(found.0.iter().map(|x| match *x {
405 StringPart::Normal(ref s) => (s.as_str(), Style::NoStyle),
406 StringPart::Highlighted(ref s) => (s.as_str(), Style::Highlight),
408 msg.push(("`", Style::NoStyle));
410 // For now, just attach these as notes
411 self.highlighted_note(msg);
415 pub fn note_expected_found_extra(
417 expected_label: &dyn fmt::Display,
418 expected: DiagnosticStyledString,
419 found_label: &dyn fmt::Display,
420 found: DiagnosticStyledString,
421 expected_extra: &dyn fmt::Display,
422 found_extra: &dyn fmt::Display,
424 let expected_label = expected_label.to_string();
425 let expected_label = if expected_label.is_empty() {
426 "expected".to_string()
428 format!("expected {}", expected_label)
430 let found_label = found_label.to_string();
431 let found_label = if found_label.is_empty() {
434 format!("found {}", found_label)
436 let (found_padding, expected_padding) = if expected_label.len() > found_label.len() {
437 (expected_label.len() - found_label.len(), 0)
439 (0, found_label.len() - expected_label.len())
441 let mut msg: Vec<_> =
442 vec![(format!("{}{} `", " ".repeat(expected_padding), expected_label), Style::NoStyle)];
443 msg.extend(expected.0.iter().map(|x| match *x {
444 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
445 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
447 msg.push((format!("`{}\n", expected_extra), Style::NoStyle));
448 msg.push((format!("{}{} `", " ".repeat(found_padding), found_label), Style::NoStyle));
449 msg.extend(found.0.iter().map(|x| match *x {
450 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
451 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
453 msg.push((format!("`{}", found_extra), Style::NoStyle));
455 // For now, just attach these as notes.
456 self.highlighted_note(msg);
460 pub fn note_trait_signature(&mut self, name: Symbol, signature: String) -> &mut Self {
461 self.highlighted_note(vec![
462 (format!("`{}` from trait: `", name), Style::NoStyle),
463 (signature, Style::Highlight),
464 ("`".to_string(), Style::NoStyle),
469 /// Add a note attached to this diagnostic.
470 #[rustc_lint_diagnostics]
471 pub fn note(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
472 self.sub(Level::Note, msg, MultiSpan::new(), None);
476 pub fn highlighted_note<M: Into<SubdiagnosticMessage>>(
478 msg: Vec<(M, Style)>,
480 self.sub_with_highlights(Level::Note, msg, MultiSpan::new(), None);
484 /// Prints the span with a note above it.
485 /// This is like [`Diagnostic::note()`], but it gets its own span.
486 pub fn note_once(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
487 self.sub(Level::OnceNote, msg, MultiSpan::new(), None);
491 /// Prints the span with a note above it.
492 /// This is like [`Diagnostic::note()`], but it gets its own span.
493 #[rustc_lint_diagnostics]
494 pub fn span_note<S: Into<MultiSpan>>(
497 msg: impl Into<SubdiagnosticMessage>,
499 self.sub(Level::Note, msg, sp.into(), None);
503 /// Prints the span with a note above it.
504 /// This is like [`Diagnostic::note()`], but it gets its own span.
505 pub fn span_note_once<S: Into<MultiSpan>>(
508 msg: impl Into<SubdiagnosticMessage>,
510 self.sub(Level::OnceNote, msg, sp.into(), None);
514 /// Add a warning attached to this diagnostic.
515 #[rustc_lint_diagnostics]
516 pub fn warn(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
517 self.sub(Level::Warning(None), msg, MultiSpan::new(), None);
521 /// Prints the span with a warning above it.
522 /// This is like [`Diagnostic::warn()`], but it gets its own span.
523 #[rustc_lint_diagnostics]
524 pub fn span_warn<S: Into<MultiSpan>>(
527 msg: impl Into<SubdiagnosticMessage>,
529 self.sub(Level::Warning(None), msg, sp.into(), None);
533 /// Add a help message attached to this diagnostic.
534 #[rustc_lint_diagnostics]
535 pub fn help(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
536 self.sub(Level::Help, msg, MultiSpan::new(), None);
540 /// Add a help message attached to this diagnostic with a customizable highlighted message.
541 pub fn highlighted_help(&mut self, msg: Vec<(String, Style)>) -> &mut Self {
542 self.sub_with_highlights(Level::Help, msg, MultiSpan::new(), None);
546 /// Prints the span with some help above it.
547 /// This is like [`Diagnostic::help()`], but it gets its own span.
548 #[rustc_lint_diagnostics]
549 pub fn span_help<S: Into<MultiSpan>>(
552 msg: impl Into<SubdiagnosticMessage>,
554 self.sub(Level::Help, msg, sp.into(), None);
558 /// Help the user upgrade to the latest edition.
559 /// This is factored out to make sure it does the right thing with `Cargo.toml`.
560 pub fn help_use_latest_edition(&mut self) -> &mut Self {
561 if std::env::var_os("CARGO").is_some() {
562 self.help(&format!("set `edition = \"{}\"` in `Cargo.toml`", LATEST_STABLE_EDITION));
564 self.help(&format!("pass `--edition {}` to `rustc`", LATEST_STABLE_EDITION));
566 self.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
570 /// Disallow attaching suggestions this diagnostic.
571 /// Any suggestions attached e.g. with the `span_suggestion_*` methods
572 /// (before and after the call to `disable_suggestions`) will be ignored.
573 pub fn disable_suggestions(&mut self) -> &mut Self {
574 self.suggestions = Err(SuggestionsDisabled);
578 /// Clear any existing suggestions.
579 pub fn clear_suggestions(&mut self) -> &mut Self {
580 if let Ok(suggestions) = &mut self.suggestions {
586 /// Helper for pushing to `self.suggestions`, if available (not disable).
587 fn push_suggestion(&mut self, suggestion: CodeSuggestion) {
588 if let Ok(suggestions) = &mut self.suggestions {
589 suggestions.push(suggestion);
593 /// Show a suggestion that has multiple parts to it.
594 /// In other words, multiple changes need to be applied as part of this suggestion.
595 pub fn multipart_suggestion(
597 msg: impl Into<SubdiagnosticMessage>,
598 suggestion: Vec<(Span, String)>,
599 applicability: Applicability,
601 self.multipart_suggestion_with_style(
605 SuggestionStyle::ShowCode,
609 /// Show a suggestion that has multiple parts to it, always as it's own subdiagnostic.
610 /// In other words, multiple changes need to be applied as part of this suggestion.
611 pub fn multipart_suggestion_verbose(
613 msg: impl Into<SubdiagnosticMessage>,
614 suggestion: Vec<(Span, String)>,
615 applicability: Applicability,
617 self.multipart_suggestion_with_style(
621 SuggestionStyle::ShowAlways,
624 /// [`Diagnostic::multipart_suggestion()`] but you can set the [`SuggestionStyle`].
625 pub fn multipart_suggestion_with_style(
627 msg: impl Into<SubdiagnosticMessage>,
628 suggestion: Vec<(Span, String)>,
629 applicability: Applicability,
630 style: SuggestionStyle,
632 assert!(!suggestion.is_empty());
634 !(suggestion.iter().any(|(sp, text)| sp.is_empty() && text.is_empty())),
635 "Span must not be empty and have no suggestion"
638 self.push_suggestion(CodeSuggestion {
639 substitutions: vec![Substitution {
642 .map(|(span, snippet)| SubstitutionPart { snippet, span })
645 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
652 /// Prints out a message with for a multipart suggestion without showing the suggested code.
654 /// This is intended to be used for suggestions that are obvious in what the changes need to
655 /// be from the message, showing the span label inline would be visually unpleasant
656 /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
657 /// improve understandability.
658 pub fn tool_only_multipart_suggestion(
660 msg: impl Into<SubdiagnosticMessage>,
661 suggestion: Vec<(Span, String)>,
662 applicability: Applicability,
664 self.multipart_suggestion_with_style(
668 SuggestionStyle::CompletelyHidden,
672 /// Prints out a message with a suggested edit of the code.
674 /// In case of short messages and a simple suggestion, rustc displays it as a label:
677 /// try adding parentheses: `(tup.0).1`
682 /// * should not end in any punctuation (a `:` is added automatically)
683 /// * should not be a question (avoid language like "did you mean")
684 /// * should not contain any phrases like "the following", "as shown", etc.
685 /// * may look like "to do xyz, use" or "to do xyz, use abc"
686 /// * may contain a name of a function, variable, or type, but not whole expressions
688 /// See `CodeSuggestion` for more information.
689 pub fn span_suggestion(
692 msg: impl Into<SubdiagnosticMessage>,
693 suggestion: impl ToString,
694 applicability: Applicability,
696 self.span_suggestion_with_style(
701 SuggestionStyle::ShowCode,
706 /// [`Diagnostic::span_suggestion()`] but you can set the [`SuggestionStyle`].
707 pub fn span_suggestion_with_style(
710 msg: impl Into<SubdiagnosticMessage>,
711 suggestion: impl ToString,
712 applicability: Applicability,
713 style: SuggestionStyle,
716 !(sp.is_empty() && suggestion.to_string().is_empty()),
717 "Span must not be empty and have no suggestion"
719 self.push_suggestion(CodeSuggestion {
720 substitutions: vec![Substitution {
721 parts: vec![SubstitutionPart { snippet: suggestion.to_string(), span: sp }],
723 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
730 /// Always show the suggested change.
731 pub fn span_suggestion_verbose(
734 msg: impl Into<SubdiagnosticMessage>,
735 suggestion: impl ToString,
736 applicability: Applicability,
738 self.span_suggestion_with_style(
743 SuggestionStyle::ShowAlways,
748 /// Prints out a message with multiple suggested edits of the code.
749 /// See also [`Diagnostic::span_suggestion()`].
750 pub fn span_suggestions(
753 msg: impl Into<SubdiagnosticMessage>,
754 suggestions: impl IntoIterator<Item = String>,
755 applicability: Applicability,
757 self.span_suggestions_with_style(
762 SuggestionStyle::ShowCode,
766 /// [`Diagnostic::span_suggestions()`] but you can set the [`SuggestionStyle`].
767 pub fn span_suggestions_with_style(
770 msg: impl Into<SubdiagnosticMessage>,
771 suggestions: impl IntoIterator<Item = String>,
772 applicability: Applicability,
773 style: SuggestionStyle,
775 let mut suggestions: Vec<_> = suggestions.into_iter().collect();
779 !(sp.is_empty() && suggestions.iter().any(|suggestion| suggestion.is_empty())),
780 "Span must not be empty and have no suggestion"
783 let substitutions = suggestions
785 .map(|snippet| Substitution { parts: vec![SubstitutionPart { snippet, span: sp }] })
787 self.push_suggestion(CodeSuggestion {
789 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
796 /// Prints out a message with multiple suggested edits of the code, where each edit consists of
798 /// See also [`Diagnostic::multipart_suggestion()`].
799 pub fn multipart_suggestions(
801 msg: impl Into<SubdiagnosticMessage>,
802 suggestions: impl IntoIterator<Item = Vec<(Span, String)>>,
803 applicability: Applicability,
805 let suggestions: Vec<_> = suggestions.into_iter().collect();
810 .any(|(sp, suggestion)| sp.is_empty() && suggestion.is_empty())),
811 "Span must not be empty and have no suggestion"
814 self.push_suggestion(CodeSuggestion {
815 substitutions: suggestions
817 .map(|sugg| Substitution {
820 .map(|(span, snippet)| SubstitutionPart { snippet, span })
824 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
825 style: SuggestionStyle::ShowCode,
831 /// Prints out a message with a suggested edit of the code. If the suggestion is presented
832 /// inline, it will only show the message and not the suggestion.
834 /// See `CodeSuggestion` for more information.
835 pub fn span_suggestion_short(
838 msg: impl Into<SubdiagnosticMessage>,
839 suggestion: impl ToString,
840 applicability: Applicability,
842 self.span_suggestion_with_style(
847 SuggestionStyle::HideCodeInline,
852 /// Prints out a message for a suggestion without showing the suggested code.
854 /// This is intended to be used for suggestions that are obvious in what the changes need to
855 /// be from the message, showing the span label inline would be visually unpleasant
856 /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
857 /// improve understandability.
858 pub fn span_suggestion_hidden(
861 msg: impl Into<SubdiagnosticMessage>,
862 suggestion: impl ToString,
863 applicability: Applicability,
865 self.span_suggestion_with_style(
870 SuggestionStyle::HideCodeAlways,
875 /// Adds a suggestion to the JSON output that will not be shown in the CLI.
877 /// This is intended to be used for suggestions that are *very* obvious in what the changes
878 /// need to be from the message, but we still want other tools to be able to apply them.
879 pub fn tool_only_span_suggestion(
882 msg: impl Into<SubdiagnosticMessage>,
883 suggestion: impl ToString,
884 applicability: Applicability,
886 self.span_suggestion_with_style(
891 SuggestionStyle::CompletelyHidden,
896 /// Add a subdiagnostic from a type that implements `Subdiagnostic` (see
897 /// [rustc_macros::Subdiagnostic]).
898 pub fn subdiagnostic(&mut self, subdiagnostic: impl AddToDiagnostic) -> &mut Self {
899 subdiagnostic.add_to_diagnostic(self);
903 /// Add a subdiagnostic from a type that implements `Subdiagnostic` (see
904 /// [rustc_macros::Subdiagnostic]). Performs eager translation of any translatable messages
905 /// used in the subdiagnostic, so suitable for use with repeated messages (i.e. re-use of
906 /// interpolated variables).
907 pub fn eager_subdiagnostic(
909 handler: &crate::Handler,
910 subdiagnostic: impl AddToDiagnostic,
912 subdiagnostic.add_to_diagnostic_with(self, |diag, msg| {
913 let args = diag.args();
914 let msg = diag.subdiagnostic_message_to_diagnostic_message(msg);
915 handler.eagerly_translate(msg, args)
920 pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self {
921 self.span = sp.into();
922 if let Some(span) = self.span.primary_span() {
923 self.sort_span = span;
928 pub fn set_is_lint(&mut self) -> &mut Self {
933 pub fn code(&mut self, s: DiagnosticId) -> &mut Self {
938 pub fn clear_code(&mut self) -> &mut Self {
943 pub fn get_code(&self) -> Option<DiagnosticId> {
947 pub fn set_primary_message(&mut self, msg: impl Into<DiagnosticMessage>) -> &mut Self {
948 self.message[0] = (msg.into(), Style::NoStyle);
952 // Exact iteration order of diagnostic arguments shouldn't make a difference to output because
953 // they're only used in interpolation.
954 #[allow(rustc::potential_query_instability)]
955 pub fn args<'a>(&'a self) -> impl Iterator<Item = DiagnosticArg<'a, 'static>> {
961 name: impl Into<Cow<'static, str>>,
962 arg: impl IntoDiagnosticArg,
964 self.args.insert(name.into(), arg.into_diagnostic_arg());
970 args: FxHashMap<DiagnosticArgName<'static>, DiagnosticArgValue<'static>>,
975 pub fn styled_message(&self) -> &[(DiagnosticMessage, Style)] {
979 /// Helper function that takes a `SubdiagnosticMessage` and returns a `DiagnosticMessage` by
980 /// combining it with the primary message of the diagnostic (if translatable, otherwise it just
981 /// passes the user's string along).
982 pub(crate) fn subdiagnostic_message_to_diagnostic_message(
984 attr: impl Into<SubdiagnosticMessage>,
985 ) -> DiagnosticMessage {
987 self.message.iter().map(|(msg, _)| msg).next().expect("diagnostic with no messages");
988 msg.with_subdiagnostic_message(attr.into())
991 /// Convenience function for internal use, clients should use one of the
992 /// public methods above.
994 /// Used by `proc_macro_server` for implementing `server::Diagnostic`.
998 message: impl Into<SubdiagnosticMessage>,
1000 render_span: Option<MultiSpan>,
1002 let sub = SubDiagnostic {
1005 self.subdiagnostic_message_to_diagnostic_message(message),
1011 self.children.push(sub);
1014 /// Convenience function for internal use, clients should use one of the
1015 /// public methods above.
1016 fn sub_with_highlights<M: Into<SubdiagnosticMessage>>(
1019 message: Vec<(M, Style)>,
1021 render_span: Option<MultiSpan>,
1023 let message = message
1025 .map(|m| (self.subdiagnostic_message_to_diagnostic_message(m.0), m.1))
1027 let sub = SubDiagnostic { level, message, span, render_span };
1028 self.children.push(sub);
1031 /// Fields used for Hash, and PartialEq trait
1036 &[(DiagnosticMessage, Style)],
1037 &Option<DiagnosticId>,
1039 &Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
1040 Option<&[SubDiagnostic]>,
1048 (if self.is_lint { None } else { Some(&self.children) }),
1053 impl Hash for Diagnostic {
1054 fn hash<H>(&self, state: &mut H)
1058 self.keys().hash(state);
1062 impl PartialEq for Diagnostic {
1063 fn eq(&self, other: &Self) -> bool {
1064 self.keys() == other.keys()