1use std::borrow::Cow;
2use std::fmt::{self, Debug};
3use std::hash::{Hash, Hasher};
4use std::marker::PhantomData;
5use std::ops::{Deref, DerefMut};
6use std::panic;
7use std::path::PathBuf;
8use std::thread::panicking;
9
10use rustc_data_structures::fx::FxIndexMap;
11use rustc_error_messages::{FluentValue, fluent_value_from_str_list_sep_by_and};
12use rustc_lint_defs::Applicability;
13use rustc_macros::{Decodable, Encodable};
14use rustc_span::source_map::Spanned;
15use rustc_span::{DUMMY_SP, Span, Symbol};
16use tracing::debug;
17
18use crate::snippet::Style;
19use crate::{
20 CodeSuggestion, DiagCtxtHandle, DiagMessage, ErrCode, ErrorGuaranteed, ExplicitBug, Level,
21 MultiSpan, StashKey, SubdiagMessage, Substitution, SubstitutionPart, SuggestionStyle,
22 Suggestions,
23};
24
25pub type DiagArg<'iter> = (&'iter DiagArgName, &'iter DiagArgValue);
29
30pub type DiagArgName = Cow<'static, str>;
32
33#[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
36pub enum DiagArgValue {
37 Str(Cow<'static, str>),
38 Number(i32),
42 StrListSepByAnd(Vec<Cow<'static, str>>),
43}
44
45pub type DiagArgMap = FxIndexMap<DiagArgName, DiagArgValue>;
46
47pub trait EmissionGuarantee: Sized {
50 type EmitResult = Self;
53
54 #[track_caller]
58 fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult;
59}
60
61impl EmissionGuarantee for ErrorGuaranteed {
62 fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult {
63 diag.emit_producing_error_guaranteed()
64 }
65}
66
67impl EmissionGuarantee for () {
68 fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult {
69 diag.emit_producing_nothing();
70 }
71}
72
73#[derive(Copy, Clone)]
76pub struct BugAbort;
77
78impl EmissionGuarantee for BugAbort {
79 type EmitResult = !;
80
81 fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult {
82 diag.emit_producing_nothing();
83 panic::panic_any(ExplicitBug);
84 }
85}
86
87#[derive(Copy, Clone)]
90pub struct FatalAbort;
91
92impl EmissionGuarantee for FatalAbort {
93 type EmitResult = !;
94
95 fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult {
96 diag.emit_producing_nothing();
97 crate::FatalError.raise()
98 }
99}
100
101impl EmissionGuarantee for rustc_span::fatal_error::FatalError {
102 fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult {
103 diag.emit_producing_nothing();
104 rustc_span::fatal_error::FatalError
105 }
106}
107
108#[rustc_diagnostic_item = "Diagnostic"]
130pub trait Diagnostic<'a, G: EmissionGuarantee = ErrorGuaranteed> {
131 #[must_use]
133 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G>;
134}
135
136impl<'a, T, G> Diagnostic<'a, G> for Spanned<T>
137where
138 T: Diagnostic<'a, G>,
139 G: EmissionGuarantee,
140{
141 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G> {
142 self.node.into_diag(dcx, level).with_span(self.span)
143 }
144}
145
146pub trait IntoDiagArg {
151 fn into_diag_arg(self) -> DiagArgValue;
152}
153
154impl IntoDiagArg for DiagArgValue {
155 fn into_diag_arg(self) -> DiagArgValue {
156 self
157 }
158}
159
160impl From<DiagArgValue> for FluentValue<'static> {
161 fn from(val: DiagArgValue) -> Self {
162 match val {
163 DiagArgValue::Str(s) => From::from(s),
164 DiagArgValue::Number(n) => From::from(n),
165 DiagArgValue::StrListSepByAnd(l) => fluent_value_from_str_list_sep_by_and(l),
166 }
167 }
168}
169
170#[rustc_diagnostic_item = "Subdiagnostic"]
173pub trait Subdiagnostic
174where
175 Self: Sized,
176{
177 fn add_to_diag<G: EmissionGuarantee>(self, diag: &mut Diag<'_, G>) {
179 self.add_to_diag_with(diag, &|_, m| m);
180 }
181
182 fn add_to_diag_with<G: EmissionGuarantee, F: SubdiagMessageOp<G>>(
185 self,
186 diag: &mut Diag<'_, G>,
187 f: &F,
188 );
189}
190
191pub trait SubdiagMessageOp<G: EmissionGuarantee> =
192 Fn(&mut Diag<'_, G>, SubdiagMessage) -> SubdiagMessage;
193
194#[rustc_diagnostic_item = "LintDiagnostic"]
197pub trait LintDiagnostic<'a, G: EmissionGuarantee> {
198 fn decorate_lint<'b>(self, diag: &'b mut Diag<'a, G>);
200}
201
202#[derive(Clone, Debug, Encodable, Decodable)]
203pub(crate) struct DiagLocation {
204 file: Cow<'static, str>,
205 line: u32,
206 col: u32,
207}
208
209impl DiagLocation {
210 #[track_caller]
211 fn caller() -> Self {
212 let loc = panic::Location::caller();
213 DiagLocation { file: loc.file().into(), line: loc.line(), col: loc.column() }
214 }
215}
216
217impl fmt::Display for DiagLocation {
218 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219 write!(f, "{}:{}:{}", self.file, self.line, self.col)
220 }
221}
222
223#[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
224pub struct IsLint {
225 pub(crate) name: String,
227 has_future_breakage: bool,
229}
230
231#[derive(Debug, PartialEq, Eq)]
232pub struct DiagStyledString(pub Vec<StringPart>);
233
234impl DiagStyledString {
235 pub fn new() -> DiagStyledString {
236 DiagStyledString(vec![])
237 }
238 pub fn push_normal<S: Into<String>>(&mut self, t: S) {
239 self.0.push(StringPart::normal(t));
240 }
241 pub fn push_highlighted<S: Into<String>>(&mut self, t: S) {
242 self.0.push(StringPart::highlighted(t));
243 }
244 pub fn push<S: Into<String>>(&mut self, t: S, highlight: bool) {
245 if highlight {
246 self.push_highlighted(t);
247 } else {
248 self.push_normal(t);
249 }
250 }
251 pub fn normal<S: Into<String>>(t: S) -> DiagStyledString {
252 DiagStyledString(vec![StringPart::normal(t)])
253 }
254
255 pub fn highlighted<S: Into<String>>(t: S) -> DiagStyledString {
256 DiagStyledString(vec![StringPart::highlighted(t)])
257 }
258
259 pub fn content(&self) -> String {
260 self.0.iter().map(|x| x.content.as_str()).collect::<String>()
261 }
262}
263
264#[derive(Debug, PartialEq, Eq)]
265pub struct StringPart {
266 content: String,
267 style: Style,
268}
269
270impl StringPart {
271 pub fn normal<S: Into<String>>(content: S) -> StringPart {
272 StringPart { content: content.into(), style: Style::NoStyle }
273 }
274
275 pub fn highlighted<S: Into<String>>(content: S) -> StringPart {
276 StringPart { content: content.into(), style: Style::Highlight }
277 }
278}
279
280#[must_use]
285#[derive(Clone, Debug, Encodable, Decodable)]
286pub struct DiagInner {
287 pub(crate) level: Level,
290
291 pub messages: Vec<(DiagMessage, Style)>,
292 pub code: Option<ErrCode>,
293 pub span: MultiSpan,
294 pub children: Vec<Subdiag>,
295 pub suggestions: Suggestions,
296 pub args: DiagArgMap,
297
298 pub sort_span: Span,
302
303 pub is_lint: Option<IsLint>,
304
305 pub long_ty_path: Option<PathBuf>,
306 pub(crate) emitted_at: DiagLocation,
309}
310
311impl DiagInner {
312 #[track_caller]
313 pub fn new<M: Into<DiagMessage>>(level: Level, message: M) -> Self {
314 DiagInner::new_with_messages(level, vec![(message.into(), Style::NoStyle)])
315 }
316
317 #[track_caller]
318 pub fn new_with_messages(level: Level, messages: Vec<(DiagMessage, Style)>) -> Self {
319 DiagInner {
320 level,
321 messages,
322 code: None,
323 span: MultiSpan::new(),
324 children: vec![],
325 suggestions: Suggestions::Enabled(vec![]),
326 args: Default::default(),
327 sort_span: DUMMY_SP,
328 is_lint: None,
329 long_ty_path: None,
330 emitted_at: DiagLocation::caller(),
331 }
332 }
333
334 #[inline(always)]
335 pub fn level(&self) -> Level {
336 self.level
337 }
338
339 pub fn is_error(&self) -> bool {
340 match self.level {
341 Level::Bug | Level::Fatal | Level::Error | Level::DelayedBug => true,
342
343 Level::ForceWarning(_)
344 | Level::Warning
345 | Level::Note
346 | Level::OnceNote
347 | Level::Help
348 | Level::OnceHelp
349 | Level::FailureNote
350 | Level::Allow
351 | Level::Expect(_) => false,
352 }
353 }
354
355 pub(crate) fn has_future_breakage(&self) -> bool {
357 matches!(self.is_lint, Some(IsLint { has_future_breakage: true, .. }))
358 }
359
360 pub(crate) fn is_force_warn(&self) -> bool {
361 match self.level {
362 Level::ForceWarning(_) => {
363 assert!(self.is_lint.is_some());
364 true
365 }
366 _ => false,
367 }
368 }
369
370 pub(crate) fn subdiagnostic_message_to_diagnostic_message(
372 &self,
373 attr: impl Into<SubdiagMessage>,
374 ) -> DiagMessage {
375 let msg =
376 self.messages.iter().map(|(msg, _)| msg).next().expect("diagnostic with no messages");
377 msg.with_subdiagnostic_message(attr.into())
378 }
379
380 pub(crate) fn sub(
381 &mut self,
382 level: Level,
383 message: impl Into<SubdiagMessage>,
384 span: MultiSpan,
385 ) {
386 let sub = Subdiag {
387 level,
388 messages: vec![(
389 self.subdiagnostic_message_to_diagnostic_message(message),
390 Style::NoStyle,
391 )],
392 span,
393 };
394 self.children.push(sub);
395 }
396
397 pub(crate) fn arg(&mut self, name: impl Into<DiagArgName>, arg: impl IntoDiagArg) {
398 self.args.insert(name.into(), arg.into_diag_arg());
399 }
400
401 fn keys(
403 &self,
404 ) -> (
405 &Level,
406 &[(DiagMessage, Style)],
407 &Option<ErrCode>,
408 &MultiSpan,
409 &[Subdiag],
410 &Suggestions,
411 Vec<(&DiagArgName, &DiagArgValue)>,
412 &Option<IsLint>,
413 ) {
414 (
415 &self.level,
416 &self.messages,
417 &self.code,
418 &self.span,
419 &self.children,
420 &self.suggestions,
421 self.args.iter().collect(),
422 &self.is_lint,
424 )
426 }
427}
428
429impl Hash for DiagInner {
430 fn hash<H>(&self, state: &mut H)
431 where
432 H: Hasher,
433 {
434 self.keys().hash(state);
435 }
436}
437
438impl PartialEq for DiagInner {
439 fn eq(&self, other: &Self) -> bool {
440 self.keys() == other.keys()
441 }
442}
443
444#[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
447pub struct Subdiag {
448 pub level: Level,
449 pub messages: Vec<(DiagMessage, Style)>,
450 pub span: MultiSpan,
451}
452
453#[must_use]
466pub struct Diag<'a, G: EmissionGuarantee = ErrorGuaranteed> {
467 pub dcx: DiagCtxtHandle<'a>,
468
469 diag: Option<Box<DiagInner>>,
479
480 _marker: PhantomData<G>,
481}
482
483impl<G> !Clone for Diag<'_, G> {}
486
487rustc_data_structures::static_assert_size!(Diag<'_, ()>, 3 * std::mem::size_of::<usize>());
488
489impl<G: EmissionGuarantee> Deref for Diag<'_, G> {
490 type Target = DiagInner;
491
492 fn deref(&self) -> &DiagInner {
493 self.diag.as_ref().unwrap()
494 }
495}
496
497impl<G: EmissionGuarantee> DerefMut for Diag<'_, G> {
498 fn deref_mut(&mut self) -> &mut DiagInner {
499 self.diag.as_mut().unwrap()
500 }
501}
502
503impl<G: EmissionGuarantee> Debug for Diag<'_, G> {
504 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
505 self.diag.fmt(f)
506 }
507}
508
509macro_rules! with_fn {
528 {
529 $with_f:ident,
530 $(#[$attrs:meta])*
531 pub fn $f:ident(&mut $self:ident, $($name:ident: $ty:ty),* $(,)?) -> &mut Self {
532 $($body:tt)*
533 }
534 } => {
535 $(#[$attrs])*
537 #[doc = concat!("See [`Diag::", stringify!($f), "()`].")]
538 pub fn $f(&mut $self, $($name: $ty),*) -> &mut Self {
539 $($body)*
540 }
541
542 $(#[$attrs])*
544 #[doc = concat!("See [`Diag::", stringify!($f), "()`].")]
545 pub fn $with_f(mut $self, $($name: $ty),*) -> Self {
546 $self.$f($($name),*);
547 $self
548 }
549 };
550}
551
552impl<'a, G: EmissionGuarantee> Diag<'a, G> {
553 #[rustc_lint_diagnostics]
554 #[track_caller]
555 pub fn new(dcx: DiagCtxtHandle<'a>, level: Level, message: impl Into<DiagMessage>) -> Self {
556 Self::new_diagnostic(dcx, DiagInner::new(level, message))
557 }
558
559 pub fn with_dcx(mut self, dcx: DiagCtxtHandle<'_>) -> Diag<'_, G> {
561 Diag { dcx, diag: self.diag.take(), _marker: PhantomData }
562 }
563
564 #[track_caller]
566 pub(crate) fn new_diagnostic(dcx: DiagCtxtHandle<'a>, diag: DiagInner) -> Self {
567 debug!("Created new diagnostic");
568 Self { dcx, diag: Some(Box::new(diag)), _marker: PhantomData }
569 }
570
571 #[rustc_lint_diagnostics]
582 #[track_caller]
583 pub fn downgrade_to_delayed_bug(&mut self) {
584 assert!(
585 matches!(self.level, Level::Error | Level::DelayedBug),
586 "downgrade_to_delayed_bug: cannot downgrade {:?} to DelayedBug: not an error",
587 self.level
588 );
589 self.level = Level::DelayedBug;
590 }
591
592 with_fn! { with_span_label,
593 #[rustc_lint_diagnostics]
606 pub fn span_label(&mut self, span: Span, label: impl Into<SubdiagMessage>) -> &mut Self {
607 let msg = self.subdiagnostic_message_to_diagnostic_message(label);
608 self.span.push_span_label(span, msg);
609 self
610 } }
611
612 with_fn! { with_span_labels,
613 #[rustc_lint_diagnostics]
616 pub fn span_labels(&mut self, spans: impl IntoIterator<Item = Span>, label: &str) -> &mut Self {
617 for span in spans {
618 self.span_label(span, label.to_string());
619 }
620 self
621 } }
622
623 #[rustc_lint_diagnostics]
624 pub fn replace_span_with(&mut self, after: Span, keep_label: bool) -> &mut Self {
625 let before = self.span.clone();
626 self.span(after);
627 for span_label in before.span_labels() {
628 if let Some(label) = span_label.label {
629 if span_label.is_primary && keep_label {
630 self.span.push_span_label(after, label);
631 } else {
632 self.span.push_span_label(span_label.span, label);
633 }
634 }
635 }
636 self
637 }
638
639 #[rustc_lint_diagnostics]
640 pub fn note_expected_found(
641 &mut self,
642 expected_label: &dyn fmt::Display,
643 expected: DiagStyledString,
644 found_label: &dyn fmt::Display,
645 found: DiagStyledString,
646 ) -> &mut Self {
647 self.note_expected_found_extra(
648 expected_label,
649 expected,
650 found_label,
651 found,
652 DiagStyledString::normal(""),
653 DiagStyledString::normal(""),
654 )
655 }
656
657 #[rustc_lint_diagnostics]
658 pub fn note_expected_found_extra(
659 &mut self,
660 expected_label: &dyn fmt::Display,
661 expected: DiagStyledString,
662 found_label: &dyn fmt::Display,
663 found: DiagStyledString,
664 expected_extra: DiagStyledString,
665 found_extra: DiagStyledString,
666 ) -> &mut Self {
667 let expected_label = expected_label.to_string();
668 let expected_label = if expected_label.is_empty() {
669 "expected".to_string()
670 } else {
671 format!("expected {expected_label}")
672 };
673 let found_label = found_label.to_string();
674 let found_label = if found_label.is_empty() {
675 "found".to_string()
676 } else {
677 format!("found {found_label}")
678 };
679 let (found_padding, expected_padding) = if expected_label.len() > found_label.len() {
680 (expected_label.len() - found_label.len(), 0)
681 } else {
682 (0, found_label.len() - expected_label.len())
683 };
684 let mut msg = vec![StringPart::normal(format!(
685 "{}{} `",
686 " ".repeat(expected_padding),
687 expected_label
688 ))];
689 msg.extend(expected.0);
690 msg.push(StringPart::normal(format!("`")));
691 msg.extend(expected_extra.0);
692 msg.push(StringPart::normal(format!("\n")));
693 msg.push(StringPart::normal(format!("{}{} `", " ".repeat(found_padding), found_label)));
694 msg.extend(found.0);
695 msg.push(StringPart::normal(format!("`")));
696 msg.extend(found_extra.0);
697
698 self.highlighted_note(msg);
700 self
701 }
702
703 #[rustc_lint_diagnostics]
704 pub fn note_trait_signature(&mut self, name: Symbol, signature: String) -> &mut Self {
705 self.highlighted_note(vec![
706 StringPart::normal(format!("`{name}` from trait: `")),
707 StringPart::highlighted(signature),
708 StringPart::normal("`"),
709 ]);
710 self
711 }
712
713 with_fn! { with_note,
714 #[rustc_lint_diagnostics]
716 pub fn note(&mut self, msg: impl Into<SubdiagMessage>) -> &mut Self {
717 self.sub(Level::Note, msg, MultiSpan::new());
718 self
719 } }
720
721 #[rustc_lint_diagnostics]
722 pub fn highlighted_note(&mut self, msg: Vec<StringPart>) -> &mut Self {
723 self.sub_with_highlights(Level::Note, msg, MultiSpan::new());
724 self
725 }
726
727 #[rustc_lint_diagnostics]
728 pub fn highlighted_span_note(
729 &mut self,
730 span: impl Into<MultiSpan>,
731 msg: Vec<StringPart>,
732 ) -> &mut Self {
733 self.sub_with_highlights(Level::Note, msg, span.into());
734 self
735 }
736
737 #[rustc_lint_diagnostics]
739 pub fn note_once(&mut self, msg: impl Into<SubdiagMessage>) -> &mut Self {
740 self.sub(Level::OnceNote, msg, MultiSpan::new());
741 self
742 }
743
744 with_fn! { with_span_note,
745 #[rustc_lint_diagnostics]
748 pub fn span_note(
749 &mut self,
750 sp: impl Into<MultiSpan>,
751 msg: impl Into<SubdiagMessage>,
752 ) -> &mut Self {
753 self.sub(Level::Note, msg, sp.into());
754 self
755 } }
756
757 #[rustc_lint_diagnostics]
760 pub fn span_note_once<S: Into<MultiSpan>>(
761 &mut self,
762 sp: S,
763 msg: impl Into<SubdiagMessage>,
764 ) -> &mut Self {
765 self.sub(Level::OnceNote, msg, sp.into());
766 self
767 }
768
769 with_fn! { with_warn,
770 #[rustc_lint_diagnostics]
772 pub fn warn(&mut self, msg: impl Into<SubdiagMessage>) -> &mut Self {
773 self.sub(Level::Warning, msg, MultiSpan::new());
774 self
775 } }
776
777 #[rustc_lint_diagnostics]
780 pub fn span_warn<S: Into<MultiSpan>>(
781 &mut self,
782 sp: S,
783 msg: impl Into<SubdiagMessage>,
784 ) -> &mut Self {
785 self.sub(Level::Warning, msg, sp.into());
786 self
787 }
788
789 with_fn! { with_help,
790 #[rustc_lint_diagnostics]
792 pub fn help(&mut self, msg: impl Into<SubdiagMessage>) -> &mut Self {
793 self.sub(Level::Help, msg, MultiSpan::new());
794 self
795 } }
796
797 #[rustc_lint_diagnostics]
799 pub fn help_once(&mut self, msg: impl Into<SubdiagMessage>) -> &mut Self {
800 self.sub(Level::OnceHelp, msg, MultiSpan::new());
801 self
802 }
803
804 #[rustc_lint_diagnostics]
806 pub fn highlighted_help(&mut self, msg: Vec<StringPart>) -> &mut Self {
807 self.sub_with_highlights(Level::Help, msg, MultiSpan::new());
808 self
809 }
810
811 #[rustc_lint_diagnostics]
813 pub fn highlighted_span_help(
814 &mut self,
815 span: impl Into<MultiSpan>,
816 msg: Vec<StringPart>,
817 ) -> &mut Self {
818 self.sub_with_highlights(Level::Help, msg, span.into());
819 self
820 }
821
822 #[rustc_lint_diagnostics]
825 pub fn span_help<S: Into<MultiSpan>>(
826 &mut self,
827 sp: S,
828 msg: impl Into<SubdiagMessage>,
829 ) -> &mut Self {
830 self.sub(Level::Help, msg, sp.into());
831 self
832 }
833
834 #[rustc_lint_diagnostics]
838 pub fn disable_suggestions(&mut self) -> &mut Self {
839 self.suggestions = Suggestions::Disabled;
840 self
841 }
842
843 #[rustc_lint_diagnostics]
848 pub fn seal_suggestions(&mut self) -> &mut Self {
849 if let Suggestions::Enabled(suggestions) = &mut self.suggestions {
850 let suggestions_slice = std::mem::take(suggestions).into_boxed_slice();
851 self.suggestions = Suggestions::Sealed(suggestions_slice);
852 }
853 self
854 }
855
856 #[rustc_lint_diagnostics]
861 fn push_suggestion(&mut self, suggestion: CodeSuggestion) {
862 for subst in &suggestion.substitutions {
863 for part in &subst.parts {
864 let span = part.span;
865 let call_site = span.ctxt().outer_expn_data().call_site;
866 if span.in_derive_expansion() && span.overlaps_or_adjacent(call_site) {
867 return;
869 }
870 }
871 }
872
873 if let Suggestions::Enabled(suggestions) = &mut self.suggestions {
874 suggestions.push(suggestion);
875 }
876 }
877
878 with_fn! { with_multipart_suggestion,
879 #[rustc_lint_diagnostics]
882 pub fn multipart_suggestion(
883 &mut self,
884 msg: impl Into<SubdiagMessage>,
885 suggestion: Vec<(Span, String)>,
886 applicability: Applicability,
887 ) -> &mut Self {
888 self.multipart_suggestion_with_style(
889 msg,
890 suggestion,
891 applicability,
892 SuggestionStyle::ShowCode,
893 )
894 } }
895
896 #[rustc_lint_diagnostics]
899 pub fn multipart_suggestion_verbose(
900 &mut self,
901 msg: impl Into<SubdiagMessage>,
902 suggestion: Vec<(Span, String)>,
903 applicability: Applicability,
904 ) -> &mut Self {
905 self.multipart_suggestion_with_style(
906 msg,
907 suggestion,
908 applicability,
909 SuggestionStyle::ShowAlways,
910 )
911 }
912
913 #[rustc_lint_diagnostics]
915 pub fn multipart_suggestion_with_style(
916 &mut self,
917 msg: impl Into<SubdiagMessage>,
918 mut suggestion: Vec<(Span, String)>,
919 applicability: Applicability,
920 style: SuggestionStyle,
921 ) -> &mut Self {
922 let mut seen = crate::FxHashSet::default();
923 suggestion.retain(|(span, msg)| seen.insert((span.lo(), span.hi(), msg.clone())));
924
925 let parts = suggestion
926 .into_iter()
927 .map(|(span, snippet)| SubstitutionPart { snippet, span })
928 .collect::<Vec<_>>();
929
930 assert!(!parts.is_empty());
931 debug_assert_eq!(
932 parts.iter().find(|part| part.span.is_empty() && part.snippet.is_empty()),
933 None,
934 "Span must not be empty and have no suggestion",
935 );
936 debug_assert_eq!(
937 parts.array_windows().find(|[a, b]| a.span.overlaps(b.span)),
938 None,
939 "suggestion must not have overlapping parts",
940 );
941
942 self.push_suggestion(CodeSuggestion {
943 substitutions: vec![Substitution { parts }],
944 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
945 style,
946 applicability,
947 });
948 self
949 }
950
951 #[rustc_lint_diagnostics]
958 pub fn tool_only_multipart_suggestion(
959 &mut self,
960 msg: impl Into<SubdiagMessage>,
961 suggestion: Vec<(Span, String)>,
962 applicability: Applicability,
963 ) -> &mut Self {
964 self.multipart_suggestion_with_style(
965 msg,
966 suggestion,
967 applicability,
968 SuggestionStyle::CompletelyHidden,
969 )
970 }
971
972 with_fn! { with_span_suggestion,
973 #[rustc_lint_diagnostics]
991 pub fn span_suggestion(
992 &mut self,
993 sp: Span,
994 msg: impl Into<SubdiagMessage>,
995 suggestion: impl ToString,
996 applicability: Applicability,
997 ) -> &mut Self {
998 self.span_suggestion_with_style(
999 sp,
1000 msg,
1001 suggestion,
1002 applicability,
1003 SuggestionStyle::ShowCode,
1004 );
1005 self
1006 } }
1007
1008 #[rustc_lint_diagnostics]
1010 pub fn span_suggestion_with_style(
1011 &mut self,
1012 sp: Span,
1013 msg: impl Into<SubdiagMessage>,
1014 suggestion: impl ToString,
1015 applicability: Applicability,
1016 style: SuggestionStyle,
1017 ) -> &mut Self {
1018 debug_assert!(
1019 !(sp.is_empty() && suggestion.to_string().is_empty()),
1020 "Span must not be empty and have no suggestion"
1021 );
1022 self.push_suggestion(CodeSuggestion {
1023 substitutions: vec![Substitution {
1024 parts: vec![SubstitutionPart { snippet: suggestion.to_string(), span: sp }],
1025 }],
1026 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
1027 style,
1028 applicability,
1029 });
1030 self
1031 }
1032
1033 with_fn! { with_span_suggestion_verbose,
1034 #[rustc_lint_diagnostics]
1036 pub fn span_suggestion_verbose(
1037 &mut self,
1038 sp: Span,
1039 msg: impl Into<SubdiagMessage>,
1040 suggestion: impl ToString,
1041 applicability: Applicability,
1042 ) -> &mut Self {
1043 self.span_suggestion_with_style(
1044 sp,
1045 msg,
1046 suggestion,
1047 applicability,
1048 SuggestionStyle::ShowAlways,
1049 );
1050 self
1051 } }
1052
1053 with_fn! { with_span_suggestions,
1054 #[rustc_lint_diagnostics]
1057 pub fn span_suggestions(
1058 &mut self,
1059 sp: Span,
1060 msg: impl Into<SubdiagMessage>,
1061 suggestions: impl IntoIterator<Item = String>,
1062 applicability: Applicability,
1063 ) -> &mut Self {
1064 self.span_suggestions_with_style(
1065 sp,
1066 msg,
1067 suggestions,
1068 applicability,
1069 SuggestionStyle::ShowCode,
1070 )
1071 } }
1072
1073 #[rustc_lint_diagnostics]
1074 pub fn span_suggestions_with_style(
1075 &mut self,
1076 sp: Span,
1077 msg: impl Into<SubdiagMessage>,
1078 suggestions: impl IntoIterator<Item = String>,
1079 applicability: Applicability,
1080 style: SuggestionStyle,
1081 ) -> &mut Self {
1082 let substitutions = suggestions
1083 .into_iter()
1084 .map(|snippet| {
1085 debug_assert!(
1086 !(sp.is_empty() && snippet.is_empty()),
1087 "Span must not be empty and have no suggestion"
1088 );
1089 Substitution { parts: vec![SubstitutionPart { snippet, span: sp }] }
1090 })
1091 .collect();
1092 self.push_suggestion(CodeSuggestion {
1093 substitutions,
1094 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
1095 style,
1096 applicability,
1097 });
1098 self
1099 }
1100
1101 #[rustc_lint_diagnostics]
1105 pub fn multipart_suggestions(
1106 &mut self,
1107 msg: impl Into<SubdiagMessage>,
1108 suggestions: impl IntoIterator<Item = Vec<(Span, String)>>,
1109 applicability: Applicability,
1110 ) -> &mut Self {
1111 let substitutions = suggestions
1112 .into_iter()
1113 .map(|sugg| {
1114 let mut parts = sugg
1115 .into_iter()
1116 .map(|(span, snippet)| SubstitutionPart { snippet, span })
1117 .collect::<Vec<_>>();
1118
1119 parts.sort_unstable_by_key(|part| part.span);
1120
1121 assert!(!parts.is_empty());
1122 debug_assert_eq!(
1123 parts.iter().find(|part| part.span.is_empty() && part.snippet.is_empty()),
1124 None,
1125 "Span must not be empty and have no suggestion",
1126 );
1127 debug_assert_eq!(
1128 parts.array_windows().find(|[a, b]| a.span.overlaps(b.span)),
1129 None,
1130 "suggestion must not have overlapping parts",
1131 );
1132
1133 Substitution { parts }
1134 })
1135 .collect();
1136
1137 self.push_suggestion(CodeSuggestion {
1138 substitutions,
1139 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
1140 style: SuggestionStyle::ShowCode,
1141 applicability,
1142 });
1143 self
1144 }
1145
1146 with_fn! { with_span_suggestion_short,
1147 #[rustc_lint_diagnostics]
1152 pub fn span_suggestion_short(
1153 &mut self,
1154 sp: Span,
1155 msg: impl Into<SubdiagMessage>,
1156 suggestion: impl ToString,
1157 applicability: Applicability,
1158 ) -> &mut Self {
1159 self.span_suggestion_with_style(
1160 sp,
1161 msg,
1162 suggestion,
1163 applicability,
1164 SuggestionStyle::HideCodeInline,
1165 );
1166 self
1167 } }
1168
1169 #[rustc_lint_diagnostics]
1176 pub fn span_suggestion_hidden(
1177 &mut self,
1178 sp: Span,
1179 msg: impl Into<SubdiagMessage>,
1180 suggestion: impl ToString,
1181 applicability: Applicability,
1182 ) -> &mut Self {
1183 self.span_suggestion_with_style(
1184 sp,
1185 msg,
1186 suggestion,
1187 applicability,
1188 SuggestionStyle::HideCodeAlways,
1189 );
1190 self
1191 }
1192
1193 with_fn! { with_tool_only_span_suggestion,
1194 #[rustc_lint_diagnostics]
1199 pub fn tool_only_span_suggestion(
1200 &mut self,
1201 sp: Span,
1202 msg: impl Into<SubdiagMessage>,
1203 suggestion: impl ToString,
1204 applicability: Applicability,
1205 ) -> &mut Self {
1206 self.span_suggestion_with_style(
1207 sp,
1208 msg,
1209 suggestion,
1210 applicability,
1211 SuggestionStyle::CompletelyHidden,
1212 );
1213 self
1214 } }
1215
1216 #[rustc_lint_diagnostics]
1221 pub fn subdiagnostic(&mut self, subdiagnostic: impl Subdiagnostic) -> &mut Self {
1222 let dcx = self.dcx;
1223 subdiagnostic.add_to_diag_with(self, &|diag, msg| {
1224 let args = diag.args.iter();
1225 let msg = diag.subdiagnostic_message_to_diagnostic_message(msg);
1226 dcx.eagerly_translate(msg, args)
1227 });
1228 self
1229 }
1230
1231 with_fn! { with_span,
1232 #[rustc_lint_diagnostics]
1234 pub fn span(&mut self, sp: impl Into<MultiSpan>) -> &mut Self {
1235 self.span = sp.into();
1236 if let Some(span) = self.span.primary_span() {
1237 self.sort_span = span;
1238 }
1239 self
1240 } }
1241
1242 #[rustc_lint_diagnostics]
1243 pub fn is_lint(&mut self, name: String, has_future_breakage: bool) -> &mut Self {
1244 self.is_lint = Some(IsLint { name, has_future_breakage });
1245 self
1246 }
1247
1248 with_fn! { with_code,
1249 #[rustc_lint_diagnostics]
1251 pub fn code(&mut self, code: ErrCode) -> &mut Self {
1252 self.code = Some(code);
1253 self
1254 } }
1255
1256 with_fn! { with_primary_message,
1257 #[rustc_lint_diagnostics]
1259 pub fn primary_message(&mut self, msg: impl Into<DiagMessage>) -> &mut Self {
1260 self.messages[0] = (msg.into(), Style::NoStyle);
1261 self
1262 } }
1263
1264 with_fn! { with_arg,
1265 #[rustc_lint_diagnostics]
1267 pub fn arg(
1268 &mut self,
1269 name: impl Into<DiagArgName>,
1270 arg: impl IntoDiagArg,
1271 ) -> &mut Self {
1272 self.deref_mut().arg(name, arg);
1273 self
1274 } }
1275
1276 pub(crate) fn subdiagnostic_message_to_diagnostic_message(
1280 &self,
1281 attr: impl Into<SubdiagMessage>,
1282 ) -> DiagMessage {
1283 self.deref().subdiagnostic_message_to_diagnostic_message(attr)
1284 }
1285
1286 pub fn sub(&mut self, level: Level, message: impl Into<SubdiagMessage>, span: MultiSpan) {
1291 self.deref_mut().sub(level, message, span);
1292 }
1293
1294 fn sub_with_highlights(&mut self, level: Level, messages: Vec<StringPart>, span: MultiSpan) {
1297 let messages = messages
1298 .into_iter()
1299 .map(|m| (self.subdiagnostic_message_to_diagnostic_message(m.content), m.style))
1300 .collect();
1301 let sub = Subdiag { level, messages, span };
1302 self.children.push(sub);
1303 }
1304
1305 fn take_diag(&mut self) -> DiagInner {
1309 if let Some(path) = &self.long_ty_path {
1310 self.note(format!(
1311 "the full name for the type has been written to '{}'",
1312 path.display()
1313 ));
1314 self.note("consider using `--verbose` to print the full type name to the console");
1315 }
1316 Box::into_inner(self.diag.take().unwrap())
1317 }
1318
1319 pub fn long_ty_path(&mut self) -> &mut Option<PathBuf> {
1337 &mut self.long_ty_path
1338 }
1339
1340 fn emit_producing_nothing(mut self) {
1342 let diag = self.take_diag();
1343 self.dcx.emit_diagnostic(diag);
1344 }
1345
1346 fn emit_producing_error_guaranteed(mut self) -> ErrorGuaranteed {
1348 let diag = self.take_diag();
1349
1350 assert!(
1359 matches!(diag.level, Level::Error | Level::DelayedBug),
1360 "invalid diagnostic level ({:?})",
1361 diag.level,
1362 );
1363
1364 let guar = self.dcx.emit_diagnostic(diag);
1365 guar.unwrap()
1366 }
1367
1368 #[track_caller]
1370 pub fn emit(self) -> G::EmitResult {
1371 G::emit_producing_guarantee(self)
1372 }
1373
1374 #[track_caller]
1379 pub fn emit_unless(mut self, delay: bool) -> G::EmitResult {
1380 if delay {
1381 self.downgrade_to_delayed_bug();
1382 }
1383 self.emit()
1384 }
1385
1386 pub fn cancel(mut self) {
1389 self.diag = None;
1390 drop(self);
1391 }
1392
1393 pub fn stash(mut self, span: Span, key: StashKey) -> Option<ErrorGuaranteed> {
1395 let diag = self.take_diag();
1396 self.dcx.stash_diagnostic(span, key, diag)
1397 }
1398
1399 #[track_caller]
1410 pub fn delay_as_bug(mut self) -> G::EmitResult {
1411 self.downgrade_to_delayed_bug();
1412 self.emit()
1413 }
1414}
1415
1416impl<G: EmissionGuarantee> Drop for Diag<'_, G> {
1419 fn drop(&mut self) {
1420 match self.diag.take() {
1421 Some(diag) if !panicking() => {
1422 self.dcx.emit_diagnostic(DiagInner::new(
1423 Level::Bug,
1424 DiagMessage::from("the following error was constructed but not emitted"),
1425 ));
1426 self.dcx.emit_diagnostic(*diag);
1427 panic!("error was constructed but not emitted");
1428 }
1429 _ => {}
1430 }
1431 }
1432}
1433
1434#[macro_export]
1435macro_rules! struct_span_code_err {
1436 ($dcx:expr, $span:expr, $code:expr, $($message:tt)*) => ({
1437 $dcx.struct_span_err($span, format!($($message)*)).with_code($code)
1438 })
1439}