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};
13 use rustc_target::spec::PanicStrategy;
16 use std::hash::{Hash, Hasher};
17 use std::path::{Path, PathBuf};
19 /// Error type for `Diagnostic`'s `suggestions` field, indicating that
20 /// `.disable_suggestions()` was called on the `Diagnostic`.
21 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
22 pub struct SuggestionsDisabled;
24 /// Simplified version of `FluentArg` that can implement `Encodable` and `Decodable`. Collection of
25 /// `DiagnosticArg` are converted to `FluentArgs` (consuming the collection) at the start of
26 /// diagnostic emission.
27 pub type DiagnosticArg<'source> = (Cow<'source, str>, DiagnosticArgValue<'source>);
29 /// Simplified version of `FluentValue` that can implement `Encodable` and `Decodable`. Converted
30 /// to a `FluentValue` by the emitter to be used in diagnostic translation.
31 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
32 pub enum DiagnosticArgValue<'source> {
33 Str(Cow<'source, str>),
37 /// Converts a value of a type into a `DiagnosticArg` (typically a field of a `SessionDiagnostic`
38 /// struct). Implemented as a custom trait rather than `From` so that it is implemented on the type
39 /// being converted rather than on `DiagnosticArgValue`, which enables types from other `rustc_*`
40 /// crates to implement this.
41 pub trait IntoDiagnosticArg {
42 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static>;
45 pub struct DiagnosticArgFromDisplay<'a>(pub &'a dyn fmt::Display);
47 impl IntoDiagnosticArg for DiagnosticArgFromDisplay<'_> {
48 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
49 self.0.to_string().into_diagnostic_arg()
53 impl<'a> From<&'a dyn fmt::Display> for DiagnosticArgFromDisplay<'a> {
54 fn from(t: &'a dyn fmt::Display) -> Self {
55 DiagnosticArgFromDisplay(t)
59 impl<'a, T: fmt::Display> From<&'a T> for DiagnosticArgFromDisplay<'a> {
60 fn from(t: &'a T) -> Self {
61 DiagnosticArgFromDisplay(t)
65 macro_rules! into_diagnostic_arg_using_display {
66 ($( $ty:ty ),+ $(,)?) => {
68 impl IntoDiagnosticArg for $ty {
69 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
70 self.to_string().into_diagnostic_arg()
77 into_diagnostic_arg_using_display!(
93 MacroRulesNormalizedIdent,
96 impl IntoDiagnosticArg for bool {
97 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
99 DiagnosticArgValue::Str(Cow::Borrowed("true"))
101 DiagnosticArgValue::Str(Cow::Borrowed("false"))
106 impl IntoDiagnosticArg for char {
107 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
108 DiagnosticArgValue::Str(Cow::Owned(format!("{:?}", self)))
112 impl IntoDiagnosticArg for Symbol {
113 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
114 self.to_ident_string().into_diagnostic_arg()
118 impl<'a> IntoDiagnosticArg for &'a str {
119 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
120 self.to_string().into_diagnostic_arg()
124 impl IntoDiagnosticArg for String {
125 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
126 DiagnosticArgValue::Str(Cow::Owned(self))
130 impl<'a> IntoDiagnosticArg for &'a Path {
131 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
132 DiagnosticArgValue::Str(Cow::Owned(self.display().to_string()))
136 impl IntoDiagnosticArg for PathBuf {
137 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
138 DiagnosticArgValue::Str(Cow::Owned(self.display().to_string()))
142 impl IntoDiagnosticArg for usize {
143 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
144 DiagnosticArgValue::Number(self)
148 impl IntoDiagnosticArg for PanicStrategy {
149 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
150 DiagnosticArgValue::Str(Cow::Owned(self.desc().to_string()))
154 impl<'source> Into<FluentValue<'source>> for DiagnosticArgValue<'source> {
155 fn into(self) -> FluentValue<'source> {
157 DiagnosticArgValue::Str(s) => From::from(s),
158 DiagnosticArgValue::Number(n) => From::from(n),
163 impl IntoDiagnosticArg for hir::ConstContext {
164 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
165 DiagnosticArgValue::Str(Cow::Borrowed(match self {
166 hir::ConstContext::ConstFn => "constant function",
167 hir::ConstContext::Static(_) => "static",
168 hir::ConstContext::Const => "constant",
173 /// Trait implemented by error types. This should not be implemented manually. Instead, use
174 /// `#[derive(SessionSubdiagnostic)]` -- see [rustc_macros::SessionSubdiagnostic].
175 #[rustc_diagnostic_item = "AddSubdiagnostic"]
176 pub trait AddSubdiagnostic {
177 /// Add a subdiagnostic to an existing diagnostic.
178 fn add_to_diagnostic(self, diag: &mut Diagnostic);
181 /// Trait implemented by lint types. This should not be implemented manually. Instead, use
182 /// `#[derive(LintDiagnostic)]` -- see [rustc_macros::LintDiagnostic].
183 #[rustc_diagnostic_item = "DecorateLint"]
184 pub trait DecorateLint<'a, G: EmissionGuarantee> {
185 /// Decorate and emit a lint.
186 fn decorate_lint(self, diag: LintDiagnosticBuilder<'a, G>);
190 #[derive(Clone, Debug, Encodable, Decodable)]
191 pub struct Diagnostic {
192 // NOTE(eddyb) this is private to disallow arbitrary after-the-fact changes,
193 // outside of what methods in this crate themselves allow.
194 pub(crate) level: Level,
196 pub message: Vec<(DiagnosticMessage, Style)>,
197 pub code: Option<DiagnosticId>,
199 pub children: Vec<SubDiagnostic>,
200 pub suggestions: Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
201 args: Vec<DiagnosticArg<'static>>,
203 /// This is not used for highlighting or rendering any error message. Rather, it can be used
204 /// as a sort key to sort a buffer of diagnostics. By default, it is the primary span of
205 /// `span` if there is one. Otherwise, it is `DUMMY_SP`.
208 /// If diagnostic is from Lint, custom hash function ignores notes
209 /// otherwise hash is based on the all the fields
213 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
214 pub enum DiagnosticId {
216 Lint { name: String, has_future_breakage: bool, is_force_warn: bool },
219 /// A "sub"-diagnostic attached to a parent diagnostic.
220 /// For example, a note attached to an error.
221 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
222 pub struct SubDiagnostic {
224 pub message: Vec<(DiagnosticMessage, Style)>,
226 pub render_span: Option<MultiSpan>,
229 #[derive(Debug, PartialEq, Eq)]
230 pub struct DiagnosticStyledString(pub Vec<StringPart>);
232 impl DiagnosticStyledString {
233 pub fn new() -> DiagnosticStyledString {
234 DiagnosticStyledString(vec![])
236 pub fn push_normal<S: Into<String>>(&mut self, t: S) {
237 self.0.push(StringPart::Normal(t.into()));
239 pub fn push_highlighted<S: Into<String>>(&mut self, t: S) {
240 self.0.push(StringPart::Highlighted(t.into()));
242 pub fn push<S: Into<String>>(&mut self, t: S, highlight: bool) {
244 self.push_highlighted(t);
249 pub fn normal<S: Into<String>>(t: S) -> DiagnosticStyledString {
250 DiagnosticStyledString(vec![StringPart::Normal(t.into())])
253 pub fn highlighted<S: Into<String>>(t: S) -> DiagnosticStyledString {
254 DiagnosticStyledString(vec![StringPart::Highlighted(t.into())])
257 pub fn content(&self) -> String {
258 self.0.iter().map(|x| x.content()).collect::<String>()
262 #[derive(Debug, PartialEq, Eq)]
263 pub enum StringPart {
269 pub fn content(&self) -> &str {
271 &StringPart::Normal(ref s) | &StringPart::Highlighted(ref s) => s,
277 pub fn new<M: Into<DiagnosticMessage>>(level: Level, message: M) -> Self {
278 Diagnostic::new_with_code(level, None, message)
281 pub fn new_with_code<M: Into<DiagnosticMessage>>(
283 code: Option<DiagnosticId>,
288 message: vec![(message.into(), Style::NoStyle)],
290 span: MultiSpan::new(),
292 suggestions: Ok(vec![]),
300 pub fn level(&self) -> Level {
304 pub fn is_error(&self) -> bool {
309 | Level::Error { .. }
310 | Level::FailureNote => true,
317 | Level::Expect(_) => false,
321 pub fn update_unstable_expectation_id(
323 unstable_to_stable: &FxHashMap<LintExpectationId, LintExpectationId>,
325 if let Level::Expect(expectation_id) | Level::Warning(Some(expectation_id)) =
328 if expectation_id.is_stable() {
332 // The unstable to stable map only maps the unstable `AttrId` to a stable `HirId` with an attribute index.
333 // The lint index inside the attribute is manually transferred here.
334 let lint_index = expectation_id.get_lint_index();
335 expectation_id.set_lint_index(None);
336 let mut stable_id = *unstable_to_stable
337 .get(&expectation_id)
338 .expect("each unstable `LintExpectationId` must have a matching stable id");
340 stable_id.set_lint_index(lint_index);
341 *expectation_id = stable_id;
345 pub fn has_future_breakage(&self) -> bool {
347 Some(DiagnosticId::Lint { has_future_breakage, .. }) => has_future_breakage,
352 pub fn is_force_warn(&self) -> bool {
354 Some(DiagnosticId::Lint { is_force_warn, .. }) => is_force_warn,
359 /// Delay emission of this diagnostic as a bug.
361 /// This can be useful in contexts where an error indicates a bug but
362 /// typically this only happens when other compilation errors have already
363 /// happened. In those cases this can be used to defer emission of this
364 /// diagnostic as a bug in the compiler only if no other errors have been
367 /// In the meantime, though, callsites are required to deal with the "bug"
368 /// locally in whichever way makes the most sense.
370 pub fn downgrade_to_delayed_bug(&mut self) -> &mut Self {
373 "downgrade_to_delayed_bug: cannot downgrade {:?} to DelayedBug: not an error",
376 self.level = Level::DelayedBug;
381 /// Adds a span/label to be included in the resulting snippet.
383 /// This is pushed onto the [`MultiSpan`] that was created when the diagnostic
384 /// was first built. That means it will be shown together with the original
385 /// span/label, *not* a span added by one of the `span_{note,warn,help,suggestions}` methods.
387 /// This span is *not* considered a ["primary span"][`MultiSpan`]; only
388 /// the `Span` supplied when creating the diagnostic is primary.
389 #[rustc_lint_diagnostics]
390 pub fn span_label(&mut self, span: Span, label: impl Into<SubdiagnosticMessage>) -> &mut Self {
391 self.span.push_span_label(span, self.subdiagnostic_message_to_diagnostic_message(label));
395 /// Labels all the given spans with the provided label.
396 /// See [`Self::span_label()`] for more information.
399 spans: impl IntoIterator<Item = Span>,
400 label: impl AsRef<str>,
402 let label = label.as_ref();
404 self.span_label(span, label);
409 pub fn replace_span_with(&mut self, after: Span) -> &mut Self {
410 let before = self.span.clone();
411 self.set_span(after);
412 for span_label in before.span_labels() {
413 if let Some(label) = span_label.label {
414 self.span.push_span_label(after, label);
420 pub fn note_expected_found(
422 expected_label: &dyn fmt::Display,
423 expected: DiagnosticStyledString,
424 found_label: &dyn fmt::Display,
425 found: DiagnosticStyledString,
427 self.note_expected_found_extra(expected_label, expected, found_label, found, &"", &"")
430 pub fn note_unsuccessful_coercion(
432 expected: DiagnosticStyledString,
433 found: DiagnosticStyledString,
435 let mut msg: Vec<_> = vec![("required when trying to coerce from type `", Style::NoStyle)];
436 msg.extend(expected.0.iter().map(|x| match *x {
437 StringPart::Normal(ref s) => (s.as_str(), Style::NoStyle),
438 StringPart::Highlighted(ref s) => (s.as_str(), Style::Highlight),
440 msg.push(("` to type '", Style::NoStyle));
441 msg.extend(found.0.iter().map(|x| match *x {
442 StringPart::Normal(ref s) => (s.as_str(), Style::NoStyle),
443 StringPart::Highlighted(ref s) => (s.as_str(), Style::Highlight),
445 msg.push(("`", Style::NoStyle));
447 // For now, just attach these as notes
448 self.highlighted_note(msg);
452 pub fn note_expected_found_extra(
454 expected_label: &dyn fmt::Display,
455 expected: DiagnosticStyledString,
456 found_label: &dyn fmt::Display,
457 found: DiagnosticStyledString,
458 expected_extra: &dyn fmt::Display,
459 found_extra: &dyn fmt::Display,
461 let expected_label = expected_label.to_string();
462 let expected_label = if expected_label.is_empty() {
463 "expected".to_string()
465 format!("expected {}", expected_label)
467 let found_label = found_label.to_string();
468 let found_label = if found_label.is_empty() {
471 format!("found {}", found_label)
473 let (found_padding, expected_padding) = if expected_label.len() > found_label.len() {
474 (expected_label.len() - found_label.len(), 0)
476 (0, found_label.len() - expected_label.len())
478 let mut msg: Vec<_> =
479 vec![(format!("{}{} `", " ".repeat(expected_padding), expected_label), Style::NoStyle)];
480 msg.extend(expected.0.iter().map(|x| match *x {
481 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
482 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
484 msg.push((format!("`{}\n", expected_extra), Style::NoStyle));
485 msg.push((format!("{}{} `", " ".repeat(found_padding), found_label), Style::NoStyle));
486 msg.extend(found.0.iter().map(|x| match *x {
487 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
488 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
490 msg.push((format!("`{}", found_extra), Style::NoStyle));
492 // For now, just attach these as notes.
493 self.highlighted_note(msg);
497 pub fn note_trait_signature(&mut self, name: Symbol, signature: String) -> &mut Self {
498 self.highlighted_note(vec![
499 (format!("`{}` from trait: `", name), Style::NoStyle),
500 (signature, Style::Highlight),
501 ("`".to_string(), Style::NoStyle),
506 /// Add a note attached to this diagnostic.
507 #[rustc_lint_diagnostics]
508 pub fn note(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
509 self.sub(Level::Note, msg, MultiSpan::new(), None);
513 pub fn highlighted_note<M: Into<SubdiagnosticMessage>>(
515 msg: Vec<(M, Style)>,
517 self.sub_with_highlights(Level::Note, 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 pub fn note_once(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
524 self.sub(Level::OnceNote, msg, MultiSpan::new(), None);
528 /// Prints the span with a note above it.
529 /// This is like [`Diagnostic::note()`], but it gets its own span.
530 #[rustc_lint_diagnostics]
531 pub fn span_note<S: Into<MultiSpan>>(
534 msg: impl Into<SubdiagnosticMessage>,
536 self.sub(Level::Note, msg, sp.into(), None);
540 /// Prints the span with a note above it.
541 /// This is like [`Diagnostic::note()`], but it gets its own span.
542 pub fn span_note_once<S: Into<MultiSpan>>(
545 msg: impl Into<SubdiagnosticMessage>,
547 self.sub(Level::OnceNote, msg, sp.into(), None);
551 /// Add a warning attached to this diagnostic.
552 #[rustc_lint_diagnostics]
553 pub fn warn(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
554 self.sub(Level::Warning(None), msg, MultiSpan::new(), None);
558 /// Prints the span with a warning above it.
559 /// This is like [`Diagnostic::warn()`], but it gets its own span.
560 #[rustc_lint_diagnostics]
561 pub fn span_warn<S: Into<MultiSpan>>(
564 msg: impl Into<SubdiagnosticMessage>,
566 self.sub(Level::Warning(None), msg, sp.into(), None);
570 /// Add a help message attached to this diagnostic.
571 #[rustc_lint_diagnostics]
572 pub fn help(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
573 self.sub(Level::Help, msg, MultiSpan::new(), None);
577 /// Add a help message attached to this diagnostic with a customizable highlighted message.
578 pub fn highlighted_help(&mut self, msg: Vec<(String, Style)>) -> &mut Self {
579 self.sub_with_highlights(Level::Help, msg, MultiSpan::new(), None);
583 /// Prints the span with some help above it.
584 /// This is like [`Diagnostic::help()`], but it gets its own span.
585 #[rustc_lint_diagnostics]
586 pub fn span_help<S: Into<MultiSpan>>(
589 msg: impl Into<SubdiagnosticMessage>,
591 self.sub(Level::Help, msg, sp.into(), None);
595 /// Help the user upgrade to the latest edition.
596 /// This is factored out to make sure it does the right thing with `Cargo.toml`.
597 pub fn help_use_latest_edition(&mut self) -> &mut Self {
598 if std::env::var_os("CARGO").is_some() {
599 self.help(&format!("set `edition = \"{}\"` in `Cargo.toml`", LATEST_STABLE_EDITION));
601 self.help(&format!("pass `--edition {}` to `rustc`", LATEST_STABLE_EDITION));
603 self.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
607 /// Disallow attaching suggestions this diagnostic.
608 /// Any suggestions attached e.g. with the `span_suggestion_*` methods
609 /// (before and after the call to `disable_suggestions`) will be ignored.
610 pub fn disable_suggestions(&mut self) -> &mut Self {
611 self.suggestions = Err(SuggestionsDisabled);
615 /// Clear any existing suggestions.
616 pub fn clear_suggestions(&mut self) -> &mut Self {
617 if let Ok(suggestions) = &mut self.suggestions {
623 /// Helper for pushing to `self.suggestions`, if available (not disable).
624 fn push_suggestion(&mut self, suggestion: CodeSuggestion) {
625 if let Ok(suggestions) = &mut self.suggestions {
626 suggestions.push(suggestion);
630 /// Show a suggestion that has multiple parts to it.
631 /// In other words, multiple changes need to be applied as part of this suggestion.
632 pub fn multipart_suggestion(
634 msg: impl Into<SubdiagnosticMessage>,
635 suggestion: Vec<(Span, String)>,
636 applicability: Applicability,
638 self.multipart_suggestion_with_style(
642 SuggestionStyle::ShowCode,
646 /// Show a suggestion that has multiple parts to it, always as it's own subdiagnostic.
647 /// In other words, multiple changes need to be applied as part of this suggestion.
648 pub fn multipart_suggestion_verbose(
650 msg: impl Into<SubdiagnosticMessage>,
651 suggestion: Vec<(Span, String)>,
652 applicability: Applicability,
654 self.multipart_suggestion_with_style(
658 SuggestionStyle::ShowAlways,
661 /// [`Diagnostic::multipart_suggestion()`] but you can set the [`SuggestionStyle`].
662 pub fn multipart_suggestion_with_style(
664 msg: impl Into<SubdiagnosticMessage>,
665 suggestion: Vec<(Span, String)>,
666 applicability: Applicability,
667 style: SuggestionStyle,
669 assert!(!suggestion.is_empty());
670 self.push_suggestion(CodeSuggestion {
671 substitutions: vec![Substitution {
674 .map(|(span, snippet)| SubstitutionPart { snippet, span })
677 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
684 /// Prints out a message with for a multipart suggestion without showing the suggested code.
686 /// This is intended to be used for suggestions that are obvious in what the changes need to
687 /// be from the message, showing the span label inline would be visually unpleasant
688 /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
689 /// improve understandability.
690 pub fn tool_only_multipart_suggestion(
692 msg: impl Into<SubdiagnosticMessage>,
693 suggestion: Vec<(Span, String)>,
694 applicability: Applicability,
696 self.multipart_suggestion_with_style(
700 SuggestionStyle::CompletelyHidden,
704 /// Prints out a message with a suggested edit of the code.
706 /// In case of short messages and a simple suggestion, rustc displays it as a label:
709 /// try adding parentheses: `(tup.0).1`
714 /// * should not end in any punctuation (a `:` is added automatically)
715 /// * should not be a question (avoid language like "did you mean")
716 /// * should not contain any phrases like "the following", "as shown", etc.
717 /// * may look like "to do xyz, use" or "to do xyz, use abc"
718 /// * may contain a name of a function, variable, or type, but not whole expressions
720 /// See `CodeSuggestion` for more information.
721 pub fn span_suggestion(
724 msg: impl Into<SubdiagnosticMessage>,
725 suggestion: impl ToString,
726 applicability: Applicability,
728 self.span_suggestion_with_style(
733 SuggestionStyle::ShowCode,
738 /// [`Diagnostic::span_suggestion()`] but you can set the [`SuggestionStyle`].
739 pub fn span_suggestion_with_style(
742 msg: impl Into<SubdiagnosticMessage>,
743 suggestion: impl ToString,
744 applicability: Applicability,
745 style: SuggestionStyle,
747 self.push_suggestion(CodeSuggestion {
748 substitutions: vec![Substitution {
749 parts: vec![SubstitutionPart { snippet: suggestion.to_string(), span: sp }],
751 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
758 /// Always show the suggested change.
759 pub fn span_suggestion_verbose(
762 msg: impl Into<SubdiagnosticMessage>,
763 suggestion: impl ToString,
764 applicability: Applicability,
766 self.span_suggestion_with_style(
771 SuggestionStyle::ShowAlways,
776 /// Prints out a message with multiple suggested edits of the code.
777 /// See also [`Diagnostic::span_suggestion()`].
778 pub fn span_suggestions(
781 msg: impl Into<SubdiagnosticMessage>,
782 suggestions: impl Iterator<Item = String>,
783 applicability: Applicability,
785 let mut suggestions: Vec<_> = suggestions.collect();
787 let substitutions = suggestions
789 .map(|snippet| Substitution { parts: vec![SubstitutionPart { snippet, span: sp }] })
791 self.push_suggestion(CodeSuggestion {
793 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
794 style: SuggestionStyle::ShowCode,
800 /// Prints out a message with multiple suggested edits of the code.
801 /// See also [`Diagnostic::span_suggestion()`].
802 pub fn multipart_suggestions(
804 msg: impl Into<SubdiagnosticMessage>,
805 suggestions: impl Iterator<Item = Vec<(Span, String)>>,
806 applicability: Applicability,
808 self.push_suggestion(CodeSuggestion {
809 substitutions: suggestions
810 .map(|sugg| Substitution {
813 .map(|(span, snippet)| SubstitutionPart { snippet, span })
817 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
818 style: SuggestionStyle::ShowCode,
823 /// Prints out a message with a suggested edit of the code. If the suggestion is presented
824 /// inline, it will only show the message and not the suggestion.
826 /// See `CodeSuggestion` for more information.
827 pub fn span_suggestion_short(
830 msg: impl Into<SubdiagnosticMessage>,
831 suggestion: impl ToString,
832 applicability: Applicability,
834 self.span_suggestion_with_style(
839 SuggestionStyle::HideCodeInline,
844 /// Prints out a message for a suggestion without showing the suggested code.
846 /// This is intended to be used for suggestions that are obvious in what the changes need to
847 /// be from the message, showing the span label inline would be visually unpleasant
848 /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
849 /// improve understandability.
850 pub fn span_suggestion_hidden(
853 msg: impl Into<SubdiagnosticMessage>,
854 suggestion: impl ToString,
855 applicability: Applicability,
857 self.span_suggestion_with_style(
862 SuggestionStyle::HideCodeAlways,
867 /// Adds a suggestion to the JSON output that will not be shown in the CLI.
869 /// This is intended to be used for suggestions that are *very* obvious in what the changes
870 /// need to be from the message, but we still want other tools to be able to apply them.
871 pub fn tool_only_span_suggestion(
874 msg: impl Into<SubdiagnosticMessage>,
875 suggestion: impl ToString,
876 applicability: Applicability,
878 self.span_suggestion_with_style(
883 SuggestionStyle::CompletelyHidden,
888 /// Add a subdiagnostic from a type that implements `SessionSubdiagnostic` - see
889 /// [rustc_macros::SessionSubdiagnostic].
890 pub fn subdiagnostic(&mut self, subdiagnostic: impl AddSubdiagnostic) -> &mut Self {
891 subdiagnostic.add_to_diagnostic(self);
895 pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self {
896 self.span = sp.into();
897 if let Some(span) = self.span.primary_span() {
898 self.sort_span = span;
903 pub fn set_is_lint(&mut self) -> &mut Self {
908 pub fn code(&mut self, s: DiagnosticId) -> &mut Self {
913 pub fn clear_code(&mut self) -> &mut Self {
918 pub fn get_code(&self) -> Option<DiagnosticId> {
922 pub fn set_primary_message(&mut self, msg: impl Into<DiagnosticMessage>) -> &mut Self {
923 self.message[0] = (msg.into(), Style::NoStyle);
927 pub fn args(&self) -> &[DiagnosticArg<'static>] {
933 name: impl Into<Cow<'static, str>>,
934 arg: impl IntoDiagnosticArg,
936 self.args.push((name.into(), arg.into_diagnostic_arg()));
940 pub fn styled_message(&self) -> &[(DiagnosticMessage, Style)] {
944 /// Helper function that takes a `SubdiagnosticMessage` and returns a `DiagnosticMessage` by
945 /// combining it with the primary message of the diagnostic (if translatable, otherwise it just
946 /// passes the user's string along).
947 fn subdiagnostic_message_to_diagnostic_message(
949 attr: impl Into<SubdiagnosticMessage>,
950 ) -> DiagnosticMessage {
952 self.message.iter().map(|(msg, _)| msg).next().expect("diagnostic with no messages");
953 msg.with_subdiagnostic_message(attr.into())
956 /// Convenience function for internal use, clients should use one of the
957 /// public methods above.
959 /// Used by `proc_macro_server` for implementing `server::Diagnostic`.
963 message: impl Into<SubdiagnosticMessage>,
965 render_span: Option<MultiSpan>,
967 let sub = SubDiagnostic {
970 self.subdiagnostic_message_to_diagnostic_message(message),
976 self.children.push(sub);
979 /// Convenience function for internal use, clients should use one of the
980 /// public methods above.
981 fn sub_with_highlights<M: Into<SubdiagnosticMessage>>(
984 message: Vec<(M, Style)>,
986 render_span: Option<MultiSpan>,
988 let message = message
990 .map(|m| (self.subdiagnostic_message_to_diagnostic_message(m.0), m.1))
992 let sub = SubDiagnostic { level, message, span, render_span };
993 self.children.push(sub);
996 /// Fields used for Hash, and PartialEq trait
1001 &[(DiagnosticMessage, Style)],
1002 &Option<DiagnosticId>,
1004 &Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
1005 Option<&[SubDiagnostic]>,
1013 (if self.is_lint { None } else { Some(&self.children) }),
1018 impl Hash for Diagnostic {
1019 fn hash<H>(&self, state: &mut H)
1023 self.keys().hash(state);
1027 impl PartialEq for Diagnostic {
1028 fn eq(&self, other: &Self) -> bool {
1029 self.keys() == other.keys()