rustc_errors/
diagnostic.rs

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
25/// Simplified version of `FluentArg` that can implement `Encodable` and `Decodable`. Collection of
26/// `DiagArg` are converted to `FluentArgs` (consuming the collection) at the start of diagnostic
27/// emission.
28pub type DiagArg<'iter> = (&'iter DiagArgName, &'iter DiagArgValue);
29
30/// Name of a diagnostic argument.
31pub type DiagArgName = Cow<'static, str>;
32
33/// Simplified version of `FluentValue` that can implement `Encodable` and `Decodable`. Converted
34/// to a `FluentValue` by the emitter to be used in diagnostic translation.
35#[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
36pub enum DiagArgValue {
37    Str(Cow<'static, str>),
38    // This gets converted to a `FluentNumber`, which is an `f64`. An `i32`
39    // safely fits in an `f64`. Any integers bigger than that will be converted
40    // to strings in `into_diag_arg` and stored using the `Str` variant.
41    Number(i32),
42    StrListSepByAnd(Vec<Cow<'static, str>>),
43}
44
45pub type DiagArgMap = FxIndexMap<DiagArgName, DiagArgValue>;
46
47/// Trait for types that `Diag::emit` can return as a "guarantee" (or "proof")
48/// token that the emission happened.
49pub trait EmissionGuarantee: Sized {
50    /// This exists so that bugs and fatal errors can both result in `!` (an
51    /// abort) when emitted, but have different aborting behaviour.
52    type EmitResult = Self;
53
54    /// Implementation of `Diag::emit`, fully controlled by each `impl` of
55    /// `EmissionGuarantee`, to make it impossible to create a value of
56    /// `Self::EmitResult` without actually performing the emission.
57    #[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/// Marker type which enables implementation of `create_bug` and `emit_bug` functions for
74/// bug diagnostics.
75#[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/// Marker type which enables implementation of `create_fatal` and `emit_fatal` functions for
88/// fatal diagnostics.
89#[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/// Trait implemented by error types. This is rarely implemented manually. Instead, use
109/// `#[derive(Diagnostic)]` -- see [rustc_macros::Diagnostic].
110///
111/// When implemented manually, it should be generic over the emission
112/// guarantee, i.e.:
113/// ```ignore (fragment)
114/// impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for Foo { ... }
115/// ```
116/// rather than being specific:
117/// ```ignore (fragment)
118/// impl<'a> Diagnostic<'a> for Bar { ... }  // the default type param is `ErrorGuaranteed`
119/// impl<'a> Diagnostic<'a, ()> for Baz { ... }
120/// ```
121/// There are two reasons for this.
122/// - A diagnostic like `Foo` *could* be emitted at any level -- `level` is
123///   passed in to `into_diag` from outside. Even if in practice it is
124///   always emitted at a single level, we let the diagnostic creation/emission
125///   site determine the level (by using `create_err`, `emit_warn`, etc.)
126///   rather than the `Diagnostic` impl.
127/// - Derived impls are always generic, and it's good for the hand-written
128///   impls to be consistent with them.
129#[rustc_diagnostic_item = "Diagnostic"]
130pub trait Diagnostic<'a, G: EmissionGuarantee = ErrorGuaranteed> {
131    /// Write out as a diagnostic out of `DiagCtxt`.
132    #[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
146/// Converts a value of a type into a `DiagArg` (typically a field of an `Diag` struct).
147/// Implemented as a custom trait rather than `From` so that it is implemented on the type being
148/// converted rather than on `DiagArgValue`, which enables types from other `rustc_*` crates to
149/// implement this.
150pub 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/// Trait implemented by error types. This should not be implemented manually. Instead, use
171/// `#[derive(Subdiagnostic)]` -- see [rustc_macros::Subdiagnostic].
172#[rustc_diagnostic_item = "Subdiagnostic"]
173pub trait Subdiagnostic
174where
175    Self: Sized,
176{
177    /// Add a subdiagnostic to an existing diagnostic.
178    fn add_to_diag<G: EmissionGuarantee>(self, diag: &mut Diag<'_, G>) {
179        self.add_to_diag_with(diag, &|_, m| m);
180    }
181
182    /// Add a subdiagnostic to an existing diagnostic where `f` is invoked on every message used
183    /// (to optionally perform eager translation).
184    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/// Trait implemented by lint types. This should not be implemented manually. Instead, use
195/// `#[derive(LintDiagnostic)]` -- see [rustc_macros::LintDiagnostic].
196#[rustc_diagnostic_item = "LintDiagnostic"]
197pub trait LintDiagnostic<'a, G: EmissionGuarantee> {
198    /// Decorate and emit a lint.
199    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    /// The lint name.
226    pub(crate) name: String,
227    /// Indicates whether this lint should show up in cargo's future breakage report.
228    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/// The main part of a diagnostic. Note that `Diag`, which wraps this type, is
281/// used for most operations, and should be used instead whenever possible.
282/// This type should only be used when `Diag`'s lifetime causes difficulties,
283/// e.g. when storing diagnostics within `DiagCtxt`.
284#[must_use]
285#[derive(Clone, Debug, Encodable, Decodable)]
286pub struct DiagInner {
287    // NOTE(eddyb) this is private to disallow arbitrary after-the-fact changes,
288    // outside of what methods in this crate themselves allow.
289    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    /// This is not used for highlighting or rendering any error message. Rather, it can be used
299    /// as a sort key to sort a buffer of diagnostics. By default, it is the primary span of
300    /// `span` if there is one. Otherwise, it is `DUMMY_SP`.
301    pub sort_span: Span,
302
303    pub is_lint: Option<IsLint>,
304
305    pub long_ty_path: Option<PathBuf>,
306    /// With `-Ztrack_diagnostics` enabled,
307    /// we print where in rustc this error was emitted.
308    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    /// Indicates whether this diagnostic should show up in cargo's future breakage report.
356    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    // See comment on `Diag::subdiagnostic_message_to_diagnostic_message`.
371    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    /// Fields used for Hash, and PartialEq trait.
402    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            // omit self.sort_span
423            &self.is_lint,
424            // omit self.emitted_at
425        )
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/// A "sub"-diagnostic attached to a parent diagnostic.
445/// For example, a note attached to an error.
446#[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/// Used for emitting structured error messages and other diagnostic information.
454/// Wraps a `DiagInner`, adding some useful things.
455/// - The `dcx` field, allowing it to (a) emit itself, and (b) do a drop check
456///   that it has been emitted or cancelled.
457/// - The `EmissionGuarantee`, which determines the type returned from `emit`.
458///
459/// Each constructed `Diag` must be consumed by a function such as `emit`,
460/// `cancel`, `delay_as_bug`, or `into_diag`. A panic occurs if a `Diag`
461/// is dropped without being consumed by one of these functions.
462///
463/// If there is some state in a downstream crate you would like to access in
464/// the methods of `Diag` here, consider extending `DiagCtxtFlags`.
465#[must_use]
466pub struct Diag<'a, G: EmissionGuarantee = ErrorGuaranteed> {
467    pub dcx: DiagCtxtHandle<'a>,
468
469    /// Why the `Option`? It is always `Some` until the `Diag` is consumed via
470    /// `emit`, `cancel`, etc. At that point it is consumed and replaced with
471    /// `None`. Then `drop` checks that it is `None`; if not, it panics because
472    /// a diagnostic was built but not used.
473    ///
474    /// Why the Box? `DiagInner` is a large type, and `Diag` is often used as a
475    /// return value, especially within the frequently-used `PResult` type. In
476    /// theory, return value optimization (RVO) should avoid unnecessary
477    /// copying. In practice, it does not (at the time of writing).
478    diag: Option<Box<DiagInner>>,
479
480    _marker: PhantomData<G>,
481}
482
483// Cloning a `Diag` is a recipe for a diagnostic being emitted twice, which
484// would be bad.
485impl<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
509/// `Diag` impls many `&mut self -> &mut Self` methods. Each one modifies an
510/// existing diagnostic, either in a standalone fashion, e.g.
511/// `err.code(code);`, or in a chained fashion to make multiple modifications,
512/// e.g. `err.code(code).span(span);`.
513///
514/// This macro creates an equivalent `self -> Self` method, with a `with_`
515/// prefix. This can be used in a chained fashion when making a new diagnostic,
516/// e.g. `let err = struct_err(msg).with_code(code);`, or emitting a new
517/// diagnostic, e.g. `struct_err(msg).with_code(code).emit();`.
518///
519/// Although the latter method can be used to modify an existing diagnostic,
520/// e.g. `err = err.with_code(code);`, this should be avoided because the former
521/// method gives shorter code, e.g. `err.code(code);`.
522///
523/// Note: the `with_` methods are added only when needed. If you want to use
524/// one and it's not defined, feel free to add it.
525///
526/// Note: any doc comments must be within the `with_fn!` call.
527macro_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        // The original function.
536        $(#[$attrs])*
537        #[doc = concat!("See [`Diag::", stringify!($f), "()`].")]
538        pub fn $f(&mut $self, $($name: $ty),*) -> &mut Self {
539            $($body)*
540        }
541
542        // The `with_*` variant.
543        $(#[$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    /// Allow moving diagnostics between different error tainting contexts
560    pub fn with_dcx(mut self, dcx: DiagCtxtHandle<'_>) -> Diag<'_, G> {
561        Diag { dcx, diag: self.diag.take(), _marker: PhantomData }
562    }
563
564    /// Creates a new `Diag` with an already constructed diagnostic.
565    #[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    /// Delay emission of this diagnostic as a bug.
572    ///
573    /// This can be useful in contexts where an error indicates a bug but
574    /// typically this only happens when other compilation errors have already
575    /// happened. In those cases this can be used to defer emission of this
576    /// diagnostic as a bug in the compiler only if no other errors have been
577    /// emitted.
578    ///
579    /// In the meantime, though, callsites are required to deal with the "bug"
580    /// locally in whichever way makes the most sense.
581    #[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    /// Appends a labeled span to the diagnostic.
594    ///
595    /// Labels are used to convey additional context for the diagnostic's primary span. They will
596    /// be shown together with the original diagnostic's span, *not* with spans added by
597    /// `span_note`, `span_help`, etc. Therefore, if the primary span is not displayable (because
598    /// the span is `DUMMY_SP` or the source code isn't found), labels will not be displayed
599    /// either.
600    ///
601    /// Implementation-wise, the label span is pushed onto the [`MultiSpan`] that was created when
602    /// the diagnostic was constructed. However, the label span is *not* considered a
603    /// ["primary span"][`MultiSpan`]; only the `Span` supplied when creating the diagnostic is
604    /// primary.
605    #[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    /// Labels all the given spans with the provided label.
614    /// See [`Self::span_label()`] for more information.
615    #[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        // For now, just attach these as notes.
699        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    /// Add a note attached to this diagnostic.
715    #[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    /// This is like [`Diag::note()`], but it's only printed once.
738    #[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    /// Prints the span with a note above it.
746    /// This is like [`Diag::note()`], but it gets its own span.
747    #[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    /// Prints the span with a note above it.
758    /// This is like [`Diag::note_once()`], but it gets its own span.
759    #[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    /// Add a warning attached to this diagnostic.
771    #[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    /// Prints the span with a warning above it.
778    /// This is like [`Diag::warn()`], but it gets its own span.
779    #[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    /// Add a help message attached to this diagnostic.
791    #[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    /// This is like [`Diag::help()`], but it's only printed once.
798    #[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    /// Add a help message attached to this diagnostic with a customizable highlighted message.
805    #[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    /// Add a help message attached to this diagnostic with a customizable highlighted message.
812    #[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    /// Prints the span with some help above it.
823    /// This is like [`Diag::help()`], but it gets its own span.
824    #[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    /// Disallow attaching suggestions to this diagnostic.
835    /// Any suggestions attached e.g. with the `span_suggestion_*` methods
836    /// (before and after the call to `disable_suggestions`) will be ignored.
837    #[rustc_lint_diagnostics]
838    pub fn disable_suggestions(&mut self) -> &mut Self {
839        self.suggestions = Suggestions::Disabled;
840        self
841    }
842
843    /// Prevent new suggestions from being added to this diagnostic.
844    ///
845    /// Suggestions added before the call to `.seal_suggestions()` will be preserved
846    /// and new suggestions will be ignored.
847    #[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    /// Helper for pushing to `self.suggestions`.
857    ///
858    /// A new suggestion is added if suggestions are enabled for this diagnostic.
859    /// Otherwise, they are ignored.
860    #[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                    // Ignore if spans is from derive macro.
868                    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    /// Show a suggestion that has multiple parts to it.
880    /// In other words, multiple changes need to be applied as part of this suggestion.
881    #[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    /// Show a suggestion that has multiple parts to it, always as its own subdiagnostic.
897    /// In other words, multiple changes need to be applied as part of this suggestion.
898    #[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    /// [`Diag::multipart_suggestion()`] but you can set the [`SuggestionStyle`].
914    #[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    /// Prints out a message with for a multipart suggestion without showing the suggested code.
952    ///
953    /// This is intended to be used for suggestions that are obvious in what the changes need to
954    /// be from the message, showing the span label inline would be visually unpleasant
955    /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
956    /// improve understandability.
957    #[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    /// Prints out a message with a suggested edit of the code.
974    ///
975    /// In case of short messages and a simple suggestion, rustc displays it as a label:
976    ///
977    /// ```text
978    /// try adding parentheses: `(tup.0).1`
979    /// ```
980    ///
981    /// The message
982    ///
983    /// * should not end in any punctuation (a `:` is added automatically)
984    /// * should not be a question (avoid language like "did you mean")
985    /// * should not contain any phrases like "the following", "as shown", etc.
986    /// * may look like "to do xyz, use" or "to do xyz, use abc"
987    /// * may contain a name of a function, variable, or type, but not whole expressions
988    ///
989    /// See `CodeSuggestion` for more information.
990    #[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    /// [`Diag::span_suggestion()`] but you can set the [`SuggestionStyle`].
1009    #[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    /// Always show the suggested change.
1035    #[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    /// Prints out a message with multiple suggested edits of the code.
1055    /// See also [`Diag::span_suggestion()`].
1056    #[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    /// Prints out a message with multiple suggested edits of the code, where each edit consists of
1102    /// multiple parts.
1103    /// See also [`Diag::multipart_suggestion()`].
1104    #[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    /// Prints out a message with a suggested edit of the code. If the suggestion is presented
1148    /// inline, it will only show the message and not the suggestion.
1149    ///
1150    /// See `CodeSuggestion` for more information.
1151    #[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    /// Prints out a message for a suggestion without showing the suggested code.
1170    ///
1171    /// This is intended to be used for suggestions that are obvious in what the changes need to
1172    /// be from the message, showing the span label inline would be visually unpleasant
1173    /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
1174    /// improve understandability.
1175    #[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    /// Adds a suggestion to the JSON output that will not be shown in the CLI.
1195    ///
1196    /// This is intended to be used for suggestions that are *very* obvious in what the changes
1197    /// need to be from the message, but we still want other tools to be able to apply them.
1198    #[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    /// Add a subdiagnostic from a type that implements `Subdiagnostic` (see
1217    /// [rustc_macros::Subdiagnostic]). Performs eager translation of any translatable messages
1218    /// used in the subdiagnostic, so suitable for use with repeated messages (i.e. re-use of
1219    /// interpolated variables).
1220    #[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    /// Add a span.
1233    #[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    /// Add an error code.
1250    #[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    /// Add a primary message.
1258    #[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    /// Add an argument.
1266    #[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    /// Helper function that takes a `SubdiagMessage` and returns a `DiagMessage` by
1277    /// combining it with the primary message of the diagnostic (if translatable, otherwise it just
1278    /// passes the user's string along).
1279    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    /// Convenience function for internal use, clients should use one of the
1287    /// public methods above.
1288    ///
1289    /// Used by `proc_macro_server` for implementing `server::Diagnostic`.
1290    pub fn sub(&mut self, level: Level, message: impl Into<SubdiagMessage>, span: MultiSpan) {
1291        self.deref_mut().sub(level, message, span);
1292    }
1293
1294    /// Convenience function for internal use, clients should use one of the
1295    /// public methods above.
1296    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    /// Takes the diagnostic. For use by methods that consume the Diag: `emit`,
1306    /// `cancel`, etc. Afterwards, `drop` is the only code that will be run on
1307    /// `self`.
1308    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    /// This method allows us to access the path of the file where "long types" are written to.
1320    ///
1321    /// When calling `Diag::emit`, as part of that we will check if a `long_ty_path` has been set,
1322    /// and if it has been then we add a note mentioning the file where the "long types" were
1323    /// written to.
1324    ///
1325    /// When calling `tcx.short_string()` after a `Diag` is constructed, the preferred way of doing
1326    /// so is `tcx.short_string(ty, diag.long_ty_path())`. The diagnostic itself is the one that
1327    /// keeps the existence of a "long type" anywhere in the diagnostic, so the note telling the
1328    /// user where we wrote the file to is only printed once at most, *and* it makes it much harder
1329    /// to forget to set it.
1330    ///
1331    /// If the diagnostic hasn't been created before a "short ty string" is created, then you should
1332    /// ensure that this method is called to set it `*diag.long_ty_path() = path`.
1333    ///
1334    /// As a rule of thumb, if you see or add at least one `tcx.short_string()` call anywhere, in a
1335    /// scope, `diag.long_ty_path()` should be called once somewhere close by.
1336    pub fn long_ty_path(&mut self) -> &mut Option<PathBuf> {
1337        &mut self.long_ty_path
1338    }
1339
1340    /// Most `emit_producing_guarantee` functions use this as a starting point.
1341    fn emit_producing_nothing(mut self) {
1342        let diag = self.take_diag();
1343        self.dcx.emit_diagnostic(diag);
1344    }
1345
1346    /// `ErrorGuaranteed::emit_producing_guarantee` uses this.
1347    fn emit_producing_error_guaranteed(mut self) -> ErrorGuaranteed {
1348        let diag = self.take_diag();
1349
1350        // The only error levels that produce `ErrorGuaranteed` are
1351        // `Error` and `DelayedBug`. But `DelayedBug` should never occur here
1352        // because delayed bugs have their level changed to `Bug` when they are
1353        // actually printed, so they produce an ICE.
1354        //
1355        // (Also, even though `level` isn't `pub`, the whole `DiagInner` could
1356        // be overwritten with a new one thanks to `DerefMut`. So this assert
1357        // protects against that, too.)
1358        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    /// Emit and consume the diagnostic.
1369    #[track_caller]
1370    pub fn emit(self) -> G::EmitResult {
1371        G::emit_producing_guarantee(self)
1372    }
1373
1374    /// Emit the diagnostic unless `delay` is true,
1375    /// in which case the emission will be delayed as a bug.
1376    ///
1377    /// See `emit` and `delay_as_bug` for details.
1378    #[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    /// Cancel and consume the diagnostic. (A diagnostic must either be emitted or
1387    /// cancelled or it will panic when dropped).
1388    pub fn cancel(mut self) {
1389        self.diag = None;
1390        drop(self);
1391    }
1392
1393    /// See `DiagCtxt::stash_diagnostic` for details.
1394    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    /// Delay emission of this diagnostic as a bug.
1400    ///
1401    /// This can be useful in contexts where an error indicates a bug but
1402    /// typically this only happens when other compilation errors have already
1403    /// happened. In those cases this can be used to defer emission of this
1404    /// diagnostic as a bug in the compiler only if no other errors have been
1405    /// emitted.
1406    ///
1407    /// In the meantime, though, callsites are required to deal with the "bug"
1408    /// locally in whichever way makes the most sense.
1409    #[track_caller]
1410    pub fn delay_as_bug(mut self) -> G::EmitResult {
1411        self.downgrade_to_delayed_bug();
1412        self.emit()
1413    }
1414}
1415
1416/// Destructor bomb: every `Diag` must be consumed (emitted, cancelled, etc.)
1417/// or we emit a bug.
1418impl<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}