1 use crate::snippet::Style;
3 CodeSuggestion, DiagnosticBuilder, DiagnosticMessage, EmissionGuarantee, Level, MultiSpan,
4 SubdiagnosticMessage, Substitution, SubstitutionPart, SuggestionStyle,
7 use rustc_ast_pretty::pprust;
8 use rustc_data_structures::fx::FxHashMap;
9 use rustc_error_messages::FluentValue;
11 use rustc_lint_defs::{Applicability, LintExpectationId};
12 use rustc_span::edition::LATEST_STABLE_EDITION;
13 use rustc_span::symbol::{Ident, MacroRulesNormalizedIdent, Symbol};
14 use rustc_span::{edition::Edition, Span, DUMMY_SP};
15 use rustc_target::spec::{PanicStrategy, SplitDebuginfo, StackProtector, TargetTriple};
18 use std::hash::{Hash, Hasher};
19 use std::num::ParseIntError;
20 use std::path::{Path, PathBuf};
22 /// Error type for `Diagnostic`'s `suggestions` field, indicating that
23 /// `.disable_suggestions()` was called on the `Diagnostic`.
24 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
25 pub struct SuggestionsDisabled;
27 /// Simplified version of `FluentArg` that can implement `Encodable` and `Decodable`. Collection of
28 /// `DiagnosticArg` are converted to `FluentArgs` (consuming the collection) at the start of
29 /// diagnostic emission.
30 pub type DiagnosticArg<'iter, 'source> =
31 (&'iter DiagnosticArgName<'source>, &'iter DiagnosticArgValue<'source>);
33 /// Name of a diagnostic argument.
34 pub type DiagnosticArgName<'source> = Cow<'source, str>;
36 /// Simplified version of `FluentValue` that can implement `Encodable` and `Decodable`. Converted
37 /// to a `FluentValue` by the emitter to be used in diagnostic translation.
38 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
39 pub enum DiagnosticArgValue<'source> {
40 Str(Cow<'source, str>),
44 /// Converts a value of a type into a `DiagnosticArg` (typically a field of an `IntoDiagnostic`
45 /// struct). Implemented as a custom trait rather than `From` so that it is implemented on the type
46 /// being converted rather than on `DiagnosticArgValue`, which enables types from other `rustc_*`
47 /// crates to implement this.
48 pub trait IntoDiagnosticArg {
49 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static>;
52 pub struct DiagnosticArgFromDisplay<'a>(pub &'a dyn fmt::Display);
54 impl IntoDiagnosticArg for DiagnosticArgFromDisplay<'_> {
55 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
56 self.0.to_string().into_diagnostic_arg()
60 impl<'a> From<&'a dyn fmt::Display> for DiagnosticArgFromDisplay<'a> {
61 fn from(t: &'a dyn fmt::Display) -> Self {
62 DiagnosticArgFromDisplay(t)
66 impl<'a, T: fmt::Display> From<&'a T> for DiagnosticArgFromDisplay<'a> {
67 fn from(t: &'a T) -> Self {
68 DiagnosticArgFromDisplay(t)
72 macro_rules! into_diagnostic_arg_using_display {
73 ($( $ty:ty ),+ $(,)?) => {
75 impl IntoDiagnosticArg for $ty {
76 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
77 self.to_string().into_diagnostic_arg()
84 into_diagnostic_arg_using_display!(
100 MacroRulesNormalizedIdent,
107 impl IntoDiagnosticArg for bool {
108 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
110 DiagnosticArgValue::Str(Cow::Borrowed("true"))
112 DiagnosticArgValue::Str(Cow::Borrowed("false"))
117 impl IntoDiagnosticArg for char {
118 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
119 DiagnosticArgValue::Str(Cow::Owned(format!("{:?}", self)))
123 impl IntoDiagnosticArg for Symbol {
124 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
125 self.to_ident_string().into_diagnostic_arg()
129 impl<'a> IntoDiagnosticArg for &'a str {
130 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
131 self.to_string().into_diagnostic_arg()
135 impl IntoDiagnosticArg for String {
136 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
137 DiagnosticArgValue::Str(Cow::Owned(self))
141 impl<'a> IntoDiagnosticArg for &'a Path {
142 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
143 DiagnosticArgValue::Str(Cow::Owned(self.display().to_string()))
147 impl IntoDiagnosticArg for PathBuf {
148 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
149 DiagnosticArgValue::Str(Cow::Owned(self.display().to_string()))
153 impl IntoDiagnosticArg for usize {
154 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
155 DiagnosticArgValue::Number(self)
159 impl IntoDiagnosticArg for PanicStrategy {
160 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
161 DiagnosticArgValue::Str(Cow::Owned(self.desc().to_string()))
165 impl<'source> Into<FluentValue<'source>> for DiagnosticArgValue<'source> {
166 fn into(self) -> FluentValue<'source> {
168 DiagnosticArgValue::Str(s) => From::from(s),
169 DiagnosticArgValue::Number(n) => From::from(n),
174 impl IntoDiagnosticArg for hir::ConstContext {
175 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
176 DiagnosticArgValue::Str(Cow::Borrowed(match self {
177 hir::ConstContext::ConstFn => "constant function",
178 hir::ConstContext::Static(_) => "static",
179 hir::ConstContext::Const => "constant",
184 impl IntoDiagnosticArg for ast::Path {
185 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
186 DiagnosticArgValue::Str(Cow::Owned(pprust::path_to_string(&self)))
190 impl IntoDiagnosticArg for ast::token::Token {
191 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
192 DiagnosticArgValue::Str(pprust::token_to_string(&self))
196 impl IntoDiagnosticArg for ast::token::TokenKind {
197 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
198 DiagnosticArgValue::Str(pprust::token_kind_to_string(&self))
202 /// Trait implemented by error types. This should not be implemented manually. Instead, use
203 /// `#[derive(Subdiagnostic)]` -- see [rustc_macros::Subdiagnostic].
204 #[cfg_attr(bootstrap, rustc_diagnostic_item = "AddSubdiagnostic")]
205 #[cfg_attr(not(bootstrap), rustc_diagnostic_item = "AddToDiagnostic")]
206 pub trait AddToDiagnostic
210 /// Add a subdiagnostic to an existing diagnostic.
211 fn add_to_diagnostic(self, diag: &mut Diagnostic) {
212 self.add_to_diagnostic_with(diag, |_, m| m);
215 /// Add a subdiagnostic to an existing diagnostic where `f` is invoked on every message used
216 /// (to optionally perform eager translation).
217 fn add_to_diagnostic_with<F>(self, diag: &mut Diagnostic, f: F)
219 F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage;
222 /// Trait implemented by lint types. This should not be implemented manually. Instead, use
223 /// `#[derive(LintDiagnostic)]` -- see [rustc_macros::LintDiagnostic].
224 #[rustc_diagnostic_item = "DecorateLint"]
225 pub trait DecorateLint<'a, G: EmissionGuarantee> {
226 /// Decorate and emit a lint.
227 fn decorate_lint<'b>(
229 diag: &'b mut DiagnosticBuilder<'a, G>,
230 ) -> &'b mut DiagnosticBuilder<'a, G>;
232 fn msg(&self) -> DiagnosticMessage;
236 #[derive(Clone, Debug, Encodable, Decodable)]
237 pub struct Diagnostic {
238 // NOTE(eddyb) this is private to disallow arbitrary after-the-fact changes,
239 // outside of what methods in this crate themselves allow.
240 pub(crate) level: Level,
242 pub message: Vec<(DiagnosticMessage, Style)>,
243 pub code: Option<DiagnosticId>,
245 pub children: Vec<SubDiagnostic>,
246 pub suggestions: Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
247 args: FxHashMap<DiagnosticArgName<'static>, DiagnosticArgValue<'static>>,
249 /// This is not used for highlighting or rendering any error message. Rather, it can be used
250 /// as a sort key to sort a buffer of diagnostics. By default, it is the primary span of
251 /// `span` if there is one. Otherwise, it is `DUMMY_SP`.
254 /// If diagnostic is from Lint, custom hash function ignores notes
255 /// otherwise hash is based on the all the fields
259 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
260 pub enum DiagnosticId {
262 Lint { name: String, has_future_breakage: bool, is_force_warn: bool },
265 /// A "sub"-diagnostic attached to a parent diagnostic.
266 /// For example, a note attached to an error.
267 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
268 pub struct SubDiagnostic {
270 pub message: Vec<(DiagnosticMessage, Style)>,
272 pub render_span: Option<MultiSpan>,
275 #[derive(Debug, PartialEq, Eq)]
276 pub struct DiagnosticStyledString(pub Vec<StringPart>);
278 impl DiagnosticStyledString {
279 pub fn new() -> DiagnosticStyledString {
280 DiagnosticStyledString(vec![])
282 pub fn push_normal<S: Into<String>>(&mut self, t: S) {
283 self.0.push(StringPart::Normal(t.into()));
285 pub fn push_highlighted<S: Into<String>>(&mut self, t: S) {
286 self.0.push(StringPart::Highlighted(t.into()));
288 pub fn push<S: Into<String>>(&mut self, t: S, highlight: bool) {
290 self.push_highlighted(t);
295 pub fn normal<S: Into<String>>(t: S) -> DiagnosticStyledString {
296 DiagnosticStyledString(vec![StringPart::Normal(t.into())])
299 pub fn highlighted<S: Into<String>>(t: S) -> DiagnosticStyledString {
300 DiagnosticStyledString(vec![StringPart::Highlighted(t.into())])
303 pub fn content(&self) -> String {
304 self.0.iter().map(|x| x.content()).collect::<String>()
308 #[derive(Debug, PartialEq, Eq)]
309 pub enum StringPart {
315 pub fn content(&self) -> &str {
317 &StringPart::Normal(ref s) | &StringPart::Highlighted(ref s) => s,
323 pub fn new<M: Into<DiagnosticMessage>>(level: Level, message: M) -> Self {
324 Diagnostic::new_with_code(level, None, message)
327 pub fn new_with_code<M: Into<DiagnosticMessage>>(
329 code: Option<DiagnosticId>,
334 message: vec![(message.into(), Style::NoStyle)],
336 span: MultiSpan::new(),
338 suggestions: Ok(vec![]),
339 args: Default::default(),
346 pub fn level(&self) -> Level {
350 pub fn is_error(&self) -> bool {
355 | Level::Error { .. }
356 | Level::FailureNote => true,
363 | Level::Expect(_) => false,
367 pub fn update_unstable_expectation_id(
369 unstable_to_stable: &FxHashMap<LintExpectationId, LintExpectationId>,
371 if let Level::Expect(expectation_id) | Level::Warning(Some(expectation_id)) =
374 if expectation_id.is_stable() {
378 // The unstable to stable map only maps the unstable `AttrId` to a stable `HirId` with an attribute index.
379 // The lint index inside the attribute is manually transferred here.
380 let lint_index = expectation_id.get_lint_index();
381 expectation_id.set_lint_index(None);
382 let mut stable_id = unstable_to_stable
383 .get(&expectation_id)
384 .expect("each unstable `LintExpectationId` must have a matching stable id")
387 stable_id.set_lint_index(lint_index);
388 *expectation_id = stable_id;
392 pub fn has_future_breakage(&self) -> bool {
394 Some(DiagnosticId::Lint { has_future_breakage, .. }) => has_future_breakage,
399 pub fn is_force_warn(&self) -> bool {
401 Some(DiagnosticId::Lint { is_force_warn, .. }) => is_force_warn,
406 /// Delay emission of this diagnostic as a bug.
408 /// This can be useful in contexts where an error indicates a bug but
409 /// typically this only happens when other compilation errors have already
410 /// happened. In those cases this can be used to defer emission of this
411 /// diagnostic as a bug in the compiler only if no other errors have been
414 /// In the meantime, though, callsites are required to deal with the "bug"
415 /// locally in whichever way makes the most sense.
417 pub fn downgrade_to_delayed_bug(&mut self) -> &mut Self {
420 "downgrade_to_delayed_bug: cannot downgrade {:?} to DelayedBug: not an error",
423 self.level = Level::DelayedBug;
428 /// Adds a span/label to be included in the resulting snippet.
430 /// This is pushed onto the [`MultiSpan`] that was created when the diagnostic
431 /// was first built. That means it will be shown together with the original
432 /// span/label, *not* a span added by one of the `span_{note,warn,help,suggestions}` methods.
434 /// This span is *not* considered a ["primary span"][`MultiSpan`]; only
435 /// the `Span` supplied when creating the diagnostic is primary.
436 #[rustc_lint_diagnostics]
437 pub fn span_label(&mut self, span: Span, label: impl Into<SubdiagnosticMessage>) -> &mut Self {
438 self.span.push_span_label(span, self.subdiagnostic_message_to_diagnostic_message(label));
442 /// Labels all the given spans with the provided label.
443 /// See [`Self::span_label()`] for more information.
446 spans: impl IntoIterator<Item = Span>,
447 label: impl AsRef<str>,
449 let label = label.as_ref();
451 self.span_label(span, label);
456 pub fn replace_span_with(&mut self, after: Span) -> &mut Self {
457 let before = self.span.clone();
458 self.set_span(after);
459 for span_label in before.span_labels() {
460 if let Some(label) = span_label.label {
461 self.span.push_span_label(after, label);
467 pub fn note_expected_found(
469 expected_label: &dyn fmt::Display,
470 expected: DiagnosticStyledString,
471 found_label: &dyn fmt::Display,
472 found: DiagnosticStyledString,
474 self.note_expected_found_extra(expected_label, expected, found_label, found, &"", &"")
477 pub fn note_unsuccessful_coercion(
479 expected: DiagnosticStyledString,
480 found: DiagnosticStyledString,
482 let mut msg: Vec<_> = vec![("required when trying to coerce from type `", Style::NoStyle)];
483 msg.extend(expected.0.iter().map(|x| match *x {
484 StringPart::Normal(ref s) => (s.as_str(), Style::NoStyle),
485 StringPart::Highlighted(ref s) => (s.as_str(), Style::Highlight),
487 msg.push(("` to type '", Style::NoStyle));
488 msg.extend(found.0.iter().map(|x| match *x {
489 StringPart::Normal(ref s) => (s.as_str(), Style::NoStyle),
490 StringPart::Highlighted(ref s) => (s.as_str(), Style::Highlight),
492 msg.push(("`", Style::NoStyle));
494 // For now, just attach these as notes
495 self.highlighted_note(msg);
499 pub fn note_expected_found_extra(
501 expected_label: &dyn fmt::Display,
502 expected: DiagnosticStyledString,
503 found_label: &dyn fmt::Display,
504 found: DiagnosticStyledString,
505 expected_extra: &dyn fmt::Display,
506 found_extra: &dyn fmt::Display,
508 let expected_label = expected_label.to_string();
509 let expected_label = if expected_label.is_empty() {
510 "expected".to_string()
512 format!("expected {}", expected_label)
514 let found_label = found_label.to_string();
515 let found_label = if found_label.is_empty() {
518 format!("found {}", found_label)
520 let (found_padding, expected_padding) = if expected_label.len() > found_label.len() {
521 (expected_label.len() - found_label.len(), 0)
523 (0, found_label.len() - expected_label.len())
525 let mut msg: Vec<_> =
526 vec![(format!("{}{} `", " ".repeat(expected_padding), expected_label), Style::NoStyle)];
527 msg.extend(expected.0.iter().map(|x| match *x {
528 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
529 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
531 msg.push((format!("`{}\n", expected_extra), Style::NoStyle));
532 msg.push((format!("{}{} `", " ".repeat(found_padding), found_label), Style::NoStyle));
533 msg.extend(found.0.iter().map(|x| match *x {
534 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
535 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
537 msg.push((format!("`{}", found_extra), Style::NoStyle));
539 // For now, just attach these as notes.
540 self.highlighted_note(msg);
544 pub fn note_trait_signature(&mut self, name: Symbol, signature: String) -> &mut Self {
545 self.highlighted_note(vec![
546 (format!("`{}` from trait: `", name), Style::NoStyle),
547 (signature, Style::Highlight),
548 ("`".to_string(), Style::NoStyle),
553 /// Add a note attached to this diagnostic.
554 #[rustc_lint_diagnostics]
555 pub fn note(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
556 self.sub(Level::Note, msg, MultiSpan::new(), None);
560 pub fn highlighted_note<M: Into<SubdiagnosticMessage>>(
562 msg: Vec<(M, Style)>,
564 self.sub_with_highlights(Level::Note, msg, MultiSpan::new(), None);
568 /// Prints the span with a note above it.
569 /// This is like [`Diagnostic::note()`], but it gets its own span.
570 pub fn note_once(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
571 self.sub(Level::OnceNote, msg, MultiSpan::new(), None);
575 /// Prints the span with a note above it.
576 /// This is like [`Diagnostic::note()`], but it gets its own span.
577 #[rustc_lint_diagnostics]
578 pub fn span_note<S: Into<MultiSpan>>(
581 msg: impl Into<SubdiagnosticMessage>,
583 self.sub(Level::Note, msg, sp.into(), None);
587 /// Prints the span with a note above it.
588 /// This is like [`Diagnostic::note()`], but it gets its own span.
589 pub fn span_note_once<S: Into<MultiSpan>>(
592 msg: impl Into<SubdiagnosticMessage>,
594 self.sub(Level::OnceNote, msg, sp.into(), None);
598 /// Add a warning attached to this diagnostic.
599 #[rustc_lint_diagnostics]
600 pub fn warn(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
601 self.sub(Level::Warning(None), msg, MultiSpan::new(), None);
605 /// Prints the span with a warning above it.
606 /// This is like [`Diagnostic::warn()`], but it gets its own span.
607 #[rustc_lint_diagnostics]
608 pub fn span_warn<S: Into<MultiSpan>>(
611 msg: impl Into<SubdiagnosticMessage>,
613 self.sub(Level::Warning(None), msg, sp.into(), None);
617 /// Add a help message attached to this diagnostic.
618 #[rustc_lint_diagnostics]
619 pub fn help(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
620 self.sub(Level::Help, msg, MultiSpan::new(), None);
624 /// Add a help message attached to this diagnostic with a customizable highlighted message.
625 pub fn highlighted_help(&mut self, msg: Vec<(String, Style)>) -> &mut Self {
626 self.sub_with_highlights(Level::Help, msg, MultiSpan::new(), None);
630 /// Prints the span with some help above it.
631 /// This is like [`Diagnostic::help()`], but it gets its own span.
632 #[rustc_lint_diagnostics]
633 pub fn span_help<S: Into<MultiSpan>>(
636 msg: impl Into<SubdiagnosticMessage>,
638 self.sub(Level::Help, msg, sp.into(), None);
642 /// Help the user upgrade to the latest edition.
643 /// This is factored out to make sure it does the right thing with `Cargo.toml`.
644 pub fn help_use_latest_edition(&mut self) -> &mut Self {
645 if std::env::var_os("CARGO").is_some() {
646 self.help(&format!("set `edition = \"{}\"` in `Cargo.toml`", LATEST_STABLE_EDITION));
648 self.help(&format!("pass `--edition {}` to `rustc`", LATEST_STABLE_EDITION));
650 self.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
654 /// Disallow attaching suggestions this diagnostic.
655 /// Any suggestions attached e.g. with the `span_suggestion_*` methods
656 /// (before and after the call to `disable_suggestions`) will be ignored.
657 pub fn disable_suggestions(&mut self) -> &mut Self {
658 self.suggestions = Err(SuggestionsDisabled);
662 /// Clear any existing suggestions.
663 pub fn clear_suggestions(&mut self) -> &mut Self {
664 if let Ok(suggestions) = &mut self.suggestions {
670 /// Helper for pushing to `self.suggestions`, if available (not disable).
671 fn push_suggestion(&mut self, suggestion: CodeSuggestion) {
672 if let Ok(suggestions) = &mut self.suggestions {
673 suggestions.push(suggestion);
677 /// Show a suggestion that has multiple parts to it.
678 /// In other words, multiple changes need to be applied as part of this suggestion.
679 pub fn multipart_suggestion(
681 msg: impl Into<SubdiagnosticMessage>,
682 suggestion: Vec<(Span, String)>,
683 applicability: Applicability,
685 self.multipart_suggestion_with_style(
689 SuggestionStyle::ShowCode,
693 /// Show a suggestion that has multiple parts to it, always as it's own subdiagnostic.
694 /// In other words, multiple changes need to be applied as part of this suggestion.
695 pub fn multipart_suggestion_verbose(
697 msg: impl Into<SubdiagnosticMessage>,
698 suggestion: Vec<(Span, String)>,
699 applicability: Applicability,
701 self.multipart_suggestion_with_style(
705 SuggestionStyle::ShowAlways,
708 /// [`Diagnostic::multipart_suggestion()`] but you can set the [`SuggestionStyle`].
709 pub fn multipart_suggestion_with_style(
711 msg: impl Into<SubdiagnosticMessage>,
712 suggestion: Vec<(Span, String)>,
713 applicability: Applicability,
714 style: SuggestionStyle,
716 assert!(!suggestion.is_empty());
717 self.push_suggestion(CodeSuggestion {
718 substitutions: vec![Substitution {
721 .map(|(span, snippet)| SubstitutionPart { snippet, span })
724 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
731 /// Prints out a message with for a multipart suggestion without showing the suggested code.
733 /// This is intended to be used for suggestions that are obvious in what the changes need to
734 /// be from the message, showing the span label inline would be visually unpleasant
735 /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
736 /// improve understandability.
737 pub fn tool_only_multipart_suggestion(
739 msg: impl Into<SubdiagnosticMessage>,
740 suggestion: Vec<(Span, String)>,
741 applicability: Applicability,
743 self.multipart_suggestion_with_style(
747 SuggestionStyle::CompletelyHidden,
751 /// Prints out a message with a suggested edit of the code.
753 /// In case of short messages and a simple suggestion, rustc displays it as a label:
756 /// try adding parentheses: `(tup.0).1`
761 /// * should not end in any punctuation (a `:` is added automatically)
762 /// * should not be a question (avoid language like "did you mean")
763 /// * should not contain any phrases like "the following", "as shown", etc.
764 /// * may look like "to do xyz, use" or "to do xyz, use abc"
765 /// * may contain a name of a function, variable, or type, but not whole expressions
767 /// See `CodeSuggestion` for more information.
768 pub fn span_suggestion(
771 msg: impl Into<SubdiagnosticMessage>,
772 suggestion: impl ToString,
773 applicability: Applicability,
775 self.span_suggestion_with_style(
780 SuggestionStyle::ShowCode,
785 /// [`Diagnostic::span_suggestion()`] but you can set the [`SuggestionStyle`].
786 pub fn span_suggestion_with_style(
789 msg: impl Into<SubdiagnosticMessage>,
790 suggestion: impl ToString,
791 applicability: Applicability,
792 style: SuggestionStyle,
794 self.push_suggestion(CodeSuggestion {
795 substitutions: vec![Substitution {
796 parts: vec![SubstitutionPart { snippet: suggestion.to_string(), span: sp }],
798 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
805 /// Always show the suggested change.
806 pub fn span_suggestion_verbose(
809 msg: impl Into<SubdiagnosticMessage>,
810 suggestion: impl ToString,
811 applicability: Applicability,
813 self.span_suggestion_with_style(
818 SuggestionStyle::ShowAlways,
823 /// Prints out a message with multiple suggested edits of the code.
824 /// See also [`Diagnostic::span_suggestion()`].
825 pub fn span_suggestions(
828 msg: impl Into<SubdiagnosticMessage>,
829 suggestions: impl Iterator<Item = String>,
830 applicability: Applicability,
832 let mut suggestions: Vec<_> = suggestions.collect();
834 let substitutions = suggestions
836 .map(|snippet| Substitution { parts: vec![SubstitutionPart { snippet, span: sp }] })
838 self.push_suggestion(CodeSuggestion {
840 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
841 style: SuggestionStyle::ShowCode,
847 /// Prints out a message with multiple suggested edits of the code.
848 /// See also [`Diagnostic::span_suggestion()`].
849 pub fn multipart_suggestions(
851 msg: impl Into<SubdiagnosticMessage>,
852 suggestions: impl Iterator<Item = Vec<(Span, String)>>,
853 applicability: Applicability,
855 self.push_suggestion(CodeSuggestion {
856 substitutions: suggestions
857 .map(|sugg| Substitution {
860 .map(|(span, snippet)| SubstitutionPart { snippet, span })
864 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
865 style: SuggestionStyle::ShowCode,
870 /// Prints out a message with a suggested edit of the code. If the suggestion is presented
871 /// inline, it will only show the message and not the suggestion.
873 /// See `CodeSuggestion` for more information.
874 pub fn span_suggestion_short(
877 msg: impl Into<SubdiagnosticMessage>,
878 suggestion: impl ToString,
879 applicability: Applicability,
881 self.span_suggestion_with_style(
886 SuggestionStyle::HideCodeInline,
891 /// Prints out a message for a suggestion without showing the suggested code.
893 /// This is intended to be used for suggestions that are obvious in what the changes need to
894 /// be from the message, showing the span label inline would be visually unpleasant
895 /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
896 /// improve understandability.
897 pub fn span_suggestion_hidden(
900 msg: impl Into<SubdiagnosticMessage>,
901 suggestion: impl ToString,
902 applicability: Applicability,
904 self.span_suggestion_with_style(
909 SuggestionStyle::HideCodeAlways,
914 /// Adds a suggestion to the JSON output that will not be shown in the CLI.
916 /// This is intended to be used for suggestions that are *very* obvious in what the changes
917 /// need to be from the message, but we still want other tools to be able to apply them.
918 pub fn tool_only_span_suggestion(
921 msg: impl Into<SubdiagnosticMessage>,
922 suggestion: impl ToString,
923 applicability: Applicability,
925 self.span_suggestion_with_style(
930 SuggestionStyle::CompletelyHidden,
935 /// Add a subdiagnostic from a type that implements `Subdiagnostic` (see
936 /// [rustc_macros::Subdiagnostic]).
937 pub fn subdiagnostic(&mut self, subdiagnostic: impl AddToDiagnostic) -> &mut Self {
938 subdiagnostic.add_to_diagnostic(self);
942 /// Add a subdiagnostic from a type that implements `Subdiagnostic` (see
943 /// [rustc_macros::Subdiagnostic]). Performs eager translation of any translatable messages
944 /// used in the subdiagnostic, so suitable for use with repeated messages (i.e. re-use of
945 /// interpolated variables).
946 pub fn eager_subdiagnostic(
948 handler: &crate::Handler,
949 subdiagnostic: impl AddToDiagnostic,
951 subdiagnostic.add_to_diagnostic_with(self, |diag, msg| {
952 let args = diag.args();
953 let msg = diag.subdiagnostic_message_to_diagnostic_message(msg);
954 handler.eagerly_translate(msg, args)
959 pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self {
960 self.span = sp.into();
961 if let Some(span) = self.span.primary_span() {
962 self.sort_span = span;
967 pub fn set_is_lint(&mut self) -> &mut Self {
972 pub fn code(&mut self, s: DiagnosticId) -> &mut Self {
977 pub fn clear_code(&mut self) -> &mut Self {
982 pub fn get_code(&self) -> Option<DiagnosticId> {
986 pub fn set_primary_message(&mut self, msg: impl Into<DiagnosticMessage>) -> &mut Self {
987 self.message[0] = (msg.into(), Style::NoStyle);
991 // Exact iteration order of diagnostic arguments shouldn't make a difference to output because
992 // they're only used in interpolation.
993 #[allow(rustc::potential_query_instability)]
994 pub fn args<'a>(&'a self) -> impl Iterator<Item = DiagnosticArg<'a, 'static>> {
1000 name: impl Into<Cow<'static, str>>,
1001 arg: impl IntoDiagnosticArg,
1003 self.args.insert(name.into(), arg.into_diagnostic_arg());
1007 pub fn styled_message(&self) -> &[(DiagnosticMessage, Style)] {
1011 /// Helper function that takes a `SubdiagnosticMessage` and returns a `DiagnosticMessage` by
1012 /// combining it with the primary message of the diagnostic (if translatable, otherwise it just
1013 /// passes the user's string along).
1014 pub(crate) fn subdiagnostic_message_to_diagnostic_message(
1016 attr: impl Into<SubdiagnosticMessage>,
1017 ) -> DiagnosticMessage {
1019 self.message.iter().map(|(msg, _)| msg).next().expect("diagnostic with no messages");
1020 msg.with_subdiagnostic_message(attr.into())
1023 /// Convenience function for internal use, clients should use one of the
1024 /// public methods above.
1026 /// Used by `proc_macro_server` for implementing `server::Diagnostic`.
1030 message: impl Into<SubdiagnosticMessage>,
1032 render_span: Option<MultiSpan>,
1034 let sub = SubDiagnostic {
1037 self.subdiagnostic_message_to_diagnostic_message(message),
1043 self.children.push(sub);
1046 /// Convenience function for internal use, clients should use one of the
1047 /// public methods above.
1048 fn sub_with_highlights<M: Into<SubdiagnosticMessage>>(
1051 message: Vec<(M, Style)>,
1053 render_span: Option<MultiSpan>,
1055 let message = message
1057 .map(|m| (self.subdiagnostic_message_to_diagnostic_message(m.0), m.1))
1059 let sub = SubDiagnostic { level, message, span, render_span };
1060 self.children.push(sub);
1063 /// Fields used for Hash, and PartialEq trait
1068 &[(DiagnosticMessage, Style)],
1069 &Option<DiagnosticId>,
1071 &Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
1072 Option<&[SubDiagnostic]>,
1080 (if self.is_lint { None } else { Some(&self.children) }),
1085 impl Hash for Diagnostic {
1086 fn hash<H>(&self, state: &mut H)
1090 self.keys().hash(state);
1094 impl PartialEq for Diagnostic {
1095 fn eq(&self, other: &Self) -> bool {
1096 self.keys() == other.keys()