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 pub struct DiagnosticArgFromDisplay<'a>(pub &'a dyn fmt::Display);
45 impl IntoDiagnosticArg for DiagnosticArgFromDisplay<'_> {
46 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
47 self.0.to_string().into_diagnostic_arg()
51 impl<'a> From<&'a dyn fmt::Display> for DiagnosticArgFromDisplay<'a> {
52 fn from(t: &'a dyn fmt::Display) -> Self {
53 DiagnosticArgFromDisplay(t)
57 impl<'a, T: fmt::Display> From<&'a T> for DiagnosticArgFromDisplay<'a> {
58 fn from(t: &'a T) -> Self {
59 DiagnosticArgFromDisplay(t)
63 macro_rules! into_diagnostic_arg_using_display {
64 ($( $ty:ty ),+ $(,)?) => {
66 impl IntoDiagnosticArg for $ty {
67 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
68 self.to_string().into_diagnostic_arg()
75 into_diagnostic_arg_using_display!(
92 impl IntoDiagnosticArg for bool {
93 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
95 DiagnosticArgValue::Str(Cow::Borrowed("true"))
97 DiagnosticArgValue::Str(Cow::Borrowed("false"))
102 impl IntoDiagnosticArg for char {
103 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
104 DiagnosticArgValue::Str(Cow::Owned(format!("{:?}", self)))
108 impl IntoDiagnosticArg for Symbol {
109 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
110 self.to_ident_string().into_diagnostic_arg()
114 impl<'a> IntoDiagnosticArg for &'a str {
115 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
116 self.to_string().into_diagnostic_arg()
120 impl IntoDiagnosticArg for String {
121 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
122 DiagnosticArgValue::Str(Cow::Owned(self))
126 impl IntoDiagnosticArg for usize {
127 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
128 DiagnosticArgValue::Number(self)
132 impl<'source> Into<FluentValue<'source>> for DiagnosticArgValue<'source> {
133 fn into(self) -> FluentValue<'source> {
135 DiagnosticArgValue::Str(s) => From::from(s),
136 DiagnosticArgValue::Number(n) => From::from(n),
141 impl IntoDiagnosticArg for hir::ConstContext {
142 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
143 DiagnosticArgValue::Str(Cow::Borrowed(match self {
144 hir::ConstContext::ConstFn => "constant function",
145 hir::ConstContext::Static(_) => "static",
146 hir::ConstContext::Const => "constant",
151 /// Trait implemented by error types. This should not be implemented manually. Instead, use
152 /// `#[derive(SessionSubdiagnostic)]` -- see [rustc_macros::SessionSubdiagnostic].
153 #[rustc_diagnostic_item = "AddSubdiagnostic"]
154 pub trait AddSubdiagnostic {
155 /// Add a subdiagnostic to an existing diagnostic.
156 fn add_to_diagnostic(self, diag: &mut Diagnostic);
159 /// Trait implemented by lint types. This should not be implemented manually. Instead, use
160 /// `#[derive(LintDiagnostic)]` -- see [rustc_macros::LintDiagnostic].
161 #[rustc_diagnostic_item = "DecorateLint"]
162 pub trait DecorateLint<'a, G: EmissionGuarantee> {
163 /// Decorate and emit a lint.
164 fn decorate_lint(self, diag: LintDiagnosticBuilder<'a, G>);
168 #[derive(Clone, Debug, Encodable, Decodable)]
169 pub struct Diagnostic {
170 // NOTE(eddyb) this is private to disallow arbitrary after-the-fact changes,
171 // outside of what methods in this crate themselves allow.
172 pub(crate) level: Level,
174 pub message: Vec<(DiagnosticMessage, Style)>,
175 pub code: Option<DiagnosticId>,
177 pub children: Vec<SubDiagnostic>,
178 pub suggestions: Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
179 args: Vec<DiagnosticArg<'static>>,
181 /// This is not used for highlighting or rendering any error message. Rather, it can be used
182 /// as a sort key to sort a buffer of diagnostics. By default, it is the primary span of
183 /// `span` if there is one. Otherwise, it is `DUMMY_SP`.
186 /// If diagnostic is from Lint, custom hash function ignores notes
187 /// otherwise hash is based on the all the fields
191 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
192 pub enum DiagnosticId {
194 Lint { name: String, has_future_breakage: bool, is_force_warn: bool },
197 /// A "sub"-diagnostic attached to a parent diagnostic.
198 /// For example, a note attached to an error.
199 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
200 pub struct SubDiagnostic {
202 pub message: Vec<(DiagnosticMessage, Style)>,
204 pub render_span: Option<MultiSpan>,
207 #[derive(Debug, PartialEq, Eq)]
208 pub struct DiagnosticStyledString(pub Vec<StringPart>);
210 impl DiagnosticStyledString {
211 pub fn new() -> DiagnosticStyledString {
212 DiagnosticStyledString(vec![])
214 pub fn push_normal<S: Into<String>>(&mut self, t: S) {
215 self.0.push(StringPart::Normal(t.into()));
217 pub fn push_highlighted<S: Into<String>>(&mut self, t: S) {
218 self.0.push(StringPart::Highlighted(t.into()));
220 pub fn push<S: Into<String>>(&mut self, t: S, highlight: bool) {
222 self.push_highlighted(t);
227 pub fn normal<S: Into<String>>(t: S) -> DiagnosticStyledString {
228 DiagnosticStyledString(vec![StringPart::Normal(t.into())])
231 pub fn highlighted<S: Into<String>>(t: S) -> DiagnosticStyledString {
232 DiagnosticStyledString(vec![StringPart::Highlighted(t.into())])
235 pub fn content(&self) -> String {
236 self.0.iter().map(|x| x.content()).collect::<String>()
240 #[derive(Debug, PartialEq, Eq)]
241 pub enum StringPart {
247 pub fn content(&self) -> &str {
249 &StringPart::Normal(ref s) | &StringPart::Highlighted(ref s) => s,
255 pub fn new<M: Into<DiagnosticMessage>>(level: Level, message: M) -> Self {
256 Diagnostic::new_with_code(level, None, message)
259 pub fn new_with_code<M: Into<DiagnosticMessage>>(
261 code: Option<DiagnosticId>,
266 message: vec![(message.into(), Style::NoStyle)],
268 span: MultiSpan::new(),
270 suggestions: Ok(vec![]),
278 pub fn level(&self) -> Level {
282 pub fn is_error(&self) -> bool {
287 | Level::Error { .. }
288 | Level::FailureNote => true,
295 | Level::Expect(_) => false,
299 pub fn update_unstable_expectation_id(
301 unstable_to_stable: &FxHashMap<LintExpectationId, LintExpectationId>,
303 if let Level::Expect(expectation_id) | Level::Warning(Some(expectation_id)) =
306 if expectation_id.is_stable() {
310 // The unstable to stable map only maps the unstable `AttrId` to a stable `HirId` with an attribute index.
311 // The lint index inside the attribute is manually transferred here.
312 let lint_index = expectation_id.get_lint_index();
313 expectation_id.set_lint_index(None);
314 let mut stable_id = *unstable_to_stable
315 .get(&expectation_id)
316 .expect("each unstable `LintExpectationId` must have a matching stable id");
318 stable_id.set_lint_index(lint_index);
319 *expectation_id = stable_id;
323 pub fn has_future_breakage(&self) -> bool {
325 Some(DiagnosticId::Lint { has_future_breakage, .. }) => has_future_breakage,
330 pub fn is_force_warn(&self) -> bool {
332 Some(DiagnosticId::Lint { is_force_warn, .. }) => is_force_warn,
337 /// Delay emission of this diagnostic as a bug.
339 /// This can be useful in contexts where an error indicates a bug but
340 /// typically this only happens when other compilation errors have already
341 /// happened. In those cases this can be used to defer emission of this
342 /// diagnostic as a bug in the compiler only if no other errors have been
345 /// In the meantime, though, callsites are required to deal with the "bug"
346 /// locally in whichever way makes the most sense.
348 pub fn downgrade_to_delayed_bug(&mut self) -> &mut Self {
351 "downgrade_to_delayed_bug: cannot downgrade {:?} to DelayedBug: not an error",
354 self.level = Level::DelayedBug;
359 /// Adds a span/label to be included in the resulting snippet.
361 /// This is pushed onto the [`MultiSpan`] that was created when the diagnostic
362 /// was first built. That means it will be shown together with the original
363 /// span/label, *not* a span added by one of the `span_{note,warn,help,suggestions}` methods.
365 /// This span is *not* considered a ["primary span"][`MultiSpan`]; only
366 /// the `Span` supplied when creating the diagnostic is primary.
367 #[rustc_lint_diagnostics]
368 pub fn span_label(&mut self, span: Span, label: impl Into<SubdiagnosticMessage>) -> &mut Self {
369 self.span.push_span_label(span, self.subdiagnostic_message_to_diagnostic_message(label));
373 /// Labels all the given spans with the provided label.
374 /// See [`Self::span_label()`] for more information.
377 spans: impl IntoIterator<Item = Span>,
378 label: impl AsRef<str>,
380 let label = label.as_ref();
382 self.span_label(span, label);
387 pub fn replace_span_with(&mut self, after: Span) -> &mut Self {
388 let before = self.span.clone();
389 self.set_span(after);
390 for span_label in before.span_labels() {
391 if let Some(label) = span_label.label {
392 self.span.push_span_label(after, label);
398 pub fn note_expected_found(
400 expected_label: &dyn fmt::Display,
401 expected: DiagnosticStyledString,
402 found_label: &dyn fmt::Display,
403 found: DiagnosticStyledString,
405 self.note_expected_found_extra(expected_label, expected, found_label, found, &"", &"")
408 pub fn note_unsuccessful_coercion(
410 expected: DiagnosticStyledString,
411 found: DiagnosticStyledString,
413 let mut msg: Vec<_> = vec![("required when trying to coerce from type `", Style::NoStyle)];
414 msg.extend(expected.0.iter().map(|x| match *x {
415 StringPart::Normal(ref s) => (s.as_str(), Style::NoStyle),
416 StringPart::Highlighted(ref s) => (s.as_str(), Style::Highlight),
418 msg.push(("` to type '", Style::NoStyle));
419 msg.extend(found.0.iter().map(|x| match *x {
420 StringPart::Normal(ref s) => (s.as_str(), Style::NoStyle),
421 StringPart::Highlighted(ref s) => (s.as_str(), Style::Highlight),
423 msg.push(("`", Style::NoStyle));
425 // For now, just attach these as notes
426 self.highlighted_note(msg);
430 pub fn note_expected_found_extra(
432 expected_label: &dyn fmt::Display,
433 expected: DiagnosticStyledString,
434 found_label: &dyn fmt::Display,
435 found: DiagnosticStyledString,
436 expected_extra: &dyn fmt::Display,
437 found_extra: &dyn fmt::Display,
439 let expected_label = expected_label.to_string();
440 let expected_label = if expected_label.is_empty() {
441 "expected".to_string()
443 format!("expected {}", expected_label)
445 let found_label = found_label.to_string();
446 let found_label = if found_label.is_empty() {
449 format!("found {}", found_label)
451 let (found_padding, expected_padding) = if expected_label.len() > found_label.len() {
452 (expected_label.len() - found_label.len(), 0)
454 (0, found_label.len() - expected_label.len())
456 let mut msg: Vec<_> =
457 vec![(format!("{}{} `", " ".repeat(expected_padding), expected_label), Style::NoStyle)];
458 msg.extend(expected.0.iter().map(|x| match *x {
459 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
460 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
462 msg.push((format!("`{}\n", expected_extra), Style::NoStyle));
463 msg.push((format!("{}{} `", " ".repeat(found_padding), found_label), Style::NoStyle));
464 msg.extend(found.0.iter().map(|x| match *x {
465 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
466 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
468 msg.push((format!("`{}", found_extra), Style::NoStyle));
470 // For now, just attach these as notes.
471 self.highlighted_note(msg);
475 pub fn note_trait_signature(&mut self, name: Symbol, signature: String) -> &mut Self {
476 self.highlighted_note(vec![
477 (format!("`{}` from trait: `", name), Style::NoStyle),
478 (signature, Style::Highlight),
479 ("`".to_string(), Style::NoStyle),
484 /// Add a note attached to this diagnostic.
485 #[rustc_lint_diagnostics]
486 pub fn note(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
487 self.sub(Level::Note, msg, MultiSpan::new(), None);
491 pub fn highlighted_note<M: Into<SubdiagnosticMessage>>(
493 msg: Vec<(M, Style)>,
495 self.sub_with_highlights(Level::Note, msg, MultiSpan::new(), None);
499 /// Prints the span with a note above it.
500 /// This is like [`Diagnostic::note()`], but it gets its own span.
501 pub fn note_once(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
502 self.sub(Level::OnceNote, msg, MultiSpan::new(), None);
506 /// Prints the span with a note above it.
507 /// This is like [`Diagnostic::note()`], but it gets its own span.
508 #[rustc_lint_diagnostics]
509 pub fn span_note<S: Into<MultiSpan>>(
512 msg: impl Into<SubdiagnosticMessage>,
514 self.sub(Level::Note, msg, sp.into(), None);
518 /// Prints the span with a note above it.
519 /// This is like [`Diagnostic::note()`], but it gets its own span.
520 pub fn span_note_once<S: Into<MultiSpan>>(
523 msg: impl Into<SubdiagnosticMessage>,
525 self.sub(Level::OnceNote, msg, sp.into(), None);
529 /// Add a warning attached to this diagnostic.
530 #[rustc_lint_diagnostics]
531 pub fn warn(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
532 self.sub(Level::Warning(None), msg, MultiSpan::new(), None);
536 /// Prints the span with a warning above it.
537 /// This is like [`Diagnostic::warn()`], but it gets its own span.
538 #[rustc_lint_diagnostics]
539 pub fn span_warn<S: Into<MultiSpan>>(
542 msg: impl Into<SubdiagnosticMessage>,
544 self.sub(Level::Warning(None), msg, sp.into(), None);
548 /// Add a help message attached to this diagnostic.
549 #[rustc_lint_diagnostics]
550 pub fn help(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
551 self.sub(Level::Help, msg, MultiSpan::new(), None);
555 /// Add a help message attached to this diagnostic with a customizable highlighted message.
556 pub fn highlighted_help(&mut self, msg: Vec<(String, Style)>) -> &mut Self {
557 self.sub_with_highlights(Level::Help, msg, MultiSpan::new(), None);
561 /// Prints the span with some help above it.
562 /// This is like [`Diagnostic::help()`], but it gets its own span.
563 #[rustc_lint_diagnostics]
564 pub fn span_help<S: Into<MultiSpan>>(
567 msg: impl Into<SubdiagnosticMessage>,
569 self.sub(Level::Help, msg, sp.into(), None);
573 /// Help the user upgrade to the latest edition.
574 /// This is factored out to make sure it does the right thing with `Cargo.toml`.
575 pub fn help_use_latest_edition(&mut self) -> &mut Self {
576 if std::env::var_os("CARGO").is_some() {
577 self.help(&format!("set `edition = \"{}\"` in `Cargo.toml`", LATEST_STABLE_EDITION));
579 self.help(&format!("pass `--edition {}` to `rustc`", LATEST_STABLE_EDITION));
581 self.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
585 /// Disallow attaching suggestions this diagnostic.
586 /// Any suggestions attached e.g. with the `span_suggestion_*` methods
587 /// (before and after the call to `disable_suggestions`) will be ignored.
588 pub fn disable_suggestions(&mut self) -> &mut Self {
589 self.suggestions = Err(SuggestionsDisabled);
593 /// Clear any existing suggestions.
594 pub fn clear_suggestions(&mut self) -> &mut Self {
595 if let Ok(suggestions) = &mut self.suggestions {
601 /// Helper for pushing to `self.suggestions`, if available (not disable).
602 fn push_suggestion(&mut self, suggestion: CodeSuggestion) {
603 if let Ok(suggestions) = &mut self.suggestions {
604 suggestions.push(suggestion);
608 /// Show a suggestion that has multiple parts to it.
609 /// In other words, multiple changes need to be applied as part of this suggestion.
610 pub fn multipart_suggestion(
612 msg: impl Into<SubdiagnosticMessage>,
613 suggestion: Vec<(Span, String)>,
614 applicability: Applicability,
616 self.multipart_suggestion_with_style(
620 SuggestionStyle::ShowCode,
624 /// Show a suggestion that has multiple parts to it, always as it's own subdiagnostic.
625 /// In other words, multiple changes need to be applied as part of this suggestion.
626 pub fn multipart_suggestion_verbose(
628 msg: impl Into<SubdiagnosticMessage>,
629 suggestion: Vec<(Span, String)>,
630 applicability: Applicability,
632 self.multipart_suggestion_with_style(
636 SuggestionStyle::ShowAlways,
639 /// [`Diagnostic::multipart_suggestion()`] but you can set the [`SuggestionStyle`].
640 pub fn multipart_suggestion_with_style(
642 msg: impl Into<SubdiagnosticMessage>,
643 suggestion: Vec<(Span, String)>,
644 applicability: Applicability,
645 style: SuggestionStyle,
647 assert!(!suggestion.is_empty());
648 self.push_suggestion(CodeSuggestion {
649 substitutions: vec![Substitution {
652 .map(|(span, snippet)| SubstitutionPart { snippet, span })
655 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
662 /// Prints out a message with for a multipart suggestion without showing the suggested code.
664 /// This is intended to be used for suggestions that are obvious in what the changes need to
665 /// be from the message, showing the span label inline would be visually unpleasant
666 /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
667 /// improve understandability.
668 pub fn tool_only_multipart_suggestion(
670 msg: impl Into<SubdiagnosticMessage>,
671 suggestion: Vec<(Span, String)>,
672 applicability: Applicability,
674 assert!(!suggestion.is_empty());
675 self.push_suggestion(CodeSuggestion {
676 substitutions: vec![Substitution {
679 .map(|(span, snippet)| SubstitutionPart { snippet, span })
682 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
683 style: SuggestionStyle::CompletelyHidden,
689 /// Prints out a message with a suggested edit of the code.
691 /// In case of short messages and a simple suggestion, rustc displays it as a label:
694 /// try adding parentheses: `(tup.0).1`
699 /// * should not end in any punctuation (a `:` is added automatically)
700 /// * should not be a question (avoid language like "did you mean")
701 /// * should not contain any phrases like "the following", "as shown", etc.
702 /// * may look like "to do xyz, use" or "to do xyz, use abc"
703 /// * may contain a name of a function, variable, or type, but not whole expressions
705 /// See `CodeSuggestion` for more information.
706 pub fn span_suggestion(
709 msg: impl Into<SubdiagnosticMessage>,
710 suggestion: impl ToString,
711 applicability: Applicability,
713 self.span_suggestion_with_style(
718 SuggestionStyle::ShowCode,
723 /// [`Diagnostic::span_suggestion()`] but you can set the [`SuggestionStyle`].
724 pub fn span_suggestion_with_style(
727 msg: impl Into<SubdiagnosticMessage>,
728 suggestion: impl ToString,
729 applicability: Applicability,
730 style: SuggestionStyle,
732 self.push_suggestion(CodeSuggestion {
733 substitutions: vec![Substitution {
734 parts: vec![SubstitutionPart { snippet: suggestion.to_string(), span: sp }],
736 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
743 /// Always show the suggested change.
744 pub fn span_suggestion_verbose(
747 msg: impl Into<SubdiagnosticMessage>,
748 suggestion: impl ToString,
749 applicability: Applicability,
751 self.span_suggestion_with_style(
756 SuggestionStyle::ShowAlways,
761 /// Prints out a message with multiple suggested edits of the code.
762 /// See also [`Diagnostic::span_suggestion()`].
763 pub fn span_suggestions(
766 msg: impl Into<SubdiagnosticMessage>,
767 suggestions: impl Iterator<Item = String>,
768 applicability: Applicability,
770 let mut suggestions: Vec<_> = suggestions.collect();
772 let substitutions = suggestions
774 .map(|snippet| Substitution { parts: vec![SubstitutionPart { snippet, span: sp }] })
776 self.push_suggestion(CodeSuggestion {
778 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
779 style: SuggestionStyle::ShowCode,
785 /// Prints out a message with multiple suggested edits of the code.
786 /// See also [`Diagnostic::span_suggestion()`].
787 pub fn multipart_suggestions(
789 msg: impl Into<SubdiagnosticMessage>,
790 suggestions: impl Iterator<Item = Vec<(Span, String)>>,
791 applicability: Applicability,
793 self.push_suggestion(CodeSuggestion {
794 substitutions: suggestions
795 .map(|sugg| Substitution {
798 .map(|(span, snippet)| SubstitutionPart { snippet, span })
802 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
803 style: SuggestionStyle::ShowCode,
808 /// Prints out a message with a suggested edit of the code. If the suggestion is presented
809 /// inline, it will only show the message and not the suggestion.
811 /// See `CodeSuggestion` for more information.
812 pub fn span_suggestion_short(
815 msg: impl Into<SubdiagnosticMessage>,
816 suggestion: impl ToString,
817 applicability: Applicability,
819 self.span_suggestion_with_style(
824 SuggestionStyle::HideCodeInline,
829 /// Prints out a message for a suggestion without showing the suggested code.
831 /// This is intended to be used for suggestions that are obvious in what the changes need to
832 /// be from the message, showing the span label inline would be visually unpleasant
833 /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
834 /// improve understandability.
835 pub fn span_suggestion_hidden(
838 msg: impl Into<SubdiagnosticMessage>,
839 suggestion: impl ToString,
840 applicability: Applicability,
842 self.span_suggestion_with_style(
847 SuggestionStyle::HideCodeAlways,
852 /// Adds a suggestion to the JSON output that will not be shown in the CLI.
854 /// This is intended to be used for suggestions that are *very* obvious in what the changes
855 /// need to be from the message, but we still want other tools to be able to apply them.
856 pub fn tool_only_span_suggestion(
859 msg: impl Into<SubdiagnosticMessage>,
860 suggestion: impl ToString,
861 applicability: Applicability,
863 self.span_suggestion_with_style(
868 SuggestionStyle::CompletelyHidden,
873 /// Add a subdiagnostic from a type that implements `SessionSubdiagnostic` - see
874 /// [rustc_macros::SessionSubdiagnostic].
875 pub fn subdiagnostic(&mut self, subdiagnostic: impl AddSubdiagnostic) -> &mut Self {
876 subdiagnostic.add_to_diagnostic(self);
880 pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self {
881 self.span = sp.into();
882 if let Some(span) = self.span.primary_span() {
883 self.sort_span = span;
888 pub fn set_is_lint(&mut self) -> &mut Self {
893 pub fn code(&mut self, s: DiagnosticId) -> &mut Self {
898 pub fn clear_code(&mut self) -> &mut Self {
903 pub fn get_code(&self) -> Option<DiagnosticId> {
907 pub fn set_primary_message(&mut self, msg: impl Into<DiagnosticMessage>) -> &mut Self {
908 self.message[0] = (msg.into(), Style::NoStyle);
912 pub fn args(&self) -> &[DiagnosticArg<'static>] {
918 name: impl Into<Cow<'static, str>>,
919 arg: impl IntoDiagnosticArg,
921 self.args.push((name.into(), arg.into_diagnostic_arg()));
925 pub fn styled_message(&self) -> &[(DiagnosticMessage, Style)] {
929 /// Helper function that takes a `SubdiagnosticMessage` and returns a `DiagnosticMessage` by
930 /// combining it with the primary message of the diagnostic (if translatable, otherwise it just
931 /// passes the user's string along).
932 fn subdiagnostic_message_to_diagnostic_message(
934 attr: impl Into<SubdiagnosticMessage>,
935 ) -> DiagnosticMessage {
937 self.message.iter().map(|(msg, _)| msg).next().expect("diagnostic with no messages");
938 msg.with_subdiagnostic_message(attr.into())
941 /// Convenience function for internal use, clients should use one of the
942 /// public methods above.
944 /// Used by `proc_macro_server` for implementing `server::Diagnostic`.
948 message: impl Into<SubdiagnosticMessage>,
950 render_span: Option<MultiSpan>,
952 let sub = SubDiagnostic {
955 self.subdiagnostic_message_to_diagnostic_message(message),
961 self.children.push(sub);
964 /// Convenience function for internal use, clients should use one of the
965 /// public methods above.
966 fn sub_with_highlights<M: Into<SubdiagnosticMessage>>(
969 mut message: Vec<(M, Style)>,
971 render_span: Option<MultiSpan>,
973 let message = message
975 .map(|m| (self.subdiagnostic_message_to_diagnostic_message(m.0), m.1))
977 let sub = SubDiagnostic { level, message, span, render_span };
978 self.children.push(sub);
981 /// Fields used for Hash, and PartialEq trait
986 &[(DiagnosticMessage, Style)],
987 &Option<DiagnosticId>,
989 &Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
990 Option<&[SubDiagnostic]>,
998 (if self.is_lint { None } else { Some(&self.children) }),
1003 impl Hash for Diagnostic {
1004 fn hash<H>(&self, state: &mut H)
1008 self.keys().hash(state);
1012 impl PartialEq for Diagnostic {
1013 fn eq(&self, other: &Self) -> bool {
1014 self.keys() == other.keys()