1 use crate::snippet::Style;
3 CodeSuggestion, DiagnosticMessage, EmissionGuarantee, Level, LintDiagnosticBuilder, MultiSpan,
4 SubdiagnosticMessage, Substitution, SubstitutionPart, SuggestionStyle,
6 use rustc_data_structures::fx::FxHashMap;
7 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::{Ident, MacroRulesNormalizedIdent, Symbol};
12 use rustc_span::{edition::Edition, Span, DUMMY_SP};
15 use std::hash::{Hash, Hasher};
16 use std::path::{Path, PathBuf};
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<'source> = (Cow<'source, str>, DiagnosticArgValue<'source>);
28 /// Simplified version of `FluentValue` that can implement `Encodable` and `Decodable`. Converted
29 /// to a `FluentValue` by the emitter to be used in diagnostic translation.
30 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
31 pub enum DiagnosticArgValue<'source> {
32 Str(Cow<'source, str>),
36 /// Converts a value of a type into a `DiagnosticArg` (typically a field of a `SessionDiagnostic`
37 /// struct). Implemented as a custom trait rather than `From` so that it is implemented on the type
38 /// being converted rather than on `DiagnosticArgValue`, which enables types from other `rustc_*`
39 /// crates to implement this.
40 pub trait IntoDiagnosticArg {
41 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static>;
44 pub struct DiagnosticArgFromDisplay<'a>(pub &'a dyn fmt::Display);
46 impl IntoDiagnosticArg for DiagnosticArgFromDisplay<'_> {
47 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
48 self.0.to_string().into_diagnostic_arg()
52 impl<'a> From<&'a dyn fmt::Display> for DiagnosticArgFromDisplay<'a> {
53 fn from(t: &'a dyn fmt::Display) -> Self {
54 DiagnosticArgFromDisplay(t)
58 impl<'a, T: fmt::Display> From<&'a T> for DiagnosticArgFromDisplay<'a> {
59 fn from(t: &'a T) -> Self {
60 DiagnosticArgFromDisplay(t)
64 macro_rules! into_diagnostic_arg_using_display {
65 ($( $ty:ty ),+ $(,)?) => {
67 impl IntoDiagnosticArg for $ty {
68 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
69 self.to_string().into_diagnostic_arg()
76 into_diagnostic_arg_using_display!(
92 MacroRulesNormalizedIdent,
95 impl IntoDiagnosticArg for bool {
96 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
98 DiagnosticArgValue::Str(Cow::Borrowed("true"))
100 DiagnosticArgValue::Str(Cow::Borrowed("false"))
105 impl IntoDiagnosticArg for char {
106 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
107 DiagnosticArgValue::Str(Cow::Owned(format!("{:?}", self)))
111 impl IntoDiagnosticArg for Symbol {
112 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
113 self.to_ident_string().into_diagnostic_arg()
117 impl<'a> IntoDiagnosticArg for &'a str {
118 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
119 self.to_string().into_diagnostic_arg()
123 impl IntoDiagnosticArg for String {
124 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
125 DiagnosticArgValue::Str(Cow::Owned(self))
129 impl<'a> IntoDiagnosticArg for &'a Path {
130 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
131 DiagnosticArgValue::Str(Cow::Owned(self.display().to_string()))
135 impl IntoDiagnosticArg for PathBuf {
136 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
137 DiagnosticArgValue::Str(Cow::Owned(self.display().to_string()))
141 impl IntoDiagnosticArg for usize {
142 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
143 DiagnosticArgValue::Number(self)
147 impl<'source> Into<FluentValue<'source>> for DiagnosticArgValue<'source> {
148 fn into(self) -> FluentValue<'source> {
150 DiagnosticArgValue::Str(s) => From::from(s),
151 DiagnosticArgValue::Number(n) => From::from(n),
156 impl IntoDiagnosticArg for hir::ConstContext {
157 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
158 DiagnosticArgValue::Str(Cow::Borrowed(match self {
159 hir::ConstContext::ConstFn => "constant function",
160 hir::ConstContext::Static(_) => "static",
161 hir::ConstContext::Const => "constant",
166 /// Trait implemented by error types. This should not be implemented manually. Instead, use
167 /// `#[derive(SessionSubdiagnostic)]` -- see [rustc_macros::SessionSubdiagnostic].
168 #[rustc_diagnostic_item = "AddSubdiagnostic"]
169 pub trait AddSubdiagnostic {
170 /// Add a subdiagnostic to an existing diagnostic.
171 fn add_to_diagnostic(self, diag: &mut Diagnostic);
174 /// Trait implemented by lint types. This should not be implemented manually. Instead, use
175 /// `#[derive(LintDiagnostic)]` -- see [rustc_macros::LintDiagnostic].
176 #[rustc_diagnostic_item = "DecorateLint"]
177 pub trait DecorateLint<'a, G: EmissionGuarantee> {
178 /// Decorate and emit a lint.
179 fn decorate_lint(self, diag: LintDiagnosticBuilder<'a, G>);
183 #[derive(Clone, Debug, Encodable, Decodable)]
184 pub struct Diagnostic {
185 // NOTE(eddyb) this is private to disallow arbitrary after-the-fact changes,
186 // outside of what methods in this crate themselves allow.
187 pub(crate) level: Level,
189 pub message: Vec<(DiagnosticMessage, Style)>,
190 pub code: Option<DiagnosticId>,
192 pub children: Vec<SubDiagnostic>,
193 pub suggestions: Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
194 args: Vec<DiagnosticArg<'static>>,
196 /// This is not used for highlighting or rendering any error message. Rather, it can be used
197 /// as a sort key to sort a buffer of diagnostics. By default, it is the primary span of
198 /// `span` if there is one. Otherwise, it is `DUMMY_SP`.
201 /// If diagnostic is from Lint, custom hash function ignores notes
202 /// otherwise hash is based on the all the fields
206 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
207 pub enum DiagnosticId {
209 Lint { name: String, has_future_breakage: bool, is_force_warn: bool },
212 /// A "sub"-diagnostic attached to a parent diagnostic.
213 /// For example, a note attached to an error.
214 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
215 pub struct SubDiagnostic {
217 pub message: Vec<(DiagnosticMessage, Style)>,
219 pub render_span: Option<MultiSpan>,
222 #[derive(Debug, PartialEq, Eq)]
223 pub struct DiagnosticStyledString(pub Vec<StringPart>);
225 impl DiagnosticStyledString {
226 pub fn new() -> DiagnosticStyledString {
227 DiagnosticStyledString(vec![])
229 pub fn push_normal<S: Into<String>>(&mut self, t: S) {
230 self.0.push(StringPart::Normal(t.into()));
232 pub fn push_highlighted<S: Into<String>>(&mut self, t: S) {
233 self.0.push(StringPart::Highlighted(t.into()));
235 pub fn push<S: Into<String>>(&mut self, t: S, highlight: bool) {
237 self.push_highlighted(t);
242 pub fn normal<S: Into<String>>(t: S) -> DiagnosticStyledString {
243 DiagnosticStyledString(vec![StringPart::Normal(t.into())])
246 pub fn highlighted<S: Into<String>>(t: S) -> DiagnosticStyledString {
247 DiagnosticStyledString(vec![StringPart::Highlighted(t.into())])
250 pub fn content(&self) -> String {
251 self.0.iter().map(|x| x.content()).collect::<String>()
255 #[derive(Debug, PartialEq, Eq)]
256 pub enum StringPart {
262 pub fn content(&self) -> &str {
264 &StringPart::Normal(ref s) | &StringPart::Highlighted(ref s) => s,
270 pub fn new<M: Into<DiagnosticMessage>>(level: Level, message: M) -> Self {
271 Diagnostic::new_with_code(level, None, message)
274 pub fn new_with_code<M: Into<DiagnosticMessage>>(
276 code: Option<DiagnosticId>,
281 message: vec![(message.into(), Style::NoStyle)],
283 span: MultiSpan::new(),
285 suggestions: Ok(vec![]),
293 pub fn level(&self) -> Level {
297 pub fn is_error(&self) -> bool {
302 | Level::Error { .. }
303 | Level::FailureNote => true,
310 | Level::Expect(_) => false,
314 pub fn update_unstable_expectation_id(
316 unstable_to_stable: &FxHashMap<LintExpectationId, LintExpectationId>,
318 if let Level::Expect(expectation_id) | Level::Warning(Some(expectation_id)) =
321 if expectation_id.is_stable() {
325 // The unstable to stable map only maps the unstable `AttrId` to a stable `HirId` with an attribute index.
326 // The lint index inside the attribute is manually transferred here.
327 let lint_index = expectation_id.get_lint_index();
328 expectation_id.set_lint_index(None);
329 let mut stable_id = *unstable_to_stable
330 .get(&expectation_id)
331 .expect("each unstable `LintExpectationId` must have a matching stable id");
333 stable_id.set_lint_index(lint_index);
334 *expectation_id = stable_id;
338 pub fn has_future_breakage(&self) -> bool {
340 Some(DiagnosticId::Lint { has_future_breakage, .. }) => has_future_breakage,
345 pub fn is_force_warn(&self) -> bool {
347 Some(DiagnosticId::Lint { is_force_warn, .. }) => is_force_warn,
352 /// Delay emission of this diagnostic as a bug.
354 /// This can be useful in contexts where an error indicates a bug but
355 /// typically this only happens when other compilation errors have already
356 /// happened. In those cases this can be used to defer emission of this
357 /// diagnostic as a bug in the compiler only if no other errors have been
360 /// In the meantime, though, callsites are required to deal with the "bug"
361 /// locally in whichever way makes the most sense.
363 pub fn downgrade_to_delayed_bug(&mut self) -> &mut Self {
366 "downgrade_to_delayed_bug: cannot downgrade {:?} to DelayedBug: not an error",
369 self.level = Level::DelayedBug;
374 /// Adds a span/label to be included in the resulting snippet.
376 /// This is pushed onto the [`MultiSpan`] that was created when the diagnostic
377 /// was first built. That means it will be shown together with the original
378 /// span/label, *not* a span added by one of the `span_{note,warn,help,suggestions}` methods.
380 /// This span is *not* considered a ["primary span"][`MultiSpan`]; only
381 /// the `Span` supplied when creating the diagnostic is primary.
382 #[rustc_lint_diagnostics]
383 pub fn span_label(&mut self, span: Span, label: impl Into<SubdiagnosticMessage>) -> &mut Self {
384 self.span.push_span_label(span, self.subdiagnostic_message_to_diagnostic_message(label));
388 /// Labels all the given spans with the provided label.
389 /// See [`Self::span_label()`] for more information.
392 spans: impl IntoIterator<Item = Span>,
393 label: impl AsRef<str>,
395 let label = label.as_ref();
397 self.span_label(span, label);
402 pub fn replace_span_with(&mut self, after: Span) -> &mut Self {
403 let before = self.span.clone();
404 self.set_span(after);
405 for span_label in before.span_labels() {
406 if let Some(label) = span_label.label {
407 self.span.push_span_label(after, label);
413 pub fn note_expected_found(
415 expected_label: &dyn fmt::Display,
416 expected: DiagnosticStyledString,
417 found_label: &dyn fmt::Display,
418 found: DiagnosticStyledString,
420 self.note_expected_found_extra(expected_label, expected, found_label, found, &"", &"")
423 pub fn note_unsuccessful_coercion(
425 expected: DiagnosticStyledString,
426 found: DiagnosticStyledString,
428 let mut msg: Vec<_> = vec![("required when trying to coerce from type `", Style::NoStyle)];
429 msg.extend(expected.0.iter().map(|x| match *x {
430 StringPart::Normal(ref s) => (s.as_str(), Style::NoStyle),
431 StringPart::Highlighted(ref s) => (s.as_str(), Style::Highlight),
433 msg.push(("` to type '", Style::NoStyle));
434 msg.extend(found.0.iter().map(|x| match *x {
435 StringPart::Normal(ref s) => (s.as_str(), Style::NoStyle),
436 StringPart::Highlighted(ref s) => (s.as_str(), Style::Highlight),
438 msg.push(("`", Style::NoStyle));
440 // For now, just attach these as notes
441 self.highlighted_note(msg);
445 pub fn note_expected_found_extra(
447 expected_label: &dyn fmt::Display,
448 expected: DiagnosticStyledString,
449 found_label: &dyn fmt::Display,
450 found: DiagnosticStyledString,
451 expected_extra: &dyn fmt::Display,
452 found_extra: &dyn fmt::Display,
454 let expected_label = expected_label.to_string();
455 let expected_label = if expected_label.is_empty() {
456 "expected".to_string()
458 format!("expected {}", expected_label)
460 let found_label = found_label.to_string();
461 let found_label = if found_label.is_empty() {
464 format!("found {}", found_label)
466 let (found_padding, expected_padding) = if expected_label.len() > found_label.len() {
467 (expected_label.len() - found_label.len(), 0)
469 (0, found_label.len() - expected_label.len())
471 let mut msg: Vec<_> =
472 vec![(format!("{}{} `", " ".repeat(expected_padding), expected_label), Style::NoStyle)];
473 msg.extend(expected.0.iter().map(|x| match *x {
474 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
475 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
477 msg.push((format!("`{}\n", expected_extra), Style::NoStyle));
478 msg.push((format!("{}{} `", " ".repeat(found_padding), found_label), Style::NoStyle));
479 msg.extend(found.0.iter().map(|x| match *x {
480 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
481 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
483 msg.push((format!("`{}", found_extra), Style::NoStyle));
485 // For now, just attach these as notes.
486 self.highlighted_note(msg);
490 pub fn note_trait_signature(&mut self, name: Symbol, signature: String) -> &mut Self {
491 self.highlighted_note(vec![
492 (format!("`{}` from trait: `", name), Style::NoStyle),
493 (signature, Style::Highlight),
494 ("`".to_string(), Style::NoStyle),
499 /// Add a note attached to this diagnostic.
500 #[rustc_lint_diagnostics]
501 pub fn note(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
502 self.sub(Level::Note, msg, MultiSpan::new(), None);
506 pub fn highlighted_note<M: Into<SubdiagnosticMessage>>(
508 msg: Vec<(M, Style)>,
510 self.sub_with_highlights(Level::Note, msg, MultiSpan::new(), None);
514 /// Prints the span with a note above it.
515 /// This is like [`Diagnostic::note()`], but it gets its own span.
516 pub fn note_once(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
517 self.sub(Level::OnceNote, msg, MultiSpan::new(), None);
521 /// Prints the span with a note above it.
522 /// This is like [`Diagnostic::note()`], but it gets its own span.
523 #[rustc_lint_diagnostics]
524 pub fn span_note<S: Into<MultiSpan>>(
527 msg: impl Into<SubdiagnosticMessage>,
529 self.sub(Level::Note, msg, sp.into(), None);
533 /// Prints the span with a note above it.
534 /// This is like [`Diagnostic::note()`], but it gets its own span.
535 pub fn span_note_once<S: Into<MultiSpan>>(
538 msg: impl Into<SubdiagnosticMessage>,
540 self.sub(Level::OnceNote, msg, sp.into(), None);
544 /// Add a warning attached to this diagnostic.
545 #[rustc_lint_diagnostics]
546 pub fn warn(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
547 self.sub(Level::Warning(None), msg, MultiSpan::new(), None);
551 /// Prints the span with a warning above it.
552 /// This is like [`Diagnostic::warn()`], but it gets its own span.
553 #[rustc_lint_diagnostics]
554 pub fn span_warn<S: Into<MultiSpan>>(
557 msg: impl Into<SubdiagnosticMessage>,
559 self.sub(Level::Warning(None), msg, sp.into(), None);
563 /// Add a help message attached to this diagnostic.
564 #[rustc_lint_diagnostics]
565 pub fn help(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
566 self.sub(Level::Help, msg, MultiSpan::new(), None);
570 /// Add a help message attached to this diagnostic with a customizable highlighted message.
571 pub fn highlighted_help(&mut self, msg: Vec<(String, Style)>) -> &mut Self {
572 self.sub_with_highlights(Level::Help, msg, MultiSpan::new(), None);
576 /// Prints the span with some help above it.
577 /// This is like [`Diagnostic::help()`], but it gets its own span.
578 #[rustc_lint_diagnostics]
579 pub fn span_help<S: Into<MultiSpan>>(
582 msg: impl Into<SubdiagnosticMessage>,
584 self.sub(Level::Help, msg, sp.into(), None);
588 /// Help the user upgrade to the latest edition.
589 /// This is factored out to make sure it does the right thing with `Cargo.toml`.
590 pub fn help_use_latest_edition(&mut self) -> &mut Self {
591 if std::env::var_os("CARGO").is_some() {
592 self.help(&format!("set `edition = \"{}\"` in `Cargo.toml`", LATEST_STABLE_EDITION));
594 self.help(&format!("pass `--edition {}` to `rustc`", LATEST_STABLE_EDITION));
596 self.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
600 /// Disallow attaching suggestions this diagnostic.
601 /// Any suggestions attached e.g. with the `span_suggestion_*` methods
602 /// (before and after the call to `disable_suggestions`) will be ignored.
603 pub fn disable_suggestions(&mut self) -> &mut Self {
604 self.suggestions = Err(SuggestionsDisabled);
608 /// Clear any existing suggestions.
609 pub fn clear_suggestions(&mut self) -> &mut Self {
610 if let Ok(suggestions) = &mut self.suggestions {
616 /// Helper for pushing to `self.suggestions`, if available (not disable).
617 fn push_suggestion(&mut self, suggestion: CodeSuggestion) {
618 if let Ok(suggestions) = &mut self.suggestions {
619 suggestions.push(suggestion);
623 /// Show a suggestion that has multiple parts to it.
624 /// In other words, multiple changes need to be applied as part of this suggestion.
625 pub fn multipart_suggestion(
627 msg: impl Into<SubdiagnosticMessage>,
628 suggestion: Vec<(Span, String)>,
629 applicability: Applicability,
631 self.multipart_suggestion_with_style(
635 SuggestionStyle::ShowCode,
639 /// Show a suggestion that has multiple parts to it, always as it's own subdiagnostic.
640 /// In other words, multiple changes need to be applied as part of this suggestion.
641 pub fn multipart_suggestion_verbose(
643 msg: impl Into<SubdiagnosticMessage>,
644 suggestion: Vec<(Span, String)>,
645 applicability: Applicability,
647 self.multipart_suggestion_with_style(
651 SuggestionStyle::ShowAlways,
654 /// [`Diagnostic::multipart_suggestion()`] but you can set the [`SuggestionStyle`].
655 pub fn multipart_suggestion_with_style(
657 msg: impl Into<SubdiagnosticMessage>,
658 suggestion: Vec<(Span, String)>,
659 applicability: Applicability,
660 style: SuggestionStyle,
662 assert!(!suggestion.is_empty());
663 self.push_suggestion(CodeSuggestion {
664 substitutions: vec![Substitution {
667 .map(|(span, snippet)| SubstitutionPart { snippet, span })
670 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
677 /// Prints out a message with for a multipart suggestion without showing the suggested code.
679 /// This is intended to be used for suggestions that are obvious in what the changes need to
680 /// be from the message, showing the span label inline would be visually unpleasant
681 /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
682 /// improve understandability.
683 pub fn tool_only_multipart_suggestion(
685 msg: impl Into<SubdiagnosticMessage>,
686 suggestion: Vec<(Span, String)>,
687 applicability: Applicability,
689 self.multipart_suggestion_with_style(
693 SuggestionStyle::CompletelyHidden,
697 /// Prints out a message with a suggested edit of the code.
699 /// In case of short messages and a simple suggestion, rustc displays it as a label:
702 /// try adding parentheses: `(tup.0).1`
707 /// * should not end in any punctuation (a `:` is added automatically)
708 /// * should not be a question (avoid language like "did you mean")
709 /// * should not contain any phrases like "the following", "as shown", etc.
710 /// * may look like "to do xyz, use" or "to do xyz, use abc"
711 /// * may contain a name of a function, variable, or type, but not whole expressions
713 /// See `CodeSuggestion` for more information.
714 pub fn span_suggestion(
717 msg: impl Into<SubdiagnosticMessage>,
718 suggestion: impl ToString,
719 applicability: Applicability,
721 self.span_suggestion_with_style(
726 SuggestionStyle::ShowCode,
731 /// [`Diagnostic::span_suggestion()`] but you can set the [`SuggestionStyle`].
732 pub fn span_suggestion_with_style(
735 msg: impl Into<SubdiagnosticMessage>,
736 suggestion: impl ToString,
737 applicability: Applicability,
738 style: SuggestionStyle,
740 self.push_suggestion(CodeSuggestion {
741 substitutions: vec![Substitution {
742 parts: vec![SubstitutionPart { snippet: suggestion.to_string(), span: sp }],
744 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
751 /// Always show the suggested change.
752 pub fn span_suggestion_verbose(
755 msg: impl Into<SubdiagnosticMessage>,
756 suggestion: impl ToString,
757 applicability: Applicability,
759 self.span_suggestion_with_style(
764 SuggestionStyle::ShowAlways,
769 /// Prints out a message with multiple suggested edits of the code.
770 /// See also [`Diagnostic::span_suggestion()`].
771 pub fn span_suggestions(
774 msg: impl Into<SubdiagnosticMessage>,
775 suggestions: impl Iterator<Item = String>,
776 applicability: Applicability,
778 let mut suggestions: Vec<_> = suggestions.collect();
780 let substitutions = suggestions
782 .map(|snippet| Substitution { parts: vec![SubstitutionPart { snippet, span: sp }] })
784 self.push_suggestion(CodeSuggestion {
786 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
787 style: SuggestionStyle::ShowCode,
793 /// Prints out a message with multiple suggested edits of the code.
794 /// See also [`Diagnostic::span_suggestion()`].
795 pub fn multipart_suggestions(
797 msg: impl Into<SubdiagnosticMessage>,
798 suggestions: impl Iterator<Item = Vec<(Span, String)>>,
799 applicability: Applicability,
801 self.push_suggestion(CodeSuggestion {
802 substitutions: suggestions
803 .map(|sugg| Substitution {
806 .map(|(span, snippet)| SubstitutionPart { snippet, span })
810 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
811 style: SuggestionStyle::ShowCode,
816 /// Prints out a message with a suggested edit of the code. If the suggestion is presented
817 /// inline, it will only show the message and not the suggestion.
819 /// See `CodeSuggestion` for more information.
820 pub fn span_suggestion_short(
823 msg: impl Into<SubdiagnosticMessage>,
824 suggestion: impl ToString,
825 applicability: Applicability,
827 self.span_suggestion_with_style(
832 SuggestionStyle::HideCodeInline,
837 /// Prints out a message for a suggestion without showing the suggested code.
839 /// This is intended to be used for suggestions that are obvious in what the changes need to
840 /// be from the message, showing the span label inline would be visually unpleasant
841 /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
842 /// improve understandability.
843 pub fn span_suggestion_hidden(
846 msg: impl Into<SubdiagnosticMessage>,
847 suggestion: impl ToString,
848 applicability: Applicability,
850 self.span_suggestion_with_style(
855 SuggestionStyle::HideCodeAlways,
860 /// Adds a suggestion to the JSON output that will not be shown in the CLI.
862 /// This is intended to be used for suggestions that are *very* obvious in what the changes
863 /// need to be from the message, but we still want other tools to be able to apply them.
864 pub fn tool_only_span_suggestion(
867 msg: impl Into<SubdiagnosticMessage>,
868 suggestion: impl ToString,
869 applicability: Applicability,
871 self.span_suggestion_with_style(
876 SuggestionStyle::CompletelyHidden,
881 /// Add a subdiagnostic from a type that implements `SessionSubdiagnostic` - see
882 /// [rustc_macros::SessionSubdiagnostic].
883 pub fn subdiagnostic(&mut self, subdiagnostic: impl AddSubdiagnostic) -> &mut Self {
884 subdiagnostic.add_to_diagnostic(self);
888 pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self {
889 self.span = sp.into();
890 if let Some(span) = self.span.primary_span() {
891 self.sort_span = span;
896 pub fn set_is_lint(&mut self) -> &mut Self {
901 pub fn code(&mut self, s: DiagnosticId) -> &mut Self {
906 pub fn clear_code(&mut self) -> &mut Self {
911 pub fn get_code(&self) -> Option<DiagnosticId> {
915 pub fn set_primary_message(&mut self, msg: impl Into<DiagnosticMessage>) -> &mut Self {
916 self.message[0] = (msg.into(), Style::NoStyle);
920 pub fn args(&self) -> &[DiagnosticArg<'static>] {
926 name: impl Into<Cow<'static, str>>,
927 arg: impl IntoDiagnosticArg,
929 self.args.push((name.into(), arg.into_diagnostic_arg()));
933 pub fn styled_message(&self) -> &[(DiagnosticMessage, Style)] {
937 /// Helper function that takes a `SubdiagnosticMessage` and returns a `DiagnosticMessage` by
938 /// combining it with the primary message of the diagnostic (if translatable, otherwise it just
939 /// passes the user's string along).
940 fn subdiagnostic_message_to_diagnostic_message(
942 attr: impl Into<SubdiagnosticMessage>,
943 ) -> DiagnosticMessage {
945 self.message.iter().map(|(msg, _)| msg).next().expect("diagnostic with no messages");
946 msg.with_subdiagnostic_message(attr.into())
949 /// Convenience function for internal use, clients should use one of the
950 /// public methods above.
952 /// Used by `proc_macro_server` for implementing `server::Diagnostic`.
956 message: impl Into<SubdiagnosticMessage>,
958 render_span: Option<MultiSpan>,
960 let sub = SubDiagnostic {
963 self.subdiagnostic_message_to_diagnostic_message(message),
969 self.children.push(sub);
972 /// Convenience function for internal use, clients should use one of the
973 /// public methods above.
974 fn sub_with_highlights<M: Into<SubdiagnosticMessage>>(
977 mut message: Vec<(M, Style)>,
979 render_span: Option<MultiSpan>,
981 let message = message
983 .map(|m| (self.subdiagnostic_message_to_diagnostic_message(m.0), m.1))
985 let sub = SubDiagnostic { level, message, span, render_span };
986 self.children.push(sub);
989 /// Fields used for Hash, and PartialEq trait
994 &[(DiagnosticMessage, Style)],
995 &Option<DiagnosticId>,
997 &Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
998 Option<&[SubDiagnostic]>,
1006 (if self.is_lint { None } else { Some(&self.children) }),
1011 impl Hash for Diagnostic {
1012 fn hash<H>(&self, state: &mut H)
1016 self.keys().hash(state);
1020 impl PartialEq for Diagnostic {
1021 fn eq(&self, other: &Self) -> bool {
1022 self.keys() == other.keys()