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, Symbol};
12 use rustc_span::{edition::Edition, Span, DUMMY_SP};
15 use std::hash::{Hash, Hasher};
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<'source> = (Cow<'source, str>, DiagnosticArgValue<'source>);
27 /// Simplified version of `FluentValue` that can implement `Encodable` and `Decodable`. Converted
28 /// to a `FluentValue` by the emitter to be used in diagnostic translation.
29 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
30 pub enum DiagnosticArgValue<'source> {
31 Str(Cow<'source, str>),
35 /// Converts a value of a type into a `DiagnosticArg` (typically a field of a `SessionDiagnostic`
36 /// struct). Implemented as a custom trait rather than `From` so that it is implemented on the type
37 /// being converted rather than on `DiagnosticArgValue`, which enables types from other `rustc_*`
38 /// crates to implement this.
39 pub trait IntoDiagnosticArg {
40 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static>;
43 macro_rules! into_diagnostic_arg_using_display {
44 ($( $ty:ty ),+ $(,)?) => {
46 impl IntoDiagnosticArg for $ty {
47 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
48 self.to_string().into_diagnostic_arg()
55 into_diagnostic_arg_using_display!(
72 impl IntoDiagnosticArg for bool {
73 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
75 DiagnosticArgValue::Str(Cow::Borrowed("true"))
77 DiagnosticArgValue::Str(Cow::Borrowed("false"))
82 impl IntoDiagnosticArg for char {
83 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
84 DiagnosticArgValue::Str(Cow::Owned(format!("{:?}", self)))
88 impl IntoDiagnosticArg for Symbol {
89 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
90 self.to_ident_string().into_diagnostic_arg()
94 impl<'a> IntoDiagnosticArg for &'a str {
95 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
96 self.to_string().into_diagnostic_arg()
100 impl IntoDiagnosticArg for String {
101 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
102 DiagnosticArgValue::Str(Cow::Owned(self))
106 impl IntoDiagnosticArg for usize {
107 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
108 DiagnosticArgValue::Number(self)
112 impl<'source> Into<FluentValue<'source>> for DiagnosticArgValue<'source> {
113 fn into(self) -> FluentValue<'source> {
115 DiagnosticArgValue::Str(s) => From::from(s),
116 DiagnosticArgValue::Number(n) => From::from(n),
121 impl IntoDiagnosticArg for hir::ConstContext {
122 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
123 DiagnosticArgValue::Str(Cow::Borrowed(match self {
124 hir::ConstContext::ConstFn => "constant function",
125 hir::ConstContext::Static(_) => "static",
126 hir::ConstContext::Const => "constant",
131 /// Trait implemented by error types. This should not be implemented manually. Instead, use
132 /// `#[derive(SessionSubdiagnostic)]` -- see [rustc_macros::SessionSubdiagnostic].
133 #[rustc_diagnostic_item = "AddSubdiagnostic"]
134 pub trait AddSubdiagnostic {
135 /// Add a subdiagnostic to an existing diagnostic.
136 fn add_to_diagnostic(self, diag: &mut Diagnostic);
139 /// Trait implemented by lint types. This should not be implemented manually. Instead, use
140 /// `#[derive(LintDiagnostic)]` -- see [rustc_macros::LintDiagnostic].
141 #[rustc_diagnostic_item = "DecorateLint"]
142 pub trait DecorateLint<'a, G: EmissionGuarantee> {
143 /// Decorate and emit a lint.
144 fn decorate_lint(self, diag: LintDiagnosticBuilder<'a, G>);
148 #[derive(Clone, Debug, Encodable, Decodable)]
149 pub struct Diagnostic {
150 // NOTE(eddyb) this is private to disallow arbitrary after-the-fact changes,
151 // outside of what methods in this crate themselves allow.
152 pub(crate) level: Level,
154 pub message: Vec<(DiagnosticMessage, Style)>,
155 pub code: Option<DiagnosticId>,
157 pub children: Vec<SubDiagnostic>,
158 pub suggestions: Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
159 args: Vec<DiagnosticArg<'static>>,
161 /// This is not used for highlighting or rendering any error message. Rather, it can be used
162 /// as a sort key to sort a buffer of diagnostics. By default, it is the primary span of
163 /// `span` if there is one. Otherwise, it is `DUMMY_SP`.
166 /// If diagnostic is from Lint, custom hash function ignores notes
167 /// otherwise hash is based on the all the fields
171 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
172 pub enum DiagnosticId {
174 Lint { name: String, has_future_breakage: bool, is_force_warn: bool },
177 /// A "sub"-diagnostic attached to a parent diagnostic.
178 /// For example, a note attached to an error.
179 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
180 pub struct SubDiagnostic {
182 pub message: Vec<(DiagnosticMessage, Style)>,
184 pub render_span: Option<MultiSpan>,
187 #[derive(Debug, PartialEq, Eq)]
188 pub struct DiagnosticStyledString(pub Vec<StringPart>);
190 impl DiagnosticStyledString {
191 pub fn new() -> DiagnosticStyledString {
192 DiagnosticStyledString(vec![])
194 pub fn push_normal<S: Into<String>>(&mut self, t: S) {
195 self.0.push(StringPart::Normal(t.into()));
197 pub fn push_highlighted<S: Into<String>>(&mut self, t: S) {
198 self.0.push(StringPart::Highlighted(t.into()));
200 pub fn push<S: Into<String>>(&mut self, t: S, highlight: bool) {
202 self.push_highlighted(t);
207 pub fn normal<S: Into<String>>(t: S) -> DiagnosticStyledString {
208 DiagnosticStyledString(vec![StringPart::Normal(t.into())])
211 pub fn highlighted<S: Into<String>>(t: S) -> DiagnosticStyledString {
212 DiagnosticStyledString(vec![StringPart::Highlighted(t.into())])
215 pub fn content(&self) -> String {
216 self.0.iter().map(|x| x.content()).collect::<String>()
220 #[derive(Debug, PartialEq, Eq)]
221 pub enum StringPart {
227 pub fn content(&self) -> &str {
229 &StringPart::Normal(ref s) | &StringPart::Highlighted(ref s) => s,
235 pub fn new<M: Into<DiagnosticMessage>>(level: Level, message: M) -> Self {
236 Diagnostic::new_with_code(level, None, message)
239 pub fn new_with_code<M: Into<DiagnosticMessage>>(
241 code: Option<DiagnosticId>,
246 message: vec![(message.into(), Style::NoStyle)],
248 span: MultiSpan::new(),
250 suggestions: Ok(vec![]),
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
295 .get(&expectation_id)
296 .expect("each unstable `LintExpectationId` must have a matching stable id");
298 stable_id.set_lint_index(lint_index);
299 *expectation_id = stable_id;
303 pub fn has_future_breakage(&self) -> bool {
305 Some(DiagnosticId::Lint { has_future_breakage, .. }) => has_future_breakage,
310 pub fn is_force_warn(&self) -> bool {
312 Some(DiagnosticId::Lint { is_force_warn, .. }) => is_force_warn,
317 /// Delay emission of this diagnostic as a bug.
319 /// This can be useful in contexts where an error indicates a bug but
320 /// typically this only happens when other compilation errors have already
321 /// happened. In those cases this can be used to defer emission of this
322 /// diagnostic as a bug in the compiler only if no other errors have been
325 /// In the meantime, though, callsites are required to deal with the "bug"
326 /// locally in whichever way makes the most sense.
328 pub fn downgrade_to_delayed_bug(&mut self) -> &mut Self {
331 "downgrade_to_delayed_bug: cannot downgrade {:?} to DelayedBug: not an error",
334 self.level = Level::DelayedBug;
339 /// Adds a span/label to be included in the resulting snippet.
341 /// This is pushed onto the [`MultiSpan`] that was created when the diagnostic
342 /// was first built. That means it will be shown together with the original
343 /// span/label, *not* a span added by one of the `span_{note,warn,help,suggestions}` methods.
345 /// This span is *not* considered a ["primary span"][`MultiSpan`]; only
346 /// the `Span` supplied when creating the diagnostic is primary.
347 #[rustc_lint_diagnostics]
348 pub fn span_label(&mut self, span: Span, label: impl Into<SubdiagnosticMessage>) -> &mut Self {
349 self.span.push_span_label(span, self.subdiagnostic_message_to_diagnostic_message(label));
353 /// Labels all the given spans with the provided label.
354 /// See [`Self::span_label()`] for more information.
357 spans: impl IntoIterator<Item = Span>,
358 label: impl AsRef<str>,
360 let label = label.as_ref();
362 self.span_label(span, label);
367 pub fn replace_span_with(&mut self, after: Span) -> &mut Self {
368 let before = self.span.clone();
369 self.set_span(after);
370 for span_label in before.span_labels() {
371 if let Some(label) = span_label.label {
372 self.span.push_span_label(after, label);
378 pub fn note_expected_found(
380 expected_label: &dyn fmt::Display,
381 expected: DiagnosticStyledString,
382 found_label: &dyn fmt::Display,
383 found: DiagnosticStyledString,
385 self.note_expected_found_extra(expected_label, expected, found_label, found, &"", &"")
388 pub fn note_unsuccessful_coercion(
390 expected: DiagnosticStyledString,
391 found: DiagnosticStyledString,
393 let mut msg: Vec<_> = vec![("required when trying to coerce from type `", Style::NoStyle)];
394 msg.extend(expected.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(("` to type '", Style::NoStyle));
399 msg.extend(found.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(("`", Style::NoStyle));
405 // For now, just attach these as notes
406 self.highlighted_note(msg);
410 pub fn note_expected_found_extra(
412 expected_label: &dyn fmt::Display,
413 expected: DiagnosticStyledString,
414 found_label: &dyn fmt::Display,
415 found: DiagnosticStyledString,
416 expected_extra: &dyn fmt::Display,
417 found_extra: &dyn fmt::Display,
419 let expected_label = expected_label.to_string();
420 let expected_label = if expected_label.is_empty() {
421 "expected".to_string()
423 format!("expected {}", expected_label)
425 let found_label = found_label.to_string();
426 let found_label = if found_label.is_empty() {
429 format!("found {}", found_label)
431 let (found_padding, expected_padding) = if expected_label.len() > found_label.len() {
432 (expected_label.len() - found_label.len(), 0)
434 (0, found_label.len() - expected_label.len())
436 let mut msg: Vec<_> =
437 vec![(format!("{}{} `", " ".repeat(expected_padding), expected_label), Style::NoStyle)];
438 msg.extend(expected.0.iter().map(|x| match *x {
439 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
440 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
442 msg.push((format!("`{}\n", expected_extra), Style::NoStyle));
443 msg.push((format!("{}{} `", " ".repeat(found_padding), found_label), Style::NoStyle));
444 msg.extend(found.0.iter().map(|x| match *x {
445 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
446 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
448 msg.push((format!("`{}", found_extra), Style::NoStyle));
450 // For now, just attach these as notes.
451 self.highlighted_note(msg);
455 pub fn note_trait_signature(&mut self, name: Symbol, signature: String) -> &mut Self {
456 self.highlighted_note(vec![
457 (format!("`{}` from trait: `", name), Style::NoStyle),
458 (signature, Style::Highlight),
459 ("`".to_string(), Style::NoStyle),
464 /// Add a note attached to this diagnostic.
465 #[rustc_lint_diagnostics]
466 pub fn note(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
467 self.sub(Level::Note, msg, MultiSpan::new(), None);
471 pub fn highlighted_note<M: Into<SubdiagnosticMessage>>(
473 msg: Vec<(M, Style)>,
475 self.sub_with_highlights(Level::Note, msg, MultiSpan::new(), None);
479 /// Prints the span with a note above it.
480 /// This is like [`Diagnostic::note()`], but it gets its own span.
481 pub fn note_once(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
482 self.sub(Level::OnceNote, msg, MultiSpan::new(), None);
486 /// Prints the span with a note above it.
487 /// This is like [`Diagnostic::note()`], but it gets its own span.
488 #[rustc_lint_diagnostics]
489 pub fn span_note<S: Into<MultiSpan>>(
492 msg: impl Into<SubdiagnosticMessage>,
494 self.sub(Level::Note, msg, sp.into(), None);
498 /// Prints the span with a note above it.
499 /// This is like [`Diagnostic::note()`], but it gets its own span.
500 pub fn span_note_once<S: Into<MultiSpan>>(
503 msg: impl Into<SubdiagnosticMessage>,
505 self.sub(Level::OnceNote, msg, sp.into(), None);
509 /// Add a warning attached to this diagnostic.
510 #[rustc_lint_diagnostics]
511 pub fn warn(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
512 self.sub(Level::Warning(None), msg, MultiSpan::new(), None);
516 /// Prints the span with a warning above it.
517 /// This is like [`Diagnostic::warn()`], but it gets its own span.
518 #[rustc_lint_diagnostics]
519 pub fn span_warn<S: Into<MultiSpan>>(
522 msg: impl Into<SubdiagnosticMessage>,
524 self.sub(Level::Warning(None), msg, sp.into(), None);
528 /// Add a help message attached to this diagnostic.
529 #[rustc_lint_diagnostics]
530 pub fn help(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
531 self.sub(Level::Help, msg, MultiSpan::new(), None);
535 /// Add a help message attached to this diagnostic with a customizable highlighted message.
536 pub fn highlighted_help(&mut self, msg: Vec<(String, Style)>) -> &mut Self {
537 self.sub_with_highlights(Level::Help, msg, MultiSpan::new(), None);
541 /// Prints the span with some help above it.
542 /// This is like [`Diagnostic::help()`], but it gets its own span.
543 #[rustc_lint_diagnostics]
544 pub fn span_help<S: Into<MultiSpan>>(
547 msg: impl Into<SubdiagnosticMessage>,
549 self.sub(Level::Help, msg, sp.into(), None);
553 /// Help the user upgrade to the latest edition.
554 /// This is factored out to make sure it does the right thing with `Cargo.toml`.
555 pub fn help_use_latest_edition(&mut self) -> &mut Self {
556 if std::env::var_os("CARGO").is_some() {
557 self.help(&format!("set `edition = \"{}\"` in `Cargo.toml`", LATEST_STABLE_EDITION));
559 self.help(&format!("pass `--edition {}` to `rustc`", LATEST_STABLE_EDITION));
561 self.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
565 /// Disallow attaching suggestions this diagnostic.
566 /// Any suggestions attached e.g. with the `span_suggestion_*` methods
567 /// (before and after the call to `disable_suggestions`) will be ignored.
568 pub fn disable_suggestions(&mut self) -> &mut Self {
569 self.suggestions = Err(SuggestionsDisabled);
573 /// Clear any existing suggestions.
574 pub fn clear_suggestions(&mut self) -> &mut Self {
575 if let Ok(suggestions) = &mut self.suggestions {
581 /// Helper for pushing to `self.suggestions`, if available (not disable).
582 fn push_suggestion(&mut self, suggestion: CodeSuggestion) {
583 if let Ok(suggestions) = &mut self.suggestions {
584 suggestions.push(suggestion);
588 /// Show a suggestion that has multiple parts to it.
589 /// In other words, multiple changes need to be applied as part of this suggestion.
590 pub fn multipart_suggestion(
592 msg: impl Into<SubdiagnosticMessage>,
593 suggestion: Vec<(Span, String)>,
594 applicability: Applicability,
596 self.multipart_suggestion_with_style(
600 SuggestionStyle::ShowCode,
604 /// Show a suggestion that has multiple parts to it, always as it's own subdiagnostic.
605 /// In other words, multiple changes need to be applied as part of this suggestion.
606 pub fn multipart_suggestion_verbose(
608 msg: impl Into<SubdiagnosticMessage>,
609 suggestion: Vec<(Span, String)>,
610 applicability: Applicability,
612 self.multipart_suggestion_with_style(
616 SuggestionStyle::ShowAlways,
619 /// [`Diagnostic::multipart_suggestion()`] but you can set the [`SuggestionStyle`].
620 pub fn multipart_suggestion_with_style(
622 msg: impl Into<SubdiagnosticMessage>,
623 suggestion: Vec<(Span, String)>,
624 applicability: Applicability,
625 style: SuggestionStyle,
627 assert!(!suggestion.is_empty());
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 assert!(!suggestion.is_empty());
655 self.push_suggestion(CodeSuggestion {
656 substitutions: vec![Substitution {
659 .map(|(span, snippet)| SubstitutionPart { snippet, span })
662 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
663 style: SuggestionStyle::CompletelyHidden,
669 /// Prints out a message with a suggested edit of the code.
671 /// In case of short messages and a simple suggestion, rustc displays it as a label:
674 /// try adding parentheses: `(tup.0).1`
679 /// * should not end in any punctuation (a `:` is added automatically)
680 /// * should not be a question (avoid language like "did you mean")
681 /// * should not contain any phrases like "the following", "as shown", etc.
682 /// * may look like "to do xyz, use" or "to do xyz, use abc"
683 /// * may contain a name of a function, variable, or type, but not whole expressions
685 /// See `CodeSuggestion` for more information.
686 pub fn span_suggestion(
689 msg: impl Into<SubdiagnosticMessage>,
690 suggestion: impl ToString,
691 applicability: Applicability,
693 self.span_suggestion_with_style(
698 SuggestionStyle::ShowCode,
703 /// [`Diagnostic::span_suggestion()`] but you can set the [`SuggestionStyle`].
704 pub fn span_suggestion_with_style(
707 msg: impl Into<SubdiagnosticMessage>,
708 suggestion: impl ToString,
709 applicability: Applicability,
710 style: SuggestionStyle,
712 self.push_suggestion(CodeSuggestion {
713 substitutions: vec![Substitution {
714 parts: vec![SubstitutionPart { snippet: suggestion.to_string(), span: sp }],
716 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
723 /// Always show the suggested change.
724 pub fn span_suggestion_verbose(
727 msg: impl Into<SubdiagnosticMessage>,
728 suggestion: impl ToString,
729 applicability: Applicability,
731 self.span_suggestion_with_style(
736 SuggestionStyle::ShowAlways,
741 /// Prints out a message with multiple suggested edits of the code.
742 /// See also [`Diagnostic::span_suggestion()`].
743 pub fn span_suggestions(
746 msg: impl Into<SubdiagnosticMessage>,
747 suggestions: impl Iterator<Item = String>,
748 applicability: Applicability,
750 let mut suggestions: Vec<_> = suggestions.collect();
752 let substitutions = suggestions
754 .map(|snippet| Substitution { parts: vec![SubstitutionPart { snippet, span: sp }] })
756 self.push_suggestion(CodeSuggestion {
758 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
759 style: SuggestionStyle::ShowCode,
765 /// Prints out a message with multiple suggested edits of the code.
766 /// See also [`Diagnostic::span_suggestion()`].
767 pub fn multipart_suggestions(
769 msg: impl Into<SubdiagnosticMessage>,
770 suggestions: impl Iterator<Item = Vec<(Span, String)>>,
771 applicability: Applicability,
773 self.push_suggestion(CodeSuggestion {
774 substitutions: suggestions
775 .map(|sugg| Substitution {
778 .map(|(span, snippet)| SubstitutionPart { snippet, span })
782 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
783 style: SuggestionStyle::ShowCode,
788 /// Prints out a message with a suggested edit of the code. If the suggestion is presented
789 /// inline, it will only show the message and not the suggestion.
791 /// See `CodeSuggestion` for more information.
792 pub fn span_suggestion_short(
795 msg: impl Into<SubdiagnosticMessage>,
796 suggestion: impl ToString,
797 applicability: Applicability,
799 self.span_suggestion_with_style(
804 SuggestionStyle::HideCodeInline,
809 /// Prints out a message for a suggestion without showing the suggested code.
811 /// This is intended to be used for suggestions that are obvious in what the changes need to
812 /// be from the message, showing the span label inline would be visually unpleasant
813 /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
814 /// improve understandability.
815 pub fn span_suggestion_hidden(
818 msg: impl Into<SubdiagnosticMessage>,
819 suggestion: impl ToString,
820 applicability: Applicability,
822 self.span_suggestion_with_style(
827 SuggestionStyle::HideCodeAlways,
832 /// Adds a suggestion to the JSON output that will not be shown in the CLI.
834 /// This is intended to be used for suggestions that are *very* obvious in what the changes
835 /// need to be from the message, but we still want other tools to be able to apply them.
836 pub fn tool_only_span_suggestion(
839 msg: impl Into<SubdiagnosticMessage>,
840 suggestion: impl ToString,
841 applicability: Applicability,
843 self.span_suggestion_with_style(
848 SuggestionStyle::CompletelyHidden,
853 /// Add a subdiagnostic from a type that implements `SessionSubdiagnostic` - see
854 /// [rustc_macros::SessionSubdiagnostic].
855 pub fn subdiagnostic(&mut self, subdiagnostic: impl AddSubdiagnostic) -> &mut Self {
856 subdiagnostic.add_to_diagnostic(self);
860 pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self {
861 self.span = sp.into();
862 if let Some(span) = self.span.primary_span() {
863 self.sort_span = span;
868 pub fn set_is_lint(&mut self) -> &mut Self {
873 pub fn code(&mut self, s: DiagnosticId) -> &mut Self {
878 pub fn clear_code(&mut self) -> &mut Self {
883 pub fn get_code(&self) -> Option<DiagnosticId> {
887 pub fn set_primary_message(&mut self, msg: impl Into<DiagnosticMessage>) -> &mut Self {
888 self.message[0] = (msg.into(), Style::NoStyle);
892 pub fn args(&self) -> &[DiagnosticArg<'static>] {
898 name: impl Into<Cow<'static, str>>,
899 arg: impl IntoDiagnosticArg,
901 self.args.push((name.into(), arg.into_diagnostic_arg()));
905 pub fn styled_message(&self) -> &[(DiagnosticMessage, Style)] {
909 /// Helper function that takes a `SubdiagnosticMessage` and returns a `DiagnosticMessage` by
910 /// combining it with the primary message of the diagnostic (if translatable, otherwise it just
911 /// passes the user's string along).
912 fn subdiagnostic_message_to_diagnostic_message(
914 attr: impl Into<SubdiagnosticMessage>,
915 ) -> DiagnosticMessage {
917 self.message.iter().map(|(msg, _)| msg).next().expect("diagnostic with no messages");
918 msg.with_subdiagnostic_message(attr.into())
921 /// Convenience function for internal use, clients should use one of the
922 /// public methods above.
924 /// Used by `proc_macro_server` for implementing `server::Diagnostic`.
928 message: impl Into<SubdiagnosticMessage>,
930 render_span: Option<MultiSpan>,
932 let sub = SubDiagnostic {
935 self.subdiagnostic_message_to_diagnostic_message(message),
941 self.children.push(sub);
944 /// Convenience function for internal use, clients should use one of the
945 /// public methods above.
946 fn sub_with_highlights<M: Into<SubdiagnosticMessage>>(
949 mut message: Vec<(M, Style)>,
951 render_span: Option<MultiSpan>,
953 let message = message
955 .map(|m| (self.subdiagnostic_message_to_diagnostic_message(m.0), m.1))
957 let sub = SubDiagnostic { level, message, span, render_span };
958 self.children.push(sub);
961 /// Fields used for Hash, and PartialEq trait
966 &[(DiagnosticMessage, Style)],
967 &Option<DiagnosticId>,
969 &Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
970 Option<&[SubDiagnostic]>,
978 (if self.is_lint { None } else { Some(&self.children) }),
983 impl Hash for Diagnostic {
984 fn hash<H>(&self, state: &mut H)
988 self.keys().hash(state);
992 impl PartialEq for Diagnostic {
993 fn eq(&self, other: &Self) -> bool {
994 self.keys() == other.keys()