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::{DiagArgName, DiagArgValue, IntoDiagArg};
12use rustc_lint_defs::{Applicability, LintExpectationId};
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 DiagArgMap = FxIndexMap<DiagArgName, DiagArgValue>;
26
27pub trait EmissionGuarantee: Sized {
30 type EmitResult = Self;
33
34 #[track_caller]
38 fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult;
39}
40
41impl EmissionGuarantee for ErrorGuaranteed {
42 fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult {
43 diag.emit_producing_error_guaranteed()
44 }
45}
46
47impl EmissionGuarantee for () {
48 fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult {
49 diag.emit_producing_nothing();
50 }
51}
52
53#[derive(Copy, Clone)]
56pub struct BugAbort;
57
58impl EmissionGuarantee for BugAbort {
59 type EmitResult = !;
60
61 fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult {
62 diag.emit_producing_nothing();
63 panic::panic_any(ExplicitBug);
64 }
65}
66
67#[derive(Copy, Clone)]
70pub struct FatalAbort;
71
72impl EmissionGuarantee for FatalAbort {
73 type EmitResult = !;
74
75 fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult {
76 diag.emit_producing_nothing();
77 crate::FatalError.raise()
78 }
79}
80
81impl EmissionGuarantee for rustc_span::fatal_error::FatalError {
82 fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult {
83 diag.emit_producing_nothing();
84 rustc_span::fatal_error::FatalError
85 }
86}
87
88#[rustc_diagnostic_item = "Diagnostic"]
110pub trait Diagnostic<'a, G: EmissionGuarantee = ErrorGuaranteed> {
111 #[must_use]
113 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G>;
114}
115
116impl<'a, T, G> Diagnostic<'a, G> for Spanned<T>
117where
118 T: Diagnostic<'a, G>,
119 G: EmissionGuarantee,
120{
121 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G> {
122 self.node.into_diag(dcx, level).with_span(self.span)
123 }
124}
125
126#[rustc_diagnostic_item = "Subdiagnostic"]
129pub trait Subdiagnostic
130where
131 Self: Sized,
132{
133 fn add_to_diag<G: EmissionGuarantee>(self, diag: &mut Diag<'_, G>);
135}
136
137#[rustc_diagnostic_item = "LintDiagnostic"]
140pub trait LintDiagnostic<'a, G: EmissionGuarantee> {
141 fn decorate_lint<'b>(self, diag: &'b mut Diag<'a, G>);
143}
144
145pub trait LintDiagnosticBox<'a, G: EmissionGuarantee> {
146 fn decorate_lint_box<'b>(self: Box<Self>, diag: &'b mut Diag<'a, G>);
147}
148
149impl<'a, G: EmissionGuarantee, D: LintDiagnostic<'a, G>> LintDiagnosticBox<'a, G> for D {
150 fn decorate_lint_box<'b>(self: Box<Self>, diag: &'b mut Diag<'a, G>) {
151 self.decorate_lint(diag);
152 }
153}
154
155#[derive(Clone, Debug, Encodable, Decodable)]
156pub(crate) struct DiagLocation {
157 file: Cow<'static, str>,
158 line: u32,
159 col: u32,
160}
161
162impl DiagLocation {
163 #[track_caller]
164 fn caller() -> Self {
165 let loc = panic::Location::caller();
166 DiagLocation { file: loc.file().into(), line: loc.line(), col: loc.column() }
167 }
168}
169
170impl fmt::Display for DiagLocation {
171 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172 write!(f, "{}:{}:{}", self.file, self.line, self.col)
173 }
174}
175
176#[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
177pub struct IsLint {
178 pub(crate) name: String,
180 has_future_breakage: bool,
182}
183
184#[derive(Debug, PartialEq, Eq)]
185pub struct DiagStyledString(pub Vec<StringPart>);
186
187impl DiagStyledString {
188 pub fn new() -> DiagStyledString {
189 DiagStyledString(vec![])
190 }
191 pub fn push_normal<S: Into<String>>(&mut self, t: S) {
192 self.0.push(StringPart::normal(t));
193 }
194 pub fn push_highlighted<S: Into<String>>(&mut self, t: S) {
195 self.0.push(StringPart::highlighted(t));
196 }
197 pub fn push<S: Into<String>>(&mut self, t: S, highlight: bool) {
198 if highlight {
199 self.push_highlighted(t);
200 } else {
201 self.push_normal(t);
202 }
203 }
204 pub fn normal<S: Into<String>>(t: S) -> DiagStyledString {
205 DiagStyledString(vec![StringPart::normal(t)])
206 }
207
208 pub fn highlighted<S: Into<String>>(t: S) -> DiagStyledString {
209 DiagStyledString(vec![StringPart::highlighted(t)])
210 }
211
212 pub fn content(&self) -> String {
213 self.0.iter().map(|x| x.content.as_str()).collect::<String>()
214 }
215}
216
217#[derive(Debug, PartialEq, Eq)]
218pub struct StringPart {
219 content: String,
220 style: Style,
221}
222
223impl StringPart {
224 pub fn normal<S: Into<String>>(content: S) -> StringPart {
225 StringPart { content: content.into(), style: Style::NoStyle }
226 }
227
228 pub fn highlighted<S: Into<String>>(content: S) -> StringPart {
229 StringPart { content: content.into(), style: Style::Highlight }
230 }
231}
232
233#[must_use]
238#[derive(Clone, Debug, Encodable, Decodable)]
239pub struct DiagInner {
240 pub(crate) level: Level,
243
244 pub messages: Vec<(DiagMessage, Style)>,
245 pub code: Option<ErrCode>,
246 pub lint_id: Option<LintExpectationId>,
247 pub span: MultiSpan,
248 pub children: Vec<Subdiag>,
249 pub suggestions: Suggestions,
250 pub args: DiagArgMap,
251
252 pub reserved_args: DiagArgMap,
254
255 pub sort_span: Span,
259
260 pub is_lint: Option<IsLint>,
261
262 pub long_ty_path: Option<PathBuf>,
263 pub(crate) emitted_at: DiagLocation,
266}
267
268impl DiagInner {
269 #[track_caller]
270 pub fn new<M: Into<DiagMessage>>(level: Level, message: M) -> Self {
271 DiagInner::new_with_messages(level, vec![(message.into(), Style::NoStyle)])
272 }
273
274 #[track_caller]
275 pub fn new_with_messages(level: Level, messages: Vec<(DiagMessage, Style)>) -> Self {
276 DiagInner {
277 level,
278 lint_id: None,
279 messages,
280 code: None,
281 span: MultiSpan::new(),
282 children: vec![],
283 suggestions: Suggestions::Enabled(vec![]),
284 args: Default::default(),
285 reserved_args: Default::default(),
286 sort_span: DUMMY_SP,
287 is_lint: None,
288 long_ty_path: None,
289 emitted_at: DiagLocation::caller(),
290 }
291 }
292
293 #[inline(always)]
294 pub fn level(&self) -> Level {
295 self.level
296 }
297
298 pub fn is_error(&self) -> bool {
299 match self.level {
300 Level::Bug | Level::Fatal | Level::Error | Level::DelayedBug => true,
301
302 Level::ForceWarning
303 | Level::Warning
304 | Level::Note
305 | Level::OnceNote
306 | Level::Help
307 | Level::OnceHelp
308 | Level::FailureNote
309 | Level::Allow
310 | Level::Expect => false,
311 }
312 }
313
314 pub(crate) fn has_future_breakage(&self) -> bool {
316 matches!(self.is_lint, Some(IsLint { has_future_breakage: true, .. }))
317 }
318
319 pub(crate) fn is_force_warn(&self) -> bool {
320 match self.level {
321 Level::ForceWarning => {
322 assert!(self.is_lint.is_some());
323 true
324 }
325 _ => false,
326 }
327 }
328
329 pub(crate) fn subdiagnostic_message_to_diagnostic_message(
331 &self,
332 attr: impl Into<SubdiagMessage>,
333 ) -> DiagMessage {
334 let msg =
335 self.messages.iter().map(|(msg, _)| msg).next().expect("diagnostic with no messages");
336 msg.with_subdiagnostic_message(attr.into())
337 }
338
339 pub(crate) fn sub(
340 &mut self,
341 level: Level,
342 message: impl Into<SubdiagMessage>,
343 span: MultiSpan,
344 ) {
345 let sub = Subdiag {
346 level,
347 messages: vec![(
348 self.subdiagnostic_message_to_diagnostic_message(message),
349 Style::NoStyle,
350 )],
351 span,
352 };
353 self.children.push(sub);
354 }
355
356 pub(crate) fn arg(&mut self, name: impl Into<DiagArgName>, arg: impl IntoDiagArg) {
357 let name = name.into();
358 let value = arg.into_diag_arg(&mut self.long_ty_path);
359 debug_assert!(
361 !self.args.contains_key(&name) || self.args.get(&name) == Some(&value),
362 "arg {} already exists",
363 name
364 );
365 self.args.insert(name, value);
366 }
367
368 pub fn remove_arg(&mut self, name: &str) {
369 self.args.swap_remove(name);
370 }
371
372 pub fn store_args(&mut self) {
373 self.reserved_args = self.args.clone();
374 }
375
376 pub fn restore_args(&mut self) {
377 self.args = std::mem::take(&mut self.reserved_args);
378 }
379
380 pub fn emitted_at_sub_diag(&self) -> Subdiag {
381 let track = format!("-Ztrack-diagnostics: created at {}", self.emitted_at);
382 Subdiag {
383 level: crate::Level::Note,
384 messages: vec![(DiagMessage::Str(Cow::Owned(track)), Style::NoStyle)],
385 span: MultiSpan::new(),
386 }
387 }
388
389 fn keys(
391 &self,
392 ) -> (
393 &Level,
394 &[(DiagMessage, Style)],
395 &Option<ErrCode>,
396 &MultiSpan,
397 &[Subdiag],
398 &Suggestions,
399 Vec<(&DiagArgName, &DiagArgValue)>,
400 &Option<IsLint>,
401 ) {
402 (
403 &self.level,
404 &self.messages,
405 &self.code,
406 &self.span,
407 &self.children,
408 &self.suggestions,
409 self.args.iter().collect(),
410 &self.is_lint,
412 )
414 }
415}
416
417impl Hash for DiagInner {
418 fn hash<H>(&self, state: &mut H)
419 where
420 H: Hasher,
421 {
422 self.keys().hash(state);
423 }
424}
425
426impl PartialEq for DiagInner {
427 fn eq(&self, other: &Self) -> bool {
428 self.keys() == other.keys()
429 }
430}
431
432#[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
435pub struct Subdiag {
436 pub level: Level,
437 pub messages: Vec<(DiagMessage, Style)>,
438 pub span: MultiSpan,
439}
440
441#[must_use]
454pub struct Diag<'a, G: EmissionGuarantee = ErrorGuaranteed> {
455 pub dcx: DiagCtxtHandle<'a>,
456
457 diag: Option<Box<DiagInner>>,
467
468 _marker: PhantomData<G>,
469}
470
471impl<G> !Clone for Diag<'_, G> {}
474
475rustc_data_structures::static_assert_size!(Diag<'_, ()>, 3 * size_of::<usize>());
476
477impl<G: EmissionGuarantee> Deref for Diag<'_, G> {
478 type Target = DiagInner;
479
480 fn deref(&self) -> &DiagInner {
481 self.diag.as_ref().unwrap()
482 }
483}
484
485impl<G: EmissionGuarantee> DerefMut for Diag<'_, G> {
486 fn deref_mut(&mut self) -> &mut DiagInner {
487 self.diag.as_mut().unwrap()
488 }
489}
490
491impl<G: EmissionGuarantee> Debug for Diag<'_, G> {
492 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
493 self.diag.fmt(f)
494 }
495}
496
497macro_rules! with_fn {
516 {
517 $with_f:ident,
518 $(#[$attrs:meta])*
519 pub fn $f:ident(&mut $self:ident, $($name:ident: $ty:ty),* $(,)?) -> &mut Self {
520 $($body:tt)*
521 }
522 } => {
523 $(#[$attrs])*
525 #[doc = concat!("See [`Diag::", stringify!($f), "()`].")]
526 pub fn $f(&mut $self, $($name: $ty),*) -> &mut Self {
527 $($body)*
528 }
529
530 $(#[$attrs])*
532 #[doc = concat!("See [`Diag::", stringify!($f), "()`].")]
533 pub fn $with_f(mut $self, $($name: $ty),*) -> Self {
534 $self.$f($($name),*);
535 $self
536 }
537 };
538}
539
540impl<'a, G: EmissionGuarantee> Diag<'a, G> {
541 #[rustc_lint_diagnostics]
542 #[track_caller]
543 pub fn new(dcx: DiagCtxtHandle<'a>, level: Level, message: impl Into<DiagMessage>) -> Self {
544 Self::new_diagnostic(dcx, DiagInner::new(level, message))
545 }
546
547 pub fn with_dcx(mut self, dcx: DiagCtxtHandle<'_>) -> Diag<'_, G> {
549 Diag { dcx, diag: self.diag.take(), _marker: PhantomData }
550 }
551
552 #[track_caller]
554 pub(crate) fn new_diagnostic(dcx: DiagCtxtHandle<'a>, diag: DiagInner) -> Self {
555 debug!("Created new diagnostic");
556 Self { dcx, diag: Some(Box::new(diag)), _marker: PhantomData }
557 }
558
559 #[rustc_lint_diagnostics]
570 #[track_caller]
571 pub fn downgrade_to_delayed_bug(&mut self) {
572 assert!(
573 matches!(self.level, Level::Error | Level::DelayedBug),
574 "downgrade_to_delayed_bug: cannot downgrade {:?} to DelayedBug: not an error",
575 self.level
576 );
577 self.level = Level::DelayedBug;
578 }
579
580 #[rustc_lint_diagnostics]
588 #[track_caller]
589 pub fn upgrade_to_fatal(mut self) -> Diag<'a, FatalAbort> {
590 assert!(
591 matches!(self.level, Level::Error),
592 "upgrade_to_fatal: cannot upgrade {:?} to Fatal: not an error",
593 self.level
594 );
595 self.level = Level::Fatal;
596
597 let diag = self.diag.take();
600 Diag { dcx: self.dcx, diag, _marker: PhantomData }
601 }
602
603 with_fn! { with_span_label,
604 #[rustc_lint_diagnostics]
617 pub fn span_label(&mut self, span: Span, label: impl Into<SubdiagMessage>) -> &mut Self {
618 let msg = self.subdiagnostic_message_to_diagnostic_message(label);
619 self.span.push_span_label(span, msg);
620 self
621 } }
622
623 with_fn! { with_span_labels,
624 #[rustc_lint_diagnostics]
627 pub fn span_labels(&mut self, spans: impl IntoIterator<Item = Span>, label: &str) -> &mut Self {
628 for span in spans {
629 self.span_label(span, label.to_string());
630 }
631 self
632 } }
633
634 #[rustc_lint_diagnostics]
635 pub fn replace_span_with(&mut self, after: Span, keep_label: bool) -> &mut Self {
636 let before = self.span.clone();
637 self.span(after);
638 for span_label in before.span_labels() {
639 if let Some(label) = span_label.label {
640 if span_label.is_primary && keep_label {
641 self.span.push_span_label(after, label);
642 } else {
643 self.span.push_span_label(span_label.span, label);
644 }
645 }
646 }
647 self
648 }
649
650 #[rustc_lint_diagnostics]
651 pub fn note_expected_found(
652 &mut self,
653 expected_label: &str,
654 expected: DiagStyledString,
655 found_label: &str,
656 found: DiagStyledString,
657 ) -> &mut Self {
658 self.note_expected_found_extra(
659 expected_label,
660 expected,
661 found_label,
662 found,
663 DiagStyledString::normal(""),
664 DiagStyledString::normal(""),
665 )
666 }
667
668 #[rustc_lint_diagnostics]
669 pub fn note_expected_found_extra(
670 &mut self,
671 expected_label: &str,
672 expected: DiagStyledString,
673 found_label: &str,
674 found: DiagStyledString,
675 expected_extra: DiagStyledString,
676 found_extra: DiagStyledString,
677 ) -> &mut Self {
678 let expected_label = expected_label.to_string();
679 let expected_label = if expected_label.is_empty() {
680 "expected".to_string()
681 } else {
682 format!("expected {expected_label}")
683 };
684 let found_label = found_label.to_string();
685 let found_label = if found_label.is_empty() {
686 "found".to_string()
687 } else {
688 format!("found {found_label}")
689 };
690 let (found_padding, expected_padding) = if expected_label.len() > found_label.len() {
691 (expected_label.len() - found_label.len(), 0)
692 } else {
693 (0, found_label.len() - expected_label.len())
694 };
695 let mut msg = vec![StringPart::normal(format!(
696 "{}{} `",
697 " ".repeat(expected_padding),
698 expected_label
699 ))];
700 msg.extend(expected.0);
701 msg.push(StringPart::normal(format!("`")));
702 msg.extend(expected_extra.0);
703 msg.push(StringPart::normal(format!("\n")));
704 msg.push(StringPart::normal(format!("{}{} `", " ".repeat(found_padding), found_label)));
705 msg.extend(found.0);
706 msg.push(StringPart::normal(format!("`")));
707 msg.extend(found_extra.0);
708
709 self.highlighted_note(msg);
711 self
712 }
713
714 #[rustc_lint_diagnostics]
715 pub fn note_trait_signature(&mut self, name: Symbol, signature: String) -> &mut Self {
716 self.highlighted_note(vec![
717 StringPart::normal(format!("`{name}` from trait: `")),
718 StringPart::highlighted(signature),
719 StringPart::normal("`"),
720 ]);
721 self
722 }
723
724 with_fn! { with_note,
725 #[rustc_lint_diagnostics]
727 pub fn note(&mut self, msg: impl Into<SubdiagMessage>) -> &mut Self {
728 self.sub(Level::Note, msg, MultiSpan::new());
729 self
730 } }
731
732 #[rustc_lint_diagnostics]
733 pub fn highlighted_note(&mut self, msg: Vec<StringPart>) -> &mut Self {
734 self.sub_with_highlights(Level::Note, msg, MultiSpan::new());
735 self
736 }
737
738 #[rustc_lint_diagnostics]
739 pub fn highlighted_span_note(
740 &mut self,
741 span: impl Into<MultiSpan>,
742 msg: Vec<StringPart>,
743 ) -> &mut Self {
744 self.sub_with_highlights(Level::Note, msg, span.into());
745 self
746 }
747
748 #[rustc_lint_diagnostics]
750 pub fn note_once(&mut self, msg: impl Into<SubdiagMessage>) -> &mut Self {
751 self.sub(Level::OnceNote, msg, MultiSpan::new());
752 self
753 }
754
755 with_fn! { with_span_note,
756 #[rustc_lint_diagnostics]
759 pub fn span_note(
760 &mut self,
761 sp: impl Into<MultiSpan>,
762 msg: impl Into<SubdiagMessage>,
763 ) -> &mut Self {
764 self.sub(Level::Note, msg, sp.into());
765 self
766 } }
767
768 #[rustc_lint_diagnostics]
771 pub fn span_note_once<S: Into<MultiSpan>>(
772 &mut self,
773 sp: S,
774 msg: impl Into<SubdiagMessage>,
775 ) -> &mut Self {
776 self.sub(Level::OnceNote, msg, sp.into());
777 self
778 }
779
780 with_fn! { with_warn,
781 #[rustc_lint_diagnostics]
783 pub fn warn(&mut self, msg: impl Into<SubdiagMessage>) -> &mut Self {
784 self.sub(Level::Warning, msg, MultiSpan::new());
785 self
786 } }
787
788 #[rustc_lint_diagnostics]
791 pub fn span_warn<S: Into<MultiSpan>>(
792 &mut self,
793 sp: S,
794 msg: impl Into<SubdiagMessage>,
795 ) -> &mut Self {
796 self.sub(Level::Warning, msg, sp.into());
797 self
798 }
799
800 with_fn! { with_help,
801 #[rustc_lint_diagnostics]
803 pub fn help(&mut self, msg: impl Into<SubdiagMessage>) -> &mut Self {
804 self.sub(Level::Help, msg, MultiSpan::new());
805 self
806 } }
807
808 #[rustc_lint_diagnostics]
810 pub fn help_once(&mut self, msg: impl Into<SubdiagMessage>) -> &mut Self {
811 self.sub(Level::OnceHelp, msg, MultiSpan::new());
812 self
813 }
814
815 #[rustc_lint_diagnostics]
817 pub fn highlighted_help(&mut self, msg: Vec<StringPart>) -> &mut Self {
818 self.sub_with_highlights(Level::Help, msg, MultiSpan::new());
819 self
820 }
821
822 #[rustc_lint_diagnostics]
824 pub fn highlighted_span_help(
825 &mut self,
826 span: impl Into<MultiSpan>,
827 msg: Vec<StringPart>,
828 ) -> &mut Self {
829 self.sub_with_highlights(Level::Help, msg, span.into());
830 self
831 }
832
833 with_fn! { with_span_help,
834 #[rustc_lint_diagnostics]
837 pub fn span_help(
838 &mut self,
839 sp: impl Into<MultiSpan>,
840 msg: impl Into<SubdiagMessage>,
841 ) -> &mut Self {
842 self.sub(Level::Help, msg, sp.into());
843 self
844 } }
845
846 #[rustc_lint_diagnostics]
850 pub fn disable_suggestions(&mut self) -> &mut Self {
851 self.suggestions = Suggestions::Disabled;
852 self
853 }
854
855 #[rustc_lint_diagnostics]
860 pub fn seal_suggestions(&mut self) -> &mut Self {
861 if let Suggestions::Enabled(suggestions) = &mut self.suggestions {
862 let suggestions_slice = std::mem::take(suggestions).into_boxed_slice();
863 self.suggestions = Suggestions::Sealed(suggestions_slice);
864 }
865 self
866 }
867
868 #[rustc_lint_diagnostics]
873 fn push_suggestion(&mut self, suggestion: CodeSuggestion) {
874 for subst in &suggestion.substitutions {
875 for part in &subst.parts {
876 let span = part.span;
877 let call_site = span.ctxt().outer_expn_data().call_site;
878 if span.in_derive_expansion() && span.overlaps_or_adjacent(call_site) {
879 return;
881 }
882 }
883 }
884
885 if let Suggestions::Enabled(suggestions) = &mut self.suggestions {
886 suggestions.push(suggestion);
887 }
888 }
889
890 with_fn! { with_multipart_suggestion,
891 #[rustc_lint_diagnostics]
894 pub fn multipart_suggestion(
895 &mut self,
896 msg: impl Into<SubdiagMessage>,
897 suggestion: Vec<(Span, String)>,
898 applicability: Applicability,
899 ) -> &mut Self {
900 self.multipart_suggestion_with_style(
901 msg,
902 suggestion,
903 applicability,
904 SuggestionStyle::ShowCode,
905 )
906 } }
907
908 #[rustc_lint_diagnostics]
911 pub fn multipart_suggestion_verbose(
912 &mut self,
913 msg: impl Into<SubdiagMessage>,
914 suggestion: Vec<(Span, String)>,
915 applicability: Applicability,
916 ) -> &mut Self {
917 self.multipart_suggestion_with_style(
918 msg,
919 suggestion,
920 applicability,
921 SuggestionStyle::ShowAlways,
922 )
923 }
924
925 #[rustc_lint_diagnostics]
927 pub fn multipart_suggestion_with_style(
928 &mut self,
929 msg: impl Into<SubdiagMessage>,
930 mut suggestion: Vec<(Span, String)>,
931 applicability: Applicability,
932 style: SuggestionStyle,
933 ) -> &mut Self {
934 let mut seen = crate::FxHashSet::default();
935 suggestion.retain(|(span, msg)| seen.insert((span.lo(), span.hi(), msg.clone())));
936
937 let parts = suggestion
938 .into_iter()
939 .map(|(span, snippet)| SubstitutionPart { snippet, span })
940 .collect::<Vec<_>>();
941
942 assert!(!parts.is_empty());
943 debug_assert_eq!(
944 parts.iter().find(|part| part.span.is_empty() && part.snippet.is_empty()),
945 None,
946 "Span must not be empty and have no suggestion",
947 );
948
949 self.push_suggestion(CodeSuggestion {
950 substitutions: vec![Substitution { parts }],
951 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
952 style,
953 applicability,
954 });
955 self
956 }
957
958 #[rustc_lint_diagnostics]
965 pub fn tool_only_multipart_suggestion(
966 &mut self,
967 msg: impl Into<SubdiagMessage>,
968 suggestion: Vec<(Span, String)>,
969 applicability: Applicability,
970 ) -> &mut Self {
971 self.multipart_suggestion_with_style(
972 msg,
973 suggestion,
974 applicability,
975 SuggestionStyle::CompletelyHidden,
976 )
977 }
978
979 with_fn! { with_span_suggestion,
980 #[rustc_lint_diagnostics]
998 pub fn span_suggestion(
999 &mut self,
1000 sp: Span,
1001 msg: impl Into<SubdiagMessage>,
1002 suggestion: impl ToString,
1003 applicability: Applicability,
1004 ) -> &mut Self {
1005 self.span_suggestion_with_style(
1006 sp,
1007 msg,
1008 suggestion,
1009 applicability,
1010 SuggestionStyle::ShowCode,
1011 );
1012 self
1013 } }
1014
1015 #[rustc_lint_diagnostics]
1017 pub fn span_suggestion_with_style(
1018 &mut self,
1019 sp: Span,
1020 msg: impl Into<SubdiagMessage>,
1021 suggestion: impl ToString,
1022 applicability: Applicability,
1023 style: SuggestionStyle,
1024 ) -> &mut Self {
1025 debug_assert!(
1026 !(sp.is_empty() && suggestion.to_string().is_empty()),
1027 "Span must not be empty and have no suggestion"
1028 );
1029 self.push_suggestion(CodeSuggestion {
1030 substitutions: vec![Substitution {
1031 parts: vec![SubstitutionPart { snippet: suggestion.to_string(), span: sp }],
1032 }],
1033 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
1034 style,
1035 applicability,
1036 });
1037 self
1038 }
1039
1040 with_fn! { with_span_suggestion_verbose,
1041 #[rustc_lint_diagnostics]
1043 pub fn span_suggestion_verbose(
1044 &mut self,
1045 sp: Span,
1046 msg: impl Into<SubdiagMessage>,
1047 suggestion: impl ToString,
1048 applicability: Applicability,
1049 ) -> &mut Self {
1050 self.span_suggestion_with_style(
1051 sp,
1052 msg,
1053 suggestion,
1054 applicability,
1055 SuggestionStyle::ShowAlways,
1056 );
1057 self
1058 } }
1059
1060 with_fn! { with_span_suggestions,
1061 #[rustc_lint_diagnostics]
1064 pub fn span_suggestions(
1065 &mut self,
1066 sp: Span,
1067 msg: impl Into<SubdiagMessage>,
1068 suggestions: impl IntoIterator<Item = String>,
1069 applicability: Applicability,
1070 ) -> &mut Self {
1071 self.span_suggestions_with_style(
1072 sp,
1073 msg,
1074 suggestions,
1075 applicability,
1076 SuggestionStyle::ShowCode,
1077 )
1078 } }
1079
1080 #[rustc_lint_diagnostics]
1081 pub fn span_suggestions_with_style(
1082 &mut self,
1083 sp: Span,
1084 msg: impl Into<SubdiagMessage>,
1085 suggestions: impl IntoIterator<Item = String>,
1086 applicability: Applicability,
1087 style: SuggestionStyle,
1088 ) -> &mut Self {
1089 let substitutions = suggestions
1090 .into_iter()
1091 .map(|snippet| {
1092 debug_assert!(
1093 !(sp.is_empty() && snippet.is_empty()),
1094 "Span `{sp:?}` must not be empty and have no suggestion"
1095 );
1096 Substitution { parts: vec![SubstitutionPart { snippet, span: sp }] }
1097 })
1098 .collect();
1099 self.push_suggestion(CodeSuggestion {
1100 substitutions,
1101 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
1102 style,
1103 applicability,
1104 });
1105 self
1106 }
1107
1108 #[rustc_lint_diagnostics]
1112 pub fn multipart_suggestions(
1113 &mut self,
1114 msg: impl Into<SubdiagMessage>,
1115 suggestions: impl IntoIterator<Item = Vec<(Span, String)>>,
1116 applicability: Applicability,
1117 ) -> &mut Self {
1118 let substitutions = suggestions
1119 .into_iter()
1120 .map(|sugg| {
1121 let mut parts = sugg
1122 .into_iter()
1123 .map(|(span, snippet)| SubstitutionPart { snippet, span })
1124 .collect::<Vec<_>>();
1125
1126 parts.sort_unstable_by_key(|part| part.span);
1127
1128 assert!(!parts.is_empty());
1129 debug_assert_eq!(
1130 parts.iter().find(|part| part.span.is_empty() && part.snippet.is_empty()),
1131 None,
1132 "Span must not be empty and have no suggestion",
1133 );
1134 debug_assert_eq!(
1135 parts.array_windows().find(|[a, b]| a.span.overlaps(b.span)),
1136 None,
1137 "suggestion must not have overlapping parts",
1138 );
1139
1140 Substitution { parts }
1141 })
1142 .collect();
1143
1144 self.push_suggestion(CodeSuggestion {
1145 substitutions,
1146 msg: self.subdiagnostic_message_to_diagnostic_message(msg),
1147 style: SuggestionStyle::ShowAlways,
1148 applicability,
1149 });
1150 self
1151 }
1152
1153 with_fn! { with_span_suggestion_short,
1154 #[rustc_lint_diagnostics]
1159 pub fn span_suggestion_short(
1160 &mut self,
1161 sp: Span,
1162 msg: impl Into<SubdiagMessage>,
1163 suggestion: impl ToString,
1164 applicability: Applicability,
1165 ) -> &mut Self {
1166 self.span_suggestion_with_style(
1167 sp,
1168 msg,
1169 suggestion,
1170 applicability,
1171 SuggestionStyle::HideCodeInline,
1172 );
1173 self
1174 } }
1175
1176 #[rustc_lint_diagnostics]
1183 pub fn span_suggestion_hidden(
1184 &mut self,
1185 sp: Span,
1186 msg: impl Into<SubdiagMessage>,
1187 suggestion: impl ToString,
1188 applicability: Applicability,
1189 ) -> &mut Self {
1190 self.span_suggestion_with_style(
1191 sp,
1192 msg,
1193 suggestion,
1194 applicability,
1195 SuggestionStyle::HideCodeAlways,
1196 );
1197 self
1198 }
1199
1200 with_fn! { with_tool_only_span_suggestion,
1201 #[rustc_lint_diagnostics]
1206 pub fn tool_only_span_suggestion(
1207 &mut self,
1208 sp: Span,
1209 msg: impl Into<SubdiagMessage>,
1210 suggestion: impl ToString,
1211 applicability: Applicability,
1212 ) -> &mut Self {
1213 self.span_suggestion_with_style(
1214 sp,
1215 msg,
1216 suggestion,
1217 applicability,
1218 SuggestionStyle::CompletelyHidden,
1219 );
1220 self
1221 } }
1222
1223 #[rustc_lint_diagnostics]
1228 pub fn subdiagnostic(&mut self, subdiagnostic: impl Subdiagnostic) -> &mut Self {
1229 subdiagnostic.add_to_diag(self);
1230 self
1231 }
1232
1233 pub fn eagerly_translate(&self, msg: impl Into<SubdiagMessage>) -> SubdiagMessage {
1239 let args = self.args.iter();
1240 let msg = self.subdiagnostic_message_to_diagnostic_message(msg.into());
1241 self.dcx.eagerly_translate(msg, args)
1242 }
1243
1244 with_fn! { with_span,
1245 #[rustc_lint_diagnostics]
1247 pub fn span(&mut self, sp: impl Into<MultiSpan>) -> &mut Self {
1248 self.span = sp.into();
1249 if let Some(span) = self.span.primary_span() {
1250 self.sort_span = span;
1251 }
1252 self
1253 } }
1254
1255 #[rustc_lint_diagnostics]
1256 pub fn is_lint(&mut self, name: String, has_future_breakage: bool) -> &mut Self {
1257 self.is_lint = Some(IsLint { name, has_future_breakage });
1258 self
1259 }
1260
1261 with_fn! { with_code,
1262 #[rustc_lint_diagnostics]
1264 pub fn code(&mut self, code: ErrCode) -> &mut Self {
1265 self.code = Some(code);
1266 self
1267 } }
1268
1269 with_fn! { with_lint_id,
1270 #[rustc_lint_diagnostics]
1272 pub fn lint_id(
1273 &mut self,
1274 id: LintExpectationId,
1275 ) -> &mut Self {
1276 self.lint_id = Some(id);
1277 self
1278 } }
1279
1280 with_fn! { with_primary_message,
1281 #[rustc_lint_diagnostics]
1283 pub fn primary_message(&mut self, msg: impl Into<DiagMessage>) -> &mut Self {
1284 self.messages[0] = (msg.into(), Style::NoStyle);
1285 self
1286 } }
1287
1288 with_fn! { with_arg,
1289 #[rustc_lint_diagnostics]
1291 pub fn arg(
1292 &mut self,
1293 name: impl Into<DiagArgName>,
1294 arg: impl IntoDiagArg,
1295 ) -> &mut Self {
1296 self.deref_mut().arg(name, arg);
1297 self
1298 } }
1299
1300 pub(crate) fn subdiagnostic_message_to_diagnostic_message(
1304 &self,
1305 attr: impl Into<SubdiagMessage>,
1306 ) -> DiagMessage {
1307 self.deref().subdiagnostic_message_to_diagnostic_message(attr)
1308 }
1309
1310 pub fn sub(&mut self, level: Level, message: impl Into<SubdiagMessage>, span: MultiSpan) {
1315 self.deref_mut().sub(level, message, span);
1316 }
1317
1318 fn sub_with_highlights(&mut self, level: Level, messages: Vec<StringPart>, span: MultiSpan) {
1321 let messages = messages
1322 .into_iter()
1323 .map(|m| (self.subdiagnostic_message_to_diagnostic_message(m.content), m.style))
1324 .collect();
1325 let sub = Subdiag { level, messages, span };
1326 self.children.push(sub);
1327 }
1328
1329 fn take_diag(&mut self) -> DiagInner {
1333 if let Some(path) = &self.long_ty_path {
1334 self.note(format!(
1335 "the full name for the type has been written to '{}'",
1336 path.display()
1337 ));
1338 self.note("consider using `--verbose` to print the full type name to the console");
1339 }
1340 *self.diag.take().unwrap()
1341 }
1342
1343 pub fn long_ty_path(&mut self) -> &mut Option<PathBuf> {
1361 &mut self.long_ty_path
1362 }
1363
1364 pub fn with_long_ty_path(mut self, long_ty_path: Option<PathBuf>) -> Self {
1365 self.long_ty_path = long_ty_path;
1366 self
1367 }
1368
1369 fn emit_producing_nothing(mut self) {
1371 let diag = self.take_diag();
1372 self.dcx.emit_diagnostic(diag);
1373 }
1374
1375 fn emit_producing_error_guaranteed(mut self) -> ErrorGuaranteed {
1377 let diag = self.take_diag();
1378
1379 assert!(
1388 matches!(diag.level, Level::Error | Level::DelayedBug),
1389 "invalid diagnostic level ({:?})",
1390 diag.level,
1391 );
1392
1393 let guar = self.dcx.emit_diagnostic(diag);
1394 guar.unwrap()
1395 }
1396
1397 #[track_caller]
1399 pub fn emit(self) -> G::EmitResult {
1400 G::emit_producing_guarantee(self)
1401 }
1402
1403 #[track_caller]
1408 pub fn emit_unless_delay(mut self, delay: bool) -> G::EmitResult {
1409 if delay {
1410 self.downgrade_to_delayed_bug();
1411 }
1412 self.emit()
1413 }
1414
1415 pub fn cancel(mut self) {
1418 self.diag = None;
1419 drop(self);
1420 }
1421
1422 pub fn stash(mut self, span: Span, key: StashKey) -> Option<ErrorGuaranteed> {
1424 let diag = self.take_diag();
1425 self.dcx.stash_diagnostic(span, key, diag)
1426 }
1427
1428 #[track_caller]
1439 pub fn delay_as_bug(mut self) -> G::EmitResult {
1440 self.downgrade_to_delayed_bug();
1441 self.emit()
1442 }
1443
1444 pub fn remove_arg(&mut self, name: &str) {
1445 if let Some(diag) = self.diag.as_mut() {
1446 diag.remove_arg(name);
1447 }
1448 }
1449}
1450
1451impl<G: EmissionGuarantee> Drop for Diag<'_, G> {
1454 fn drop(&mut self) {
1455 match self.diag.take() {
1456 Some(diag) if !panicking() => {
1457 self.dcx.emit_diagnostic(DiagInner::new(
1458 Level::Bug,
1459 DiagMessage::from("the following error was constructed but not emitted"),
1460 ));
1461 self.dcx.emit_diagnostic(*diag);
1462 panic!("error was constructed but not emitted");
1463 }
1464 _ => {}
1465 }
1466 }
1467}
1468
1469#[macro_export]
1470macro_rules! struct_span_code_err {
1471 ($dcx:expr, $span:expr, $code:expr, $($message:tt)*) => ({
1472 $dcx.struct_span_err($span, format!($($message)*)).with_code($code)
1473 })
1474}