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};
15 use std::panic::Location;
17 /// Error type for `Diagnostic`'s `suggestions` field, indicating that
18 /// `.disable_suggestions()` was called on the `Diagnostic`.
19 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
20 pub struct SuggestionsDisabled;
22 /// Simplified version of `FluentArg` that can implement `Encodable` and `Decodable`. Collection of
23 /// `DiagnosticArg` are converted to `FluentArgs` (consuming the collection) at the start of
24 /// diagnostic emission.
25 pub type DiagnosticArg<'iter, 'source> =
26 (&'iter DiagnosticArgName<'source>, &'iter DiagnosticArgValue<'source>);
28 /// Name of a diagnostic argument.
29 pub type DiagnosticArgName<'source> = Cow<'source, str>;
31 /// Simplified version of `FluentValue` that can implement `Encodable` and `Decodable`. Converted
32 /// to a `FluentValue` by the emitter to be used in diagnostic translation.
33 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
34 pub enum DiagnosticArgValue<'source> {
35 Str(Cow<'source, str>),
39 /// Converts a value of a type into a `DiagnosticArg` (typically a field of an `IntoDiagnostic`
40 /// struct). Implemented as a custom trait rather than `From` so that it is implemented on the type
41 /// being converted rather than on `DiagnosticArgValue`, which enables types from other `rustc_*`
42 /// crates to implement this.
43 pub trait IntoDiagnosticArg {
44 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static>;
47 impl<'source> IntoDiagnosticArg for DiagnosticArgValue<'source> {
48 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
50 DiagnosticArgValue::Str(s) => DiagnosticArgValue::Str(Cow::Owned(s.into_owned())),
51 DiagnosticArgValue::Number(n) => DiagnosticArgValue::Number(n),
56 impl<'source> Into<FluentValue<'source>> for DiagnosticArgValue<'source> {
57 fn into(self) -> FluentValue<'source> {
59 DiagnosticArgValue::Str(s) => From::from(s),
60 DiagnosticArgValue::Number(n) => From::from(n),
65 /// Trait implemented by error types. This should not be implemented manually. Instead, use
66 /// `#[derive(Subdiagnostic)]` -- see [rustc_macros::Subdiagnostic].
67 #[rustc_diagnostic_item = "AddToDiagnostic"]
68 pub trait AddToDiagnostic
72 /// Add a subdiagnostic to an existing diagnostic.
73 fn add_to_diagnostic(self, diag: &mut Diagnostic) {
74 self.add_to_diagnostic_with(diag, |_, m| m);
77 /// Add a subdiagnostic to an existing diagnostic where `f` is invoked on every message used
78 /// (to optionally perform eager translation).
79 fn add_to_diagnostic_with<F>(self, diag: &mut Diagnostic, f: F)
81 F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage;
84 /// Trait implemented by lint types. This should not be implemented manually. Instead, use
85 /// `#[derive(LintDiagnostic)]` -- see [rustc_macros::LintDiagnostic].
86 #[rustc_diagnostic_item = "DecorateLint"]
87 pub trait DecorateLint<'a, G: EmissionGuarantee> {
88 /// Decorate and emit a lint.
91 diag: &'b mut DiagnosticBuilder<'a, G>,
92 ) -> &'b mut DiagnosticBuilder<'a, G>;
94 fn msg(&self) -> DiagnosticMessage;
98 #[derive(Clone, Debug, Encodable, Decodable)]
99 pub struct Diagnostic {
100 // NOTE(eddyb) this is private to disallow arbitrary after-the-fact changes,
101 // outside of what methods in this crate themselves allow.
102 pub(crate) level: Level,
104 pub message: Vec<(DiagnosticMessage, Style)>,
105 pub code: Option<DiagnosticId>,
107 pub children: Vec<SubDiagnostic>,
108 pub suggestions: Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
109 args: FxHashMap<DiagnosticArgName<'static>, DiagnosticArgValue<'static>>,
111 /// This is not used for highlighting or rendering any error message. Rather, it can be used
112 /// as a sort key to sort a buffer of diagnostics. By default, it is the primary span of
113 /// `span` if there is one. Otherwise, it is `DUMMY_SP`.
116 /// If diagnostic is from Lint, custom hash function ignores notes
117 /// otherwise hash is based on the all the fields
120 /// With `-Ztrack_diagnostics` enabled,
121 /// we print where in rustc this error was emitted.
122 pub emitted_at: DiagnosticLocation,
125 #[derive(Clone, Debug, Encodable, Decodable)]
126 pub struct DiagnosticLocation {
127 file: Cow<'static, str>,
132 impl DiagnosticLocation {
134 fn caller() -> Self {
135 let loc = Location::caller();
136 DiagnosticLocation { file: loc.file().into(), line: loc.line(), col: loc.column() }
140 impl fmt::Display for DiagnosticLocation {
141 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142 write!(f, "{}:{}:{}", self.file, self.line, self.col)
146 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
147 pub enum DiagnosticId {
149 Lint { name: String, has_future_breakage: bool, is_force_warn: bool },
152 /// A "sub"-diagnostic attached to a parent diagnostic.
153 /// For example, a note attached to an error.
154 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
155 pub struct SubDiagnostic {
157 pub message: Vec<(DiagnosticMessage, Style)>,
159 pub render_span: Option<MultiSpan>,
162 #[derive(Debug, PartialEq, Eq)]
163 pub struct DiagnosticStyledString(pub Vec<StringPart>);
165 impl DiagnosticStyledString {
166 pub fn new() -> DiagnosticStyledString {
167 DiagnosticStyledString(vec![])
169 pub fn push_normal<S: Into<String>>(&mut self, t: S) {
170 self.0.push(StringPart::Normal(t.into()));
172 pub fn push_highlighted<S: Into<String>>(&mut self, t: S) {
173 self.0.push(StringPart::Highlighted(t.into()));
175 pub fn push<S: Into<String>>(&mut self, t: S, highlight: bool) {
177 self.push_highlighted(t);
182 pub fn normal<S: Into<String>>(t: S) -> DiagnosticStyledString {
183 DiagnosticStyledString(vec![StringPart::Normal(t.into())])
186 pub fn highlighted<S: Into<String>>(t: S) -> DiagnosticStyledString {
187 DiagnosticStyledString(vec![StringPart::Highlighted(t.into())])
190 pub fn content(&self) -> String {
191 self.0.iter().map(|x| x.content()).collect::<String>()
195 #[derive(Debug, PartialEq, Eq)]
196 pub enum StringPart {
202 pub fn content(&self) -> &str {
204 &StringPart::Normal(ref s) | &StringPart::Highlighted(ref s) => s,
211 pub fn new<M: Into<DiagnosticMessage>>(level: Level, message: M) -> Self {
212 Diagnostic::new_with_code(level, None, message)
216 pub fn new_with_messages(level: Level, messages: Vec<(DiagnosticMessage, Style)>) -> Self {
221 span: MultiSpan::new(),
223 suggestions: Ok(vec![]),
224 args: Default::default(),
227 emitted_at: DiagnosticLocation::caller(),
232 pub fn new_with_code<M: Into<DiagnosticMessage>>(
234 code: Option<DiagnosticId>,
239 message: vec![(message.into(), Style::NoStyle)],
241 span: MultiSpan::new(),
243 suggestions: Ok(vec![]),
244 args: Default::default(),
247 emitted_at: DiagnosticLocation::caller(),
252 pub fn level(&self) -> Level {
256 pub fn is_error(&self) -> bool {
261 | Level::Error { .. }
262 | Level::FailureNote => true,
269 | Level::Expect(_) => false,
273 pub fn update_unstable_expectation_id(
275 unstable_to_stable: &FxHashMap<LintExpectationId, LintExpectationId>,
277 if let Level::Expect(expectation_id) | Level::Warning(Some(expectation_id)) =
280 if expectation_id.is_stable() {
284 // The unstable to stable map only maps the unstable `AttrId` to a stable `HirId` with an attribute index.
285 // The lint index inside the attribute is manually transferred here.
286 let lint_index = expectation_id.get_lint_index();
287 expectation_id.set_lint_index(None);
288 let mut stable_id = unstable_to_stable
289 .get(&expectation_id)
290 .expect("each unstable `LintExpectationId` must have a matching stable id")
293 stable_id.set_lint_index(lint_index);
294 *expectation_id = stable_id;
298 pub fn has_future_breakage(&self) -> bool {
300 Some(DiagnosticId::Lint { has_future_breakage, .. }) => has_future_breakage,
305 pub fn is_force_warn(&self) -> bool {
307 Some(DiagnosticId::Lint { is_force_warn, .. }) => is_force_warn,
312 /// Delay emission of this diagnostic as a bug.
314 /// This can be useful in contexts where an error indicates a bug but
315 /// typically this only happens when other compilation errors have already
316 /// happened. In those cases this can be used to defer emission of this
317 /// diagnostic as a bug in the compiler only if no other errors have been
320 /// In the meantime, though, callsites are required to deal with the "bug"
321 /// locally in whichever way makes the most sense.
323 pub fn downgrade_to_delayed_bug(&mut self) -> &mut Self {
326 "downgrade_to_delayed_bug: cannot downgrade {:?} to DelayedBug: not an error",
329 self.level = Level::DelayedBug;
334 /// Adds a span/label to be included in the resulting snippet.
336 /// This is pushed onto the [`MultiSpan`] that was created when the diagnostic
337 /// was first built. That means it will be shown together with the original
338 /// span/label, *not* a span added by one of the `span_{note,warn,help,suggestions}` methods.
340 /// This span is *not* considered a ["primary span"][`MultiSpan`]; only
341 /// the `Span` supplied when creating the diagnostic is primary.
342 #[rustc_lint_diagnostics]
343 pub fn span_label(&mut self, span: Span, label: impl Into<SubdiagnosticMessage>) -> &mut Self {
344 self.span.push_span_label(span, self.subdiagnostic_message_to_diagnostic_message(label));
348 /// Labels all the given spans with the provided label.
349 /// See [`Self::span_label()`] for more information.
352 spans: impl IntoIterator<Item = Span>,
353 label: impl AsRef<str>,
355 let label = label.as_ref();
357 self.span_label(span, label);
362 pub fn replace_span_with(&mut self, after: Span) -> &mut Self {
363 let before = self.span.clone();
364 self.set_span(after);
365 for span_label in before.span_labels() {
366 if let Some(label) = span_label.label {
367 self.span.push_span_label(after, label);
373 pub fn note_expected_found(
375 expected_label: &dyn fmt::Display,
376 expected: DiagnosticStyledString,
377 found_label: &dyn fmt::Display,
378 found: DiagnosticStyledString,
380 self.note_expected_found_extra(expected_label, expected, found_label, found, &"", &"")
383 pub fn note_unsuccessful_coercion(
385 expected: DiagnosticStyledString,
386 found: DiagnosticStyledString,
388 let mut msg: Vec<_> = vec![("required when trying to coerce from type `", Style::NoStyle)];
389 msg.extend(expected.0.iter().map(|x| match *x {
390 StringPart::Normal(ref s) => (s.as_str(), Style::NoStyle),
391 StringPart::Highlighted(ref s) => (s.as_str(), Style::Highlight),
393 msg.push(("` to type '", Style::NoStyle));
394 msg.extend(found.0.iter().map(|x| match *x {
395 StringPart::Normal(ref s) => (s.as_str(), Style::NoStyle),
396 StringPart::Highlighted(ref s) => (s.as_str(), Style::Highlight),
398 msg.push(("`", Style::NoStyle));
400 // For now, just attach these as notes
401 self.highlighted_note(msg);
405 pub fn note_expected_found_extra(
407 expected_label: &dyn fmt::Display,
408 expected: DiagnosticStyledString,
409 found_label: &dyn fmt::Display,
410 found: DiagnosticStyledString,
411 expected_extra: &dyn fmt::Display,
412 found_extra: &dyn fmt::Display,
414 let expected_label = expected_label.to_string();
415 let expected_label = if expected_label.is_empty() {
416 "expected".to_string()
418 format!("expected {}", expected_label)
420 let found_label = found_label.to_string();
421 let found_label = if found_label.is_empty() {
424 format!("found {}", found_label)
426 let (found_padding, expected_padding) = if expected_label.len() > found_label.len() {
427 (expected_label.len() - found_label.len(), 0)
429 (0, found_label.len() - expected_label.len())
431 let mut msg: Vec<_> =
432 vec![(format!("{}{} `", " ".repeat(expected_padding), expected_label), Style::NoStyle)];
433 msg.extend(expected.0.iter().map(|x| match *x {
434 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
435 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
437 msg.push((format!("`{}\n", expected_extra), Style::NoStyle));
438 msg.push((format!("{}{} `", " ".repeat(found_padding), found_label), Style::NoStyle));
439 msg.extend(found.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!("`{}", found_extra), Style::NoStyle));
445 // For now, just attach these as notes.
446 self.highlighted_note(msg);
450 pub fn note_trait_signature(&mut self, name: Symbol, signature: String) -> &mut Self {
451 self.highlighted_note(vec![
452 (format!("`{}` from trait: `", name), Style::NoStyle),
453 (signature, Style::Highlight),
454 ("`".to_string(), Style::NoStyle),
459 /// Add a note attached to this diagnostic.
460 #[rustc_lint_diagnostics]
461 pub fn note(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
462 self.sub(Level::Note, msg, MultiSpan::new(), None);
466 pub fn highlighted_note<M: Into<SubdiagnosticMessage>>(
468 msg: Vec<(M, Style)>,
470 self.sub_with_highlights(Level::Note, msg, MultiSpan::new(), None);
474 /// Prints the span with a note above it.
475 /// This is like [`Diagnostic::note()`], but it gets its own span.
476 pub fn note_once(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
477 self.sub(Level::OnceNote, msg, MultiSpan::new(), None);
481 /// Prints the span with a note above it.
482 /// This is like [`Diagnostic::note()`], but it gets its own span.
483 #[rustc_lint_diagnostics]
484 pub fn span_note<S: Into<MultiSpan>>(
487 msg: impl Into<SubdiagnosticMessage>,
489 self.sub(Level::Note, msg, sp.into(), None);
493 /// Prints the span with a note above it.
494 /// This is like [`Diagnostic::note()`], but it gets its own span.
495 pub fn span_note_once<S: Into<MultiSpan>>(
498 msg: impl Into<SubdiagnosticMessage>,
500 self.sub(Level::OnceNote, msg, sp.into(), None);
504 /// Add a warning attached to this diagnostic.
505 #[rustc_lint_diagnostics]
506 pub fn warn(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
507 self.sub(Level::Warning(None), msg, MultiSpan::new(), None);
511 /// Prints the span with a warning above it.
512 /// This is like [`Diagnostic::warn()`], but it gets its own span.
513 #[rustc_lint_diagnostics]
514 pub fn span_warn<S: Into<MultiSpan>>(
517 msg: impl Into<SubdiagnosticMessage>,
519 self.sub(Level::Warning(None), msg, sp.into(), None);
523 /// Add a help message attached to this diagnostic.
524 #[rustc_lint_diagnostics]
525 pub fn help(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
526 self.sub(Level::Help, msg, MultiSpan::new(), None);
530 /// Add a help message attached to this diagnostic with a customizable highlighted message.
531 pub fn highlighted_help(&mut self, msg: Vec<(String, Style)>) -> &mut Self {
532 self.sub_with_highlights(Level::Help, msg, MultiSpan::new(), None);
536 /// Prints the span with some help above it.
537 /// This is like [`Diagnostic::help()`], but it gets its own span.
538 #[rustc_lint_diagnostics]
539 pub fn span_help<S: Into<MultiSpan>>(
542 msg: impl Into<SubdiagnosticMessage>,
544 self.sub(Level::Help, msg, sp.into(), None);
548 /// Help the user upgrade to the latest edition.
549 /// This is factored out to make sure it does the right thing with `Cargo.toml`.
550 pub fn help_use_latest_edition(&mut self) -> &mut Self {
551 if std::env::var_os("CARGO").is_some() {
552 self.help(&format!("set `edition = \"{}\"` in `Cargo.toml`", LATEST_STABLE_EDITION));
554 self.help(&format!("pass `--edition {}` to `rustc`", LATEST_STABLE_EDITION));
556 self.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
560 /// Disallow attaching suggestions this diagnostic.
561 /// Any suggestions attached e.g. with the `span_suggestion_*` methods
562 /// (before and after the call to `disable_suggestions`) will be ignored.
563 pub fn disable_suggestions(&mut self) -> &mut Self {
564 self.suggestions = Err(SuggestionsDisabled);
568 /// Clear any existing suggestions.
569 pub fn clear_suggestions(&mut self) -> &mut Self {
570 if let Ok(suggestions) = &mut self.suggestions {
576 /// Helper for pushing to `self.suggestions`, if available (not disable).
577 fn push_suggestion(&mut self, suggestion: CodeSuggestion) {
578 if let Ok(suggestions) = &mut self.suggestions {
579 suggestions.push(suggestion);
583 /// Show a suggestion that has multiple parts to it.
584 /// In other words, multiple changes need to be applied as part of this suggestion.
585 pub fn multipart_suggestion(
587 msg: impl Into<SubdiagnosticMessage>,
588 suggestion: Vec<(Span, String)>,
589 applicability: Applicability,
591 self.multipart_suggestion_with_style(
595 SuggestionStyle::ShowCode,
599 /// Show a suggestion that has multiple parts to it, always as it's own subdiagnostic.
600 /// In other words, multiple changes need to be applied as part of this suggestion.
601 pub fn multipart_suggestion_verbose(
603 msg: impl Into<SubdiagnosticMessage>,
604 suggestion: Vec<(Span, String)>,
605 applicability: Applicability,
607 self.multipart_suggestion_with_style(
611 SuggestionStyle::ShowAlways,
614 /// [`Diagnostic::multipart_suggestion()`] but you can set the [`SuggestionStyle`].
615 pub fn multipart_suggestion_with_style(
617 msg: impl Into<SubdiagnosticMessage>,
618 suggestion: Vec<(Span, String)>,
619 applicability: Applicability,
620 style: SuggestionStyle,
622 assert!(!suggestion.is_empty());
624 !(suggestion.iter().any(|(sp, text)| sp.is_empty() && text.is_empty())),
625 "Span must not be empty and have no suggestion"
628 self.push_suggestion(CodeSuggestion {
629 substitutions: vec![Substitution {
632 .map(|(span, snippet)| SubstitutionPart { snippet, span })
635 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
642 /// Prints out a message with for a multipart suggestion without showing the suggested code.
644 /// This is intended to be used for suggestions that are obvious in what the changes need to
645 /// be from the message, showing the span label inline would be visually unpleasant
646 /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
647 /// improve understandability.
648 pub fn tool_only_multipart_suggestion(
650 msg: impl Into<SubdiagnosticMessage>,
651 suggestion: Vec<(Span, String)>,
652 applicability: Applicability,
654 self.multipart_suggestion_with_style(
658 SuggestionStyle::CompletelyHidden,
662 /// Prints out a message with a suggested edit of the code.
664 /// In case of short messages and a simple suggestion, rustc displays it as a label:
667 /// try adding parentheses: `(tup.0).1`
672 /// * should not end in any punctuation (a `:` is added automatically)
673 /// * should not be a question (avoid language like "did you mean")
674 /// * should not contain any phrases like "the following", "as shown", etc.
675 /// * may look like "to do xyz, use" or "to do xyz, use abc"
676 /// * may contain a name of a function, variable, or type, but not whole expressions
678 /// See `CodeSuggestion` for more information.
679 pub fn span_suggestion(
682 msg: impl Into<SubdiagnosticMessage>,
683 suggestion: impl ToString,
684 applicability: Applicability,
686 self.span_suggestion_with_style(
691 SuggestionStyle::ShowCode,
696 /// [`Diagnostic::span_suggestion()`] but you can set the [`SuggestionStyle`].
697 pub fn span_suggestion_with_style(
700 msg: impl Into<SubdiagnosticMessage>,
701 suggestion: impl ToString,
702 applicability: Applicability,
703 style: SuggestionStyle,
706 !(sp.is_empty() && suggestion.to_string().is_empty()),
707 "Span must not be empty and have no suggestion"
709 self.push_suggestion(CodeSuggestion {
710 substitutions: vec![Substitution {
711 parts: vec![SubstitutionPart { snippet: suggestion.to_string(), span: sp }],
713 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
720 /// Always show the suggested change.
721 pub fn span_suggestion_verbose(
724 msg: impl Into<SubdiagnosticMessage>,
725 suggestion: impl ToString,
726 applicability: Applicability,
728 self.span_suggestion_with_style(
733 SuggestionStyle::ShowAlways,
738 /// Prints out a message with multiple suggested edits of the code.
739 /// See also [`Diagnostic::span_suggestion()`].
740 pub fn span_suggestions(
743 msg: impl Into<SubdiagnosticMessage>,
744 suggestions: impl IntoIterator<Item = String>,
745 applicability: Applicability,
747 self.span_suggestions_with_style(
752 SuggestionStyle::ShowCode,
756 /// [`Diagnostic::span_suggestions()`] but you can set the [`SuggestionStyle`].
757 pub fn span_suggestions_with_style(
760 msg: impl Into<SubdiagnosticMessage>,
761 suggestions: impl IntoIterator<Item = String>,
762 applicability: Applicability,
763 style: SuggestionStyle,
765 let mut suggestions: Vec<_> = suggestions.into_iter().collect();
769 !(sp.is_empty() && suggestions.iter().any(|suggestion| suggestion.is_empty())),
770 "Span must not be empty and have no suggestion"
773 let substitutions = suggestions
775 .map(|snippet| Substitution { parts: vec![SubstitutionPart { snippet, span: sp }] })
777 self.push_suggestion(CodeSuggestion {
779 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
786 /// Prints out a message with multiple suggested edits of the code, where each edit consists of
788 /// See also [`Diagnostic::multipart_suggestion()`].
789 pub fn multipart_suggestions(
791 msg: impl Into<SubdiagnosticMessage>,
792 suggestions: impl IntoIterator<Item = Vec<(Span, String)>>,
793 applicability: Applicability,
795 let suggestions: Vec<_> = suggestions.into_iter().collect();
799 .flat_map(|suggs| suggs)
800 .any(|(sp, suggestion)| sp.is_empty() && suggestion.is_empty())),
801 "Span must not be empty and have no suggestion"
804 self.push_suggestion(CodeSuggestion {
805 substitutions: suggestions
807 .map(|sugg| Substitution {
810 .map(|(span, snippet)| SubstitutionPart { snippet, span })
814 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
815 style: SuggestionStyle::ShowCode,
821 /// Prints out a message with a suggested edit of the code. If the suggestion is presented
822 /// inline, it will only show the message and not the suggestion.
824 /// See `CodeSuggestion` for more information.
825 pub fn span_suggestion_short(
828 msg: impl Into<SubdiagnosticMessage>,
829 suggestion: impl ToString,
830 applicability: Applicability,
832 self.span_suggestion_with_style(
837 SuggestionStyle::HideCodeInline,
842 /// Prints out a message for a suggestion without showing the suggested code.
844 /// This is intended to be used for suggestions that are obvious in what the changes need to
845 /// be from the message, showing the span label inline would be visually unpleasant
846 /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
847 /// improve understandability.
848 pub fn span_suggestion_hidden(
851 msg: impl Into<SubdiagnosticMessage>,
852 suggestion: impl ToString,
853 applicability: Applicability,
855 self.span_suggestion_with_style(
860 SuggestionStyle::HideCodeAlways,
865 /// Adds a suggestion to the JSON output that will not be shown in the CLI.
867 /// This is intended to be used for suggestions that are *very* obvious in what the changes
868 /// need to be from the message, but we still want other tools to be able to apply them.
869 pub fn tool_only_span_suggestion(
872 msg: impl Into<SubdiagnosticMessage>,
873 suggestion: impl ToString,
874 applicability: Applicability,
876 self.span_suggestion_with_style(
881 SuggestionStyle::CompletelyHidden,
886 /// Add a subdiagnostic from a type that implements `Subdiagnostic` (see
887 /// [rustc_macros::Subdiagnostic]).
888 pub fn subdiagnostic(&mut self, subdiagnostic: impl AddToDiagnostic) -> &mut Self {
889 subdiagnostic.add_to_diagnostic(self);
893 /// Add a subdiagnostic from a type that implements `Subdiagnostic` (see
894 /// [rustc_macros::Subdiagnostic]). Performs eager translation of any translatable messages
895 /// used in the subdiagnostic, so suitable for use with repeated messages (i.e. re-use of
896 /// interpolated variables).
897 pub fn eager_subdiagnostic(
899 handler: &crate::Handler,
900 subdiagnostic: impl AddToDiagnostic,
902 subdiagnostic.add_to_diagnostic_with(self, |diag, msg| {
903 let args = diag.args();
904 let msg = diag.subdiagnostic_message_to_diagnostic_message(msg);
905 handler.eagerly_translate(msg, args)
910 pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self {
911 self.span = sp.into();
912 if let Some(span) = self.span.primary_span() {
913 self.sort_span = span;
918 pub fn set_is_lint(&mut self) -> &mut Self {
923 pub fn code(&mut self, s: DiagnosticId) -> &mut Self {
928 pub fn clear_code(&mut self) -> &mut Self {
933 pub fn get_code(&self) -> Option<DiagnosticId> {
937 pub fn set_primary_message(&mut self, msg: impl Into<DiagnosticMessage>) -> &mut Self {
938 self.message[0] = (msg.into(), Style::NoStyle);
942 // Exact iteration order of diagnostic arguments shouldn't make a difference to output because
943 // they're only used in interpolation.
944 #[allow(rustc::potential_query_instability)]
945 pub fn args<'a>(&'a self) -> impl Iterator<Item = DiagnosticArg<'a, 'static>> {
951 name: impl Into<Cow<'static, str>>,
952 arg: impl IntoDiagnosticArg,
954 self.args.insert(name.into(), arg.into_diagnostic_arg());
960 args: FxHashMap<DiagnosticArgName<'static>, DiagnosticArgValue<'static>>,
965 pub fn styled_message(&self) -> &[(DiagnosticMessage, Style)] {
969 /// Helper function that takes a `SubdiagnosticMessage` and returns a `DiagnosticMessage` by
970 /// combining it with the primary message of the diagnostic (if translatable, otherwise it just
971 /// passes the user's string along).
972 pub(crate) fn subdiagnostic_message_to_diagnostic_message(
974 attr: impl Into<SubdiagnosticMessage>,
975 ) -> DiagnosticMessage {
977 self.message.iter().map(|(msg, _)| msg).next().expect("diagnostic with no messages");
978 msg.with_subdiagnostic_message(attr.into())
981 /// Convenience function for internal use, clients should use one of the
982 /// public methods above.
984 /// Used by `proc_macro_server` for implementing `server::Diagnostic`.
988 message: impl Into<SubdiagnosticMessage>,
990 render_span: Option<MultiSpan>,
992 let sub = SubDiagnostic {
995 self.subdiagnostic_message_to_diagnostic_message(message),
1001 self.children.push(sub);
1004 /// Convenience function for internal use, clients should use one of the
1005 /// public methods above.
1006 fn sub_with_highlights<M: Into<SubdiagnosticMessage>>(
1009 message: Vec<(M, Style)>,
1011 render_span: Option<MultiSpan>,
1013 let message = message
1015 .map(|m| (self.subdiagnostic_message_to_diagnostic_message(m.0), m.1))
1017 let sub = SubDiagnostic { level, message, span, render_span };
1018 self.children.push(sub);
1021 /// Fields used for Hash, and PartialEq trait
1026 &[(DiagnosticMessage, Style)],
1027 &Option<DiagnosticId>,
1029 &Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
1030 Option<&[SubDiagnostic]>,
1038 (if self.is_lint { None } else { Some(&self.children) }),
1043 impl Hash for Diagnostic {
1044 fn hash<H>(&self, state: &mut H)
1048 self.keys().hash(state);
1052 impl PartialEq for Diagnostic {
1053 fn eq(&self, other: &Self) -> bool {
1054 self.keys() == other.keys()