1 use crate::snippet::Style;
3 CodeSuggestion, DiagnosticBuilder, DiagnosticMessage, EmissionGuarantee, Level, MultiSpan,
4 SubdiagnosticMessage, Substitution, SubstitutionPart, SuggestionStyle,
6 use rustc_data_structures::fx::FxHashMap;
7 use rustc_error_messages::FluentValue;
8 use rustc_lint_defs::{Applicability, LintExpectationId};
9 use rustc_span::edition::LATEST_STABLE_EDITION;
10 use rustc_span::symbol::Symbol;
11 use rustc_span::{Span, DUMMY_SP};
14 use std::hash::{Hash, Hasher};
15 use std::panic::Location;
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<'iter, 'source> =
26 (&'iter DiagnosticArgName<'source>, &'iter DiagnosticArgValue<'source>);
28 /// Name of a diagnostic argument.
29 pub type DiagnosticArgName<'source> = Cow<'source, str>;
31 /// Simplified version of `FluentValue` that can implement `Encodable` and `Decodable`. Converted
32 /// to a `FluentValue` by the emitter to be used in diagnostic translation.
33 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
34 pub enum DiagnosticArgValue<'source> {
35 Str(Cow<'source, str>),
39 /// Converts a value of a type into a `DiagnosticArg` (typically a field of an `IntoDiagnostic`
40 /// struct). Implemented as a custom trait rather than `From` so that it is implemented on the type
41 /// being converted rather than on `DiagnosticArgValue`, which enables types from other `rustc_*`
42 /// crates to implement this.
43 pub trait IntoDiagnosticArg {
44 fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static>;
47 impl<'source> Into<FluentValue<'source>> for DiagnosticArgValue<'source> {
48 fn into(self) -> FluentValue<'source> {
50 DiagnosticArgValue::Str(s) => From::from(s),
51 DiagnosticArgValue::Number(n) => From::from(n),
56 /// Trait implemented by error types. This should not be implemented manually. Instead, use
57 /// `#[derive(Subdiagnostic)]` -- see [rustc_macros::Subdiagnostic].
58 #[cfg_attr(bootstrap, rustc_diagnostic_item = "AddSubdiagnostic")]
59 #[cfg_attr(not(bootstrap), rustc_diagnostic_item = "AddToDiagnostic")]
60 pub trait AddToDiagnostic
64 /// Add a subdiagnostic to an existing diagnostic.
65 fn add_to_diagnostic(self, diag: &mut Diagnostic) {
66 self.add_to_diagnostic_with(diag, |_, m| m);
69 /// Add a subdiagnostic to an existing diagnostic where `f` is invoked on every message used
70 /// (to optionally perform eager translation).
71 fn add_to_diagnostic_with<F>(self, diag: &mut Diagnostic, f: F)
73 F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage;
76 /// Trait implemented by lint types. This should not be implemented manually. Instead, use
77 /// `#[derive(LintDiagnostic)]` -- see [rustc_macros::LintDiagnostic].
78 #[rustc_diagnostic_item = "DecorateLint"]
79 pub trait DecorateLint<'a, G: EmissionGuarantee> {
80 /// Decorate and emit a lint.
83 diag: &'b mut DiagnosticBuilder<'a, G>,
84 ) -> &'b mut DiagnosticBuilder<'a, G>;
86 fn msg(&self) -> DiagnosticMessage;
90 #[derive(Clone, Debug, Encodable, Decodable)]
91 pub struct Diagnostic {
92 // NOTE(eddyb) this is private to disallow arbitrary after-the-fact changes,
93 // outside of what methods in this crate themselves allow.
94 pub(crate) level: Level,
96 pub message: Vec<(DiagnosticMessage, Style)>,
97 pub code: Option<DiagnosticId>,
99 pub children: Vec<SubDiagnostic>,
100 pub suggestions: Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
101 args: FxHashMap<DiagnosticArgName<'static>, DiagnosticArgValue<'static>>,
103 /// This is not used for highlighting or rendering any error message. Rather, it can be used
104 /// as a sort key to sort a buffer of diagnostics. By default, it is the primary span of
105 /// `span` if there is one. Otherwise, it is `DUMMY_SP`.
108 /// If diagnostic is from Lint, custom hash function ignores notes
109 /// otherwise hash is based on the all the fields
112 /// With `-Ztrack_diagnostics` enabled,
113 /// we print where in rustc this error was emitted.
114 pub emitted_at: DiagnosticLocation,
117 #[derive(Clone, Debug, Encodable, Decodable)]
118 pub struct DiagnosticLocation {
119 file: Cow<'static, str>,
124 impl DiagnosticLocation {
126 fn caller() -> Self {
127 let loc = Location::caller();
128 DiagnosticLocation { file: loc.file().into(), line: loc.line(), col: loc.column() }
132 impl fmt::Display for DiagnosticLocation {
133 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134 write!(f, "{}:{}:{}", self.file, self.line, self.col)
138 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
139 pub enum DiagnosticId {
141 Lint { name: String, has_future_breakage: bool, is_force_warn: bool },
144 /// A "sub"-diagnostic attached to a parent diagnostic.
145 /// For example, a note attached to an error.
146 #[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
147 pub struct SubDiagnostic {
149 pub message: Vec<(DiagnosticMessage, Style)>,
151 pub render_span: Option<MultiSpan>,
154 #[derive(Debug, PartialEq, Eq)]
155 pub struct DiagnosticStyledString(pub Vec<StringPart>);
157 impl DiagnosticStyledString {
158 pub fn new() -> DiagnosticStyledString {
159 DiagnosticStyledString(vec![])
161 pub fn push_normal<S: Into<String>>(&mut self, t: S) {
162 self.0.push(StringPart::Normal(t.into()));
164 pub fn push_highlighted<S: Into<String>>(&mut self, t: S) {
165 self.0.push(StringPart::Highlighted(t.into()));
167 pub fn push<S: Into<String>>(&mut self, t: S, highlight: bool) {
169 self.push_highlighted(t);
174 pub fn normal<S: Into<String>>(t: S) -> DiagnosticStyledString {
175 DiagnosticStyledString(vec![StringPart::Normal(t.into())])
178 pub fn highlighted<S: Into<String>>(t: S) -> DiagnosticStyledString {
179 DiagnosticStyledString(vec![StringPart::Highlighted(t.into())])
182 pub fn content(&self) -> String {
183 self.0.iter().map(|x| x.content()).collect::<String>()
187 #[derive(Debug, PartialEq, Eq)]
188 pub enum StringPart {
194 pub fn content(&self) -> &str {
196 &StringPart::Normal(ref s) | &StringPart::Highlighted(ref s) => s,
203 pub fn new<M: Into<DiagnosticMessage>>(level: Level, message: M) -> Self {
204 Diagnostic::new_with_code(level, None, message)
208 pub fn new_with_code<M: Into<DiagnosticMessage>>(
210 code: Option<DiagnosticId>,
215 message: vec![(message.into(), Style::NoStyle)],
217 span: MultiSpan::new(),
219 suggestions: Ok(vec![]),
220 args: Default::default(),
223 emitted_at: DiagnosticLocation::caller(),
228 pub fn level(&self) -> Level {
232 pub fn is_error(&self) -> bool {
237 | Level::Error { .. }
238 | Level::FailureNote => true,
245 | Level::Expect(_) => false,
249 pub fn update_unstable_expectation_id(
251 unstable_to_stable: &FxHashMap<LintExpectationId, LintExpectationId>,
253 if let Level::Expect(expectation_id) | Level::Warning(Some(expectation_id)) =
256 if expectation_id.is_stable() {
260 // The unstable to stable map only maps the unstable `AttrId` to a stable `HirId` with an attribute index.
261 // The lint index inside the attribute is manually transferred here.
262 let lint_index = expectation_id.get_lint_index();
263 expectation_id.set_lint_index(None);
264 let mut stable_id = unstable_to_stable
265 .get(&expectation_id)
266 .expect("each unstable `LintExpectationId` must have a matching stable id")
269 stable_id.set_lint_index(lint_index);
270 *expectation_id = stable_id;
274 pub fn has_future_breakage(&self) -> bool {
276 Some(DiagnosticId::Lint { has_future_breakage, .. }) => has_future_breakage,
281 pub fn is_force_warn(&self) -> bool {
283 Some(DiagnosticId::Lint { is_force_warn, .. }) => is_force_warn,
288 /// Delay emission of this diagnostic as a bug.
290 /// This can be useful in contexts where an error indicates a bug but
291 /// typically this only happens when other compilation errors have already
292 /// happened. In those cases this can be used to defer emission of this
293 /// diagnostic as a bug in the compiler only if no other errors have been
296 /// In the meantime, though, callsites are required to deal with the "bug"
297 /// locally in whichever way makes the most sense.
299 pub fn downgrade_to_delayed_bug(&mut self) -> &mut Self {
302 "downgrade_to_delayed_bug: cannot downgrade {:?} to DelayedBug: not an error",
305 self.level = Level::DelayedBug;
310 /// Adds a span/label to be included in the resulting snippet.
312 /// This is pushed onto the [`MultiSpan`] that was created when the diagnostic
313 /// was first built. That means it will be shown together with the original
314 /// span/label, *not* a span added by one of the `span_{note,warn,help,suggestions}` methods.
316 /// This span is *not* considered a ["primary span"][`MultiSpan`]; only
317 /// the `Span` supplied when creating the diagnostic is primary.
318 #[rustc_lint_diagnostics]
319 pub fn span_label(&mut self, span: Span, label: impl Into<SubdiagnosticMessage>) -> &mut Self {
320 self.span.push_span_label(span, self.subdiagnostic_message_to_diagnostic_message(label));
324 /// Labels all the given spans with the provided label.
325 /// See [`Self::span_label()`] for more information.
328 spans: impl IntoIterator<Item = Span>,
329 label: impl AsRef<str>,
331 let label = label.as_ref();
333 self.span_label(span, label);
338 pub fn replace_span_with(&mut self, after: Span) -> &mut Self {
339 let before = self.span.clone();
340 self.set_span(after);
341 for span_label in before.span_labels() {
342 if let Some(label) = span_label.label {
343 self.span.push_span_label(after, label);
349 pub fn note_expected_found(
351 expected_label: &dyn fmt::Display,
352 expected: DiagnosticStyledString,
353 found_label: &dyn fmt::Display,
354 found: DiagnosticStyledString,
356 self.note_expected_found_extra(expected_label, expected, found_label, found, &"", &"")
359 pub fn note_unsuccessful_coercion(
361 expected: DiagnosticStyledString,
362 found: DiagnosticStyledString,
364 let mut msg: Vec<_> = vec![("required when trying to coerce from type `", Style::NoStyle)];
365 msg.extend(expected.0.iter().map(|x| match *x {
366 StringPart::Normal(ref s) => (s.as_str(), Style::NoStyle),
367 StringPart::Highlighted(ref s) => (s.as_str(), Style::Highlight),
369 msg.push(("` to type '", Style::NoStyle));
370 msg.extend(found.0.iter().map(|x| match *x {
371 StringPart::Normal(ref s) => (s.as_str(), Style::NoStyle),
372 StringPart::Highlighted(ref s) => (s.as_str(), Style::Highlight),
374 msg.push(("`", Style::NoStyle));
376 // For now, just attach these as notes
377 self.highlighted_note(msg);
381 pub fn note_expected_found_extra(
383 expected_label: &dyn fmt::Display,
384 expected: DiagnosticStyledString,
385 found_label: &dyn fmt::Display,
386 found: DiagnosticStyledString,
387 expected_extra: &dyn fmt::Display,
388 found_extra: &dyn fmt::Display,
390 let expected_label = expected_label.to_string();
391 let expected_label = if expected_label.is_empty() {
392 "expected".to_string()
394 format!("expected {}", expected_label)
396 let found_label = found_label.to_string();
397 let found_label = if found_label.is_empty() {
400 format!("found {}", found_label)
402 let (found_padding, expected_padding) = if expected_label.len() > found_label.len() {
403 (expected_label.len() - found_label.len(), 0)
405 (0, found_label.len() - expected_label.len())
407 let mut msg: Vec<_> =
408 vec![(format!("{}{} `", " ".repeat(expected_padding), expected_label), Style::NoStyle)];
409 msg.extend(expected.0.iter().map(|x| match *x {
410 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
411 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
413 msg.push((format!("`{}\n", expected_extra), Style::NoStyle));
414 msg.push((format!("{}{} `", " ".repeat(found_padding), found_label), Style::NoStyle));
415 msg.extend(found.0.iter().map(|x| match *x {
416 StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle),
417 StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight),
419 msg.push((format!("`{}", found_extra), Style::NoStyle));
421 // For now, just attach these as notes.
422 self.highlighted_note(msg);
426 pub fn note_trait_signature(&mut self, name: Symbol, signature: String) -> &mut Self {
427 self.highlighted_note(vec![
428 (format!("`{}` from trait: `", name), Style::NoStyle),
429 (signature, Style::Highlight),
430 ("`".to_string(), Style::NoStyle),
435 /// Add a note attached to this diagnostic.
436 #[rustc_lint_diagnostics]
437 pub fn note(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
438 self.sub(Level::Note, msg, MultiSpan::new(), None);
442 pub fn highlighted_note<M: Into<SubdiagnosticMessage>>(
444 msg: Vec<(M, Style)>,
446 self.sub_with_highlights(Level::Note, msg, MultiSpan::new(), None);
450 /// Prints the span with a note above it.
451 /// This is like [`Diagnostic::note()`], but it gets its own span.
452 pub fn note_once(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
453 self.sub(Level::OnceNote, msg, MultiSpan::new(), None);
457 /// Prints the span with a note above it.
458 /// This is like [`Diagnostic::note()`], but it gets its own span.
459 #[rustc_lint_diagnostics]
460 pub fn span_note<S: Into<MultiSpan>>(
463 msg: impl Into<SubdiagnosticMessage>,
465 self.sub(Level::Note, msg, sp.into(), None);
469 /// Prints the span with a note above it.
470 /// This is like [`Diagnostic::note()`], but it gets its own span.
471 pub fn span_note_once<S: Into<MultiSpan>>(
474 msg: impl Into<SubdiagnosticMessage>,
476 self.sub(Level::OnceNote, msg, sp.into(), None);
480 /// Add a warning attached to this diagnostic.
481 #[rustc_lint_diagnostics]
482 pub fn warn(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
483 self.sub(Level::Warning(None), msg, MultiSpan::new(), None);
487 /// Prints the span with a warning above it.
488 /// This is like [`Diagnostic::warn()`], but it gets its own span.
489 #[rustc_lint_diagnostics]
490 pub fn span_warn<S: Into<MultiSpan>>(
493 msg: impl Into<SubdiagnosticMessage>,
495 self.sub(Level::Warning(None), msg, sp.into(), None);
499 /// Add a help message attached to this diagnostic.
500 #[rustc_lint_diagnostics]
501 pub fn help(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
502 self.sub(Level::Help, msg, MultiSpan::new(), None);
506 /// Add a help message attached to this diagnostic with a customizable highlighted message.
507 pub fn highlighted_help(&mut self, msg: Vec<(String, Style)>) -> &mut Self {
508 self.sub_with_highlights(Level::Help, msg, MultiSpan::new(), None);
512 /// Prints the span with some help above it.
513 /// This is like [`Diagnostic::help()`], but it gets its own span.
514 #[rustc_lint_diagnostics]
515 pub fn span_help<S: Into<MultiSpan>>(
518 msg: impl Into<SubdiagnosticMessage>,
520 self.sub(Level::Help, msg, sp.into(), None);
524 /// Help the user upgrade to the latest edition.
525 /// This is factored out to make sure it does the right thing with `Cargo.toml`.
526 pub fn help_use_latest_edition(&mut self) -> &mut Self {
527 if std::env::var_os("CARGO").is_some() {
528 self.help(&format!("set `edition = \"{}\"` in `Cargo.toml`", LATEST_STABLE_EDITION));
530 self.help(&format!("pass `--edition {}` to `rustc`", LATEST_STABLE_EDITION));
532 self.note("for more on editions, read https://doc.rust-lang.org/edition-guide");
536 /// Disallow attaching suggestions this diagnostic.
537 /// Any suggestions attached e.g. with the `span_suggestion_*` methods
538 /// (before and after the call to `disable_suggestions`) will be ignored.
539 pub fn disable_suggestions(&mut self) -> &mut Self {
540 self.suggestions = Err(SuggestionsDisabled);
544 /// Clear any existing suggestions.
545 pub fn clear_suggestions(&mut self) -> &mut Self {
546 if let Ok(suggestions) = &mut self.suggestions {
552 /// Helper for pushing to `self.suggestions`, if available (not disable).
553 fn push_suggestion(&mut self, suggestion: CodeSuggestion) {
554 if let Ok(suggestions) = &mut self.suggestions {
555 suggestions.push(suggestion);
559 /// Show a suggestion that has multiple parts to it.
560 /// In other words, multiple changes need to be applied as part of this suggestion.
561 pub fn multipart_suggestion(
563 msg: impl Into<SubdiagnosticMessage>,
564 suggestion: Vec<(Span, String)>,
565 applicability: Applicability,
567 self.multipart_suggestion_with_style(
571 SuggestionStyle::ShowCode,
575 /// Show a suggestion that has multiple parts to it, always as it's own subdiagnostic.
576 /// In other words, multiple changes need to be applied as part of this suggestion.
577 pub fn multipart_suggestion_verbose(
579 msg: impl Into<SubdiagnosticMessage>,
580 suggestion: Vec<(Span, String)>,
581 applicability: Applicability,
583 self.multipart_suggestion_with_style(
587 SuggestionStyle::ShowAlways,
590 /// [`Diagnostic::multipart_suggestion()`] but you can set the [`SuggestionStyle`].
591 pub fn multipart_suggestion_with_style(
593 msg: impl Into<SubdiagnosticMessage>,
594 suggestion: Vec<(Span, String)>,
595 applicability: Applicability,
596 style: SuggestionStyle,
598 assert!(!suggestion.is_empty());
600 !(suggestion.iter().any(|(sp, text)| sp.is_empty() && text.is_empty())),
601 "Span must not be empty and have no suggestion"
604 self.push_suggestion(CodeSuggestion {
605 substitutions: vec![Substitution {
608 .map(|(span, snippet)| SubstitutionPart { snippet, span })
611 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
618 /// Prints out a message with for a multipart suggestion without showing the suggested code.
620 /// This is intended to be used for suggestions that are obvious in what the changes need to
621 /// be from the message, showing the span label inline would be visually unpleasant
622 /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
623 /// improve understandability.
624 pub fn tool_only_multipart_suggestion(
626 msg: impl Into<SubdiagnosticMessage>,
627 suggestion: Vec<(Span, String)>,
628 applicability: Applicability,
630 self.multipart_suggestion_with_style(
634 SuggestionStyle::CompletelyHidden,
638 /// Prints out a message with a suggested edit of the code.
640 /// In case of short messages and a simple suggestion, rustc displays it as a label:
643 /// try adding parentheses: `(tup.0).1`
648 /// * should not end in any punctuation (a `:` is added automatically)
649 /// * should not be a question (avoid language like "did you mean")
650 /// * should not contain any phrases like "the following", "as shown", etc.
651 /// * may look like "to do xyz, use" or "to do xyz, use abc"
652 /// * may contain a name of a function, variable, or type, but not whole expressions
654 /// See `CodeSuggestion` for more information.
655 pub fn span_suggestion(
658 msg: impl Into<SubdiagnosticMessage>,
659 suggestion: impl ToString,
660 applicability: Applicability,
662 self.span_suggestion_with_style(
667 SuggestionStyle::ShowCode,
672 /// [`Diagnostic::span_suggestion()`] but you can set the [`SuggestionStyle`].
673 pub fn span_suggestion_with_style(
676 msg: impl Into<SubdiagnosticMessage>,
677 suggestion: impl ToString,
678 applicability: Applicability,
679 style: SuggestionStyle,
682 !(sp.is_empty() && suggestion.to_string().is_empty()),
683 "Span must not be empty and have no suggestion"
685 self.push_suggestion(CodeSuggestion {
686 substitutions: vec![Substitution {
687 parts: vec![SubstitutionPart { snippet: suggestion.to_string(), span: sp }],
689 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
696 /// Always show the suggested change.
697 pub fn span_suggestion_verbose(
700 msg: impl Into<SubdiagnosticMessage>,
701 suggestion: impl ToString,
702 applicability: Applicability,
704 self.span_suggestion_with_style(
709 SuggestionStyle::ShowAlways,
714 /// Prints out a message with multiple suggested edits of the code.
715 /// See also [`Diagnostic::span_suggestion()`].
716 pub fn span_suggestions(
719 msg: impl Into<SubdiagnosticMessage>,
720 suggestions: impl Iterator<Item = String>,
721 applicability: Applicability,
723 self.span_suggestions_with_style(
728 SuggestionStyle::ShowCode,
732 /// [`Diagnostic::span_suggestions()`] but you can set the [`SuggestionStyle`].
733 pub fn span_suggestions_with_style(
736 msg: impl Into<SubdiagnosticMessage>,
737 suggestions: impl Iterator<Item = String>,
738 applicability: Applicability,
739 style: SuggestionStyle,
741 let mut suggestions: Vec<_> = suggestions.collect();
745 !(sp.is_empty() && suggestions.iter().any(|suggestion| suggestion.is_empty())),
746 "Span must not be empty and have no suggestion"
749 let substitutions = suggestions
751 .map(|snippet| Substitution { parts: vec![SubstitutionPart { snippet, span: sp }] })
753 self.push_suggestion(CodeSuggestion {
755 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
762 /// Prints out a message with multiple suggested edits of the code, where each edit consists of
764 /// See also [`Diagnostic::multipart_suggestion()`].
765 pub fn multipart_suggestions(
767 msg: impl Into<SubdiagnosticMessage>,
768 suggestions: impl Iterator<Item = Vec<(Span, String)>>,
769 applicability: Applicability,
771 let suggestions: Vec<_> = suggestions.collect();
775 .flat_map(|suggs| suggs)
776 .any(|(sp, suggestion)| sp.is_empty() && suggestion.is_empty())),
777 "Span must not be empty and have no suggestion"
780 self.push_suggestion(CodeSuggestion {
781 substitutions: suggestions
783 .map(|sugg| Substitution {
786 .map(|(span, snippet)| SubstitutionPart { snippet, span })
790 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
791 style: SuggestionStyle::ShowCode,
797 /// Prints out a message with a suggested edit of the code. If the suggestion is presented
798 /// inline, it will only show the message and not the suggestion.
800 /// See `CodeSuggestion` for more information.
801 pub fn span_suggestion_short(
804 msg: impl Into<SubdiagnosticMessage>,
805 suggestion: impl ToString,
806 applicability: Applicability,
808 self.span_suggestion_with_style(
813 SuggestionStyle::HideCodeInline,
818 /// Prints out a message for a suggestion without showing the suggested code.
820 /// This is intended to be used for suggestions that are obvious in what the changes need to
821 /// be from the message, showing the span label inline would be visually unpleasant
822 /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
823 /// improve understandability.
824 pub fn span_suggestion_hidden(
827 msg: impl Into<SubdiagnosticMessage>,
828 suggestion: impl ToString,
829 applicability: Applicability,
831 self.span_suggestion_with_style(
836 SuggestionStyle::HideCodeAlways,
841 /// Adds a suggestion to the JSON output that will not be shown in the CLI.
843 /// This is intended to be used for suggestions that are *very* obvious in what the changes
844 /// need to be from the message, but we still want other tools to be able to apply them.
845 pub fn tool_only_span_suggestion(
848 msg: impl Into<SubdiagnosticMessage>,
849 suggestion: impl ToString,
850 applicability: Applicability,
852 self.span_suggestion_with_style(
857 SuggestionStyle::CompletelyHidden,
862 /// Add a subdiagnostic from a type that implements `Subdiagnostic` (see
863 /// [rustc_macros::Subdiagnostic]).
864 pub fn subdiagnostic(&mut self, subdiagnostic: impl AddToDiagnostic) -> &mut Self {
865 subdiagnostic.add_to_diagnostic(self);
869 /// Add a subdiagnostic from a type that implements `Subdiagnostic` (see
870 /// [rustc_macros::Subdiagnostic]). Performs eager translation of any translatable messages
871 /// used in the subdiagnostic, so suitable for use with repeated messages (i.e. re-use of
872 /// interpolated variables).
873 pub fn eager_subdiagnostic(
875 handler: &crate::Handler,
876 subdiagnostic: impl AddToDiagnostic,
878 subdiagnostic.add_to_diagnostic_with(self, |diag, msg| {
879 let args = diag.args();
880 let msg = diag.subdiagnostic_message_to_diagnostic_message(msg);
881 handler.eagerly_translate(msg, args)
886 pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self {
887 self.span = sp.into();
888 if let Some(span) = self.span.primary_span() {
889 self.sort_span = span;
894 pub fn set_is_lint(&mut self) -> &mut Self {
899 pub fn code(&mut self, s: DiagnosticId) -> &mut Self {
904 pub fn clear_code(&mut self) -> &mut Self {
909 pub fn get_code(&self) -> Option<DiagnosticId> {
913 pub fn set_primary_message(&mut self, msg: impl Into<DiagnosticMessage>) -> &mut Self {
914 self.message[0] = (msg.into(), Style::NoStyle);
918 // Exact iteration order of diagnostic arguments shouldn't make a difference to output because
919 // they're only used in interpolation.
920 #[allow(rustc::potential_query_instability)]
921 pub fn args<'a>(&'a self) -> impl Iterator<Item = DiagnosticArg<'a, 'static>> {
927 name: impl Into<Cow<'static, str>>,
928 arg: impl IntoDiagnosticArg,
930 self.args.insert(name.into(), arg.into_diagnostic_arg());
934 pub fn styled_message(&self) -> &[(DiagnosticMessage, Style)] {
938 /// Helper function that takes a `SubdiagnosticMessage` and returns a `DiagnosticMessage` by
939 /// combining it with the primary message of the diagnostic (if translatable, otherwise it just
940 /// passes the user's string along).
941 pub(crate) fn subdiagnostic_message_to_diagnostic_message(
943 attr: impl Into<SubdiagnosticMessage>,
944 ) -> DiagnosticMessage {
946 self.message.iter().map(|(msg, _)| msg).next().expect("diagnostic with no messages");
947 msg.with_subdiagnostic_message(attr.into())
950 /// Convenience function for internal use, clients should use one of the
951 /// public methods above.
953 /// Used by `proc_macro_server` for implementing `server::Diagnostic`.
957 message: impl Into<SubdiagnosticMessage>,
959 render_span: Option<MultiSpan>,
961 let sub = SubDiagnostic {
964 self.subdiagnostic_message_to_diagnostic_message(message),
970 self.children.push(sub);
973 /// Convenience function for internal use, clients should use one of the
974 /// public methods above.
975 fn sub_with_highlights<M: Into<SubdiagnosticMessage>>(
978 message: Vec<(M, Style)>,
980 render_span: Option<MultiSpan>,
982 let message = message
984 .map(|m| (self.subdiagnostic_message_to_diagnostic_message(m.0), m.1))
986 let sub = SubDiagnostic { level, message, span, render_span };
987 self.children.push(sub);
990 /// Fields used for Hash, and PartialEq trait
995 &[(DiagnosticMessage, Style)],
996 &Option<DiagnosticId>,
998 &Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
999 Option<&[SubDiagnostic]>,
1007 (if self.is_lint { None } else { Some(&self.children) }),
1012 impl Hash for Diagnostic {
1013 fn hash<H>(&self, state: &mut H)
1017 self.keys().hash(state);
1021 impl PartialEq for Diagnostic {
1022 fn eq(&self, other: &Self) -> bool {
1023 self.keys() == other.keys()